函数式组件是一种定义自身没有任何状态的组件的方式。它们就像纯函数:接受props,返回vnodes。函数式组件在渲染过程中不会创建组件实例(也就是说,没有this),也不会触发常规的组件生命周期钩子。
下面用一个例子来学习函数式组件:
<script setup lang='ts'>
import { ref ,h} from "vue"
/**
* 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.
*/
const ListComponent = (props, { emit }) => {
const children = []
props.list.map((item,index)=>{
children.push(
h('li', {
style: {
color: index === props['active-index'] ? 'red' : '#333'
},
onClick:()=>{
emit('toggle',index)
}},item.name)
)
})
return h('ul',children)
}
const list = [{
name: "John",
}, {
name: "Doe",
}, {
name: "Smith",
}]
const activeIndex = ref(0)
function toggle(index: number) {
activeIndex.value = index
}
</script>
<template>
<list-component
:list="list"
:active-index="activeIndex"
@toggle="toggle"
/>
</template>
该例子实现的效果是点击文字时,文字会变为红色