Skip to content

21 - 函数式组件 #1845

Open
Open
@yeyongc

Description

@yeyongc
<script setup lang='ts'>

import { ref, h } from "vue"

/**
 * 实现该函数式组件 :
 * 1. 使用`list`数据渲染列表元素 (ul/li)
 * 2. 当点击列表子元素时,将其文本颜色更改为红色
*/
const ListComponent = () => {
    return h('ul', {}, list.map((item, idx) => {
         return h('li', {
            onClick(){
                toggle(idx)
            },
            style:{
               color: idx === activeIndex.value ? 'red' : 'black'
            }
         }, item.name)
    }))
}

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>

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions