此处没有使用全局事件总线mitt
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
<!-- <script src="https://unpkg.com/mitt/dist/mitt.umd.js"></script> -->
</head>
<body>
<div id="app"></div>
<template id="root">
<div>
<!-- 根组件的作用是用于发送值到未完成组件 -->
<add-component @add-Task="handleTask"></add-component>
<!-- 未完成组件,用于接收根本组件的值和发送值到完成组件 -->
<unfinish-component :message="message" @finish-Task="handleTask2"></unfinish-component>
<!-- 接收完成组件的值 -->
<finish-component :message2="message2"></finish-component>
</div>
</template>
<!-- 根组件 -->
<template id="addComponent">
<span>任务名:</span>
<!-- 绑定发送的值 -->
<input type="text" v-model="name">
<!-- 提交点击事件 -->
<button @click="addTask">提交</button>
</template>
<!-- 未完成组件 -->
<template id="unfinishComponent">
<div>
<h2>未完成:</h2>
<div class="box">
<!-- 遍历里面的值 -->
<ul v-for="(t,index) in tasks" :key="index">
<!-- 显示信息,且创建点击完成事件 -->
<li>{{t.name}} <button @click="finishTask(index)">完成</button></li>
</ul>
</div>
</div>
</template>
<template id="finishComponent">
<div>
<h2>已完成:</h2>
<div class="box">
<ul v-for="(t,index) in tasks2" :key="index">
<li>{{t.name}} <button @click="deleteTask(index)">删除</button></li>
</ul>
</div>
<button @click="allDelete">全部删除</button>
</div>
</template>
<script type="text/javascript">
// 实例化ref对象
const { ref, reactive, watch } = Vue
const app = Vue.createApp({
template: "#root",
setup() {
let message = ref({})
let message2 = ref({})
// 根组件发送到未完成组件的消息
let handleTask = (name) => {
message.value = name
}
// 未完成组件发送到完成组件的消息
let handleTask2 = (name) => {
message2.value = name
}
return {
handleTask,
handleTask2,
message,
message2
}
}
})
app.component('addComponent', {
template: "#addComponent",
setup(props, { emit }) {
let name = ref('')
let addTask = () => {
// 根组件发送值
emit('addTask', { "name": name.value })
}
return {
name,
addTask
}
}
})
app.component('unfinishComponent', {
template: "#unfinishComponent",
props: { message: Object },
setup(props, { emit }) {
// 创建遍历的数组
let tasks = reactive([{ name: "111" }])
// 发送到已完成组件
let finishTask = (e) => {
emit('finishTask', { "name": tasks[e].name })
// 发送后删除
tasks.splice(e, 1)
}
// 监听根组件发送的值
watch(() => props.message, (nvalue, ovalue) => {
// 写入数组里面
tasks.push(nvalue)
})
return {
tasks,
finishTask
}
}
})
app.component('finishComponent', {
template: "#finishComponent",
props: { message2: Object },
setup(props, { emit }) {
// 定义一个数组task2
let tasks2 = reactive([{ name: "222" }])
// 监听task发送出来的数据
watch(() => props.message2, (nvalue, ovalue) => {
tasks2.push(nvalue)
})
// 删除一个
let deleteTask = (e) => {
tasks2.splice(e, 1)
}
// 删除全部
const allDelete = () => {
// 0-数组的长度
tasks2.splice(0, tasks2.length)
}
return {
tasks2,
deleteTask,
allDelete
}
}
})
app.mount("#app")
</script>
</body>
</html>