Skip to content

21 - 函数式组件 #1798

Open
Open
@chen-ziwen

Description

@chen-ziwen
<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 c = props.list.map((item,index)=>{
    return h(
    "li",{
      style:{
        color:props['active-index'] === index?'lightblue':'gray',
      },
      onClick:()=>{
        emit('toggle',index);
      }
    },
      item.name
    )
  })
  return h('ul',c)
}

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