Vue3 父子组件通信,实现单选任务清单
可以通过props属性将响应式数据从父组件传递到子组件,并且子组件也可以通过触发事件来改变父组件的响应式值
子组件
TodoList.vue
<template>
<ul>
<template v-for="(item, index) in list" :key="index">
<li :class="item.active ? 'active' : ''" @click="onHandle(index)">
<p class="title">{{ item.title }}</p>
<p class="content">{{ item.content }}</p>
</li>
</template>
</ul>
</template>
<script setup>
const props = defineProps({ list: Object })
const $emit = defineEmits(['msg'])
const onHandle = (idx) => {
// 复位选中状态
for (let item of props.list) { item.active = false }
// 设定当前选项
props.list[idx].active = true
// 向父组件传递消息
$emit('msg', props.list[idx])
}
</script>
<style lang="less" scoped>
ul li {
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;
list-style: none;
padding: 6px 16px;
margin-bottom: 4px;
line-height: 0.8;
border-radius: 8px;
font-size: 13px;
cursor: pointer;
color: #303133;
border: 1px solid #d9ecff;
transition: border-color 0.3s, background-color 0.3s, color 0.3s;
.content {
color: #909399;
}
&:hover,
&:focus {
color: #409eff;
}
&.active {
color: #409eff;
background-color: rgba(64, 158, 255, .1);
border-color: #a0cfff;
}
&.active .title {
font-weight: 600;
}
}
</style>
父组件
Main.vue
<template>
<TodoList :list="list" @msg="onMsgHandle"></TodoList>
</template>
<script setup>
import { ref } from "vue"
import TodoList from "TodoList.vue"
function onMsgHandle(params) {
console.log(params)
}
const list = ref([
{
id: 1,
title: 'Button 按钮',
content: '使用属性来控制按钮是否为禁用状态',
active: false
}, {
id: 2,
title: 'Container 布局容器',
content: '可以设置链接按钮的主题样式',
active: false
}, {
id: 3,
title: 'Scrollbar 滚动条',
content: '单独使用图标不添加文字来节省显示区域占用',
active: false
},
])
</script>