vuejs-challenges
vuejs-challenges copied to clipboard
21 - 函数式组件
<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 childrens = props.list.reduce((res, item, index)=> {
return [
...res,
h('li',{
key: index,
dataIndex: index,
style: Number(props.activeIndex) === index ? {'color': 'red'} : null
},item.name)
]
},[])
return h('ul',{
onClick:(ev)=>{
const clickIndex = ev.target.getAttribute('dataIndex')
emit('toggle',clickIndex)
}
},childrens)
}
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"
:activeIndex="activeIndex"
@toggle="toggle"
/>
</template>