vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

21 - 函数式组件

Open PoliWen opened this issue 2 years ago • 0 comments

<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>

PoliWen avatar Sep 10 '22 02:09 PoliWen