Skip to content

21 - 函数式组件 #1983

Open
Open
@gaoshunpeng

Description

@gaoshunpeng

求助

为啥我这样就不行?报错:Cannot read properties of undefined (reading '__asyncLoader'),参考的 官方写法
因为不知道为啥 jsx 识别不了,就改为了 h 渲染函数

<script setup lang='ts'>

import { ref, FunctionalComponent, 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.
*/
interface Item {
  name: string
} 

type FComponentProps = {
  list: Item[]
  activeIndex: number
}

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


const ListComponent: FunctionalComponent<FComponentProps, Events> = (props, context) => {
  return h('ul', {}, props.list.map((item, index) => h('li', {
    style: {
      color: props['active-index'] == index ? 'red' : ''
    },
    onclick: () => context.emit('toggle', index)
  }, item.name)))
}

ListComponent.props = {
  list: {
    type: Object,
    required: true
  },
  activeIndex: {
    type: Number,
    required: true
  }
}

ListComponent.emits = {
  toggle: (index) => typeof index === 'number'
}


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