Open
Description
// 你的答案
<template>
<!-- 将 ListComponent 组件绑定到模板 -->
<list-component :list="list" :active-index="activeIndex" @toggle="toggle" />
<Hslist />
</template>
<script setup>
import { ref, h } from 'vue'; // 从 'vue' 中导入 ref 和 h
// 定义一个名为 ListComponent 的函数组件
const ListComponent = (props, { emit }) => {
console.log(emit)
const toggle = (index) => {
console.log(index); // 打印当前点击的列表项的索引
emit('toggle', index); // 当列表项被点击时,发出名为 "toggle" 的自定义事件
};
// 使用 map 方法遍历列表数据,并为每个数据项创建一个 <li> 元素
let li = props.list.map((item, index) =>
h(
'li', {
style: index === props['active-index'] ? { color: 'yellow' } : null, // 如果当前列表项是选中的,将其文本颜色设置为黄色
onClick: () => toggle(index), // 为 <li> 元素添加点击事件处理函数
},
item.name
)
);
// 返回包含列表项的 <ul> 元素
return h('ul', {}, li);
};
// 定义一个名为 list 的响应式引用,用于存储列表数据
const list = [
{
name: 'John',
},
{
name: 'Doe',
},
{
name: 'Smith',
},
];
// 定义一个名为 activeIndex 的响应式引用,用于存储当前选中的列表项的索引
const activeIndex = ref(0);
// 定义一个名为 toggle 的函数,用于处理 "toggle" 事件的回调函数
function toggle(index) {
activeIndex.value = index; // 更新 activeIndex 的值,以便在列表中高亮显示选中的项
}
</script>