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

21 - 函数式组件

Open kalu5 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, { slots, emit, attrs }) => {
  
  const { list, activeIndex } = props
  
  return h(
    'ul',
    list.map((item,index) => {
      return h(
        'li',
        {
          key: index,
          style: {
            width: '200px',
            height: '40px',
            border: '1px solid red',
            backgroundColor: index === activeIndex ? 'red' : ''
          },
          onClick: () => {
            emit('toggle', index)
          }
        },
        item
        )
    })
  )
}

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

const activeIndex = ref(0)

function toggle(index: number) {
  activeIndex.value = index
}
  
ListComponent.props = ['list', 'activeIndex']
  
</script>

<template>
  <list-component
    :list="list"
    :active-index="activeIndex"
    @toggle="toggle"
  />
</template>

kalu5 avatar Sep 16 '22 09:09 kalu5