Vue3 父子组件通信,实现单选任务清单

本文详细介绍了如何在Vue3中通过props和事件实现父子组件之间的通信,以创建一个可复选的单选任务清单。子组件通过`props`接收数据并处理选中状态,通过触发事件更新父组件并传递数据给父组件进行处理。
摘要由CSDN通过智能技术生成

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>
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值