Skip to content

21 - 函数式组件 #3046

@silence1996

Description

@silence1996

`<script setup lang='ts'>

import { ref, h } from "vue"
import type { FunctionalComponent } from 'vue'

type ListObj = {
name: string
}

type ListComponentProps = {
list?: Array,
activeIndex?: number
}

type ListComponentEvent = {
toggle(index: number): void
}

/**

  • Implement a functional component :
    1. Render the list elements (ul/li) with the list data
    1. Change the list item text color to red when clicked.
      */
      const ListComponent: FunctionalComponent<ListComponentProps, ListComponentEvent> = (props, context) => {
      return h('ul', props.list.map((item, i) => h(
      'li',
      {
      key: i,
      style: Object.assign({ cursor: 'pointer' }, props['active-index'] === i && { color: 'red' }),
      onClick: () => context.emit('toggle', i)
      },
      item.name
      )))
      }
      ListComponent.displayName = 'ListComponent'

const list: Array = [{
name: "John",
}, {
name: "Doe",
}, {
name: "Smith",
}]

const activeIndex = ref(0)

function toggle(index: number) {
activeIndex.value = index
}

</script> `

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions