Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

21 - 函数式组件 #407

Closed
bladeyon opened this issue Jul 8, 2022 · 0 comments
Closed

21 - 函数式组件 #407

bladeyon opened this issue Jul 8, 2022 · 0 comments

Comments

@bladeyon
Copy link

bladeyon commented Jul 8, 2022

<script setup lang="ts">
import { ref, h } from "vue";

/**
 * 实现该函数式组件 :
 * 1. 使用`list`数据渲染列表元素 (ul/li)
 * 2. 当点击列表子元素时,将其文本颜色更改为红色
 */
const ListComponent = (props, { emit }) => {
  const { list } = props;
  const children = list.map((item, idx) => {
    return h(
      "li",
      { "data-id": idx, class: props["active-index"] === idx ? "red" : "" },
      item.name
    );
  });

  return h(
    "ul",
    {
      onClick(e) {
        let id = e.target.dataset.id;
        emit("toggle", +id);
      }
    },
    children
  );
};

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>

<style>
ul li.red {
  color: red;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant