/**
* 事件总线实现
核心:
Vue.prototype.$bus = new Vue()
事件总线是一种发布订阅模式:
vm.$emit 方法将事件函数广播发布
vm.$on 接收广播
*/
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.prototype.$bus = new Vue()
Vue.config.productionTip = false
new Vue({
router,
render: (h) => h(App)
}).$mount('#app')
父组件
<template>
<div
id="app"
style="border:solid 2px black"
>
<div id="nav">
<router-link to="/home">进入主页</router-link>
<div>
<h1>我是TodoList4的父组件</h1>
<input
v-model="inputValue"
type="text"
/>
<button @click="addDataToList">添加</button>
<list-item :list="list"></list-item>
</div>
</div>
<router-view />
</div>
</template>
<script>
import ListItem from './TodoList4'
/**
*1. 父组件引入子组件,父组件修改变量值
*/
export default {
name: 'Welcome',
data() {
return {
list: [],
inputValue: ''
}
},
components: {
//显示子组件
ListItem
},
created() {
// 需要在 created 里面注册 delDataFromList 方法。
this.$bus.$on('delDataFromList', (index) => {
this.list.splice(index, 1)
})
},
mounted() {},
methods: {
addDataToList() {
if (this.inputValue.length === 0) {
return '长度为0不添加'
}
this.list.push(this.inputValue)
this.inputValue
}
},
computed: {}
}
</script>
<style scoped lang="scss"></style>
子组件
<template>
<div style="border:solid 2px blue">
<h1>我是TodoList4组件</h1>
<div
v-for="(item, index) in list"
@click="delDataFromList(index)"
:key="index"
>{{ item }}</div>
</div>
</template>
<script>
export default {
name: 'List',
data() {
return {}
},
props: {
list: {
type: Array,
default() {
return []
}
}
},
components: {},
created() {},
mounted() {},
methods: {
delDataFromList(index) {
this.$bus.$emit('delDataFromList', index)
}
},
computed: {}
}
</script>
<style scoped lang="scss"></style>