I discovered functional components while training for the level 1 certification of Vue.js. While I might not use it every day as it is very verbose, I’d like to share an example in this article.
I’ll be 100% honest: functional component is another level. It uses the render function h() in Vue.js.
I believe it’s what Vue uses under the hood to convert your SFC (Single File Component) or In-Template code to Virtual DOM nodes.
//Using TypeScrit and Composition API
import{ref,h}from"vue";// To type the list of items
typeUser={name: String;};// To type the props
typeProps={list: User[];activeIndex: number;};// To type the events ( e.g. emit)
typeEvents={toogle(index: number):void;};/**
* The challenge > Implement a functional component :
* 1. Render the list elements (ul/li) with the list data
* 2. Change the list item text color to red when clicked.
*/constListComponent=(props: Props,{emit})=>{returnh("ul",// create a ul element
props.list.map((item: User,index)=>h(// loop the list prop (equivalent to v-for)
"li",// ... to create an li element for each element
{// ... with the mandatory key attribute
key: index,// ... with the inline style to set the text to red
// when the current index is equal to activeIndex prop
style: index==props.activeIndex?{color:"red"}:null,// ... with the assignment of the node `innerText` value
innerText: item.name,// ... and attaching the onclick handler with the toggle emit
onClick:()=>emit("toggle",index),})));};// This lists the props of the component,
// but doesn't define it. See above type.
ListComponent.props=["list","active-index"];// This lists the events handled by the component,
// but doesn't define it. See above type.
ListComponent.emits=["toggle"];constlist: User[]=[{name:"John",},{name:"Doe",},{name:"Smith",},];constactiveIndex=ref(0);functiontoggle(index: number){activeIndex.value=index;}
Now, you understand Vue.js a bit more in depth.
As for the template, the usage is unchanged to a regular SFC.