webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.71k stars 187 forks source link

21 - 函数式组件 tsx解法 #2807

Open Tofu-Xx opened 1 month ago

Tofu-Xx commented 1 month ago
<script setup lang='tsx'>
import { ref } 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 = ({ list, activeIndex }, { emit }) => (
  <ul>{
    list.map(({ name }, i) => (
      <li style={{ color: (activeIndex == i) ? 'red' : null }} onClick={() => { emit('toggle', i) }}> {
        name
      } </li>
    ))
  } </ul>
)

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

const activeIndex = ref(0)

function toggle(index: number) {
  activeIndex.value = index
}
</script>

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