全局事件总线
(没有新的api)利用自定义事件,实现兄弟组件之间的通信。
复习VueComponet
复习重要的内置关系
所以,在Vue的原型对象上添加属性。
需要有$on(绑定事件,触发事件时的回调)、$emit(触发事件)。
$on、$emit、$off都在Vue的原型对象上。vm和vc都能看见。
利用beforeCreate钩子: 此时数据还没解析,数据代理、监测没开始。
main.js:
/*
const Demo = Vue.extend({});//Demo:一个Vuecomponent构造函数
const d = new Demo();//new调用,生成vc实例
Vue.prototype.x = d;//x是一个vc实例*/
//创建vue实例对象
new Vue({
//将App组件放入容器中
render: h => h(App),
beforeCreate() {
//安装全局事件总线
Vue.prototype.$bus = this;//$bus是一个vm实例,$bus是它的名字,$bus在Vue原型对象上,vc能够看见,没有必要new一个vc
},
}).$mount('#app')
school.vue
<template>
<div class="school">
<h2>schoolname:{
{ name }}</h2>
<h2>schoolage{
{ schoolage }}</h2>
</div>
</template>
<script>
export default {
name: "SchoolInfo",
data() {
return {
name: "atguigu",
schoolage: 20,
stuname:'???'
};
},
methods:{
},
mounted(){
//console.log('school',this.$bus);
//给$bus绑定hello事件、事件回调在school上
this.$bus.$on('hello',(data)=>{
//写成箭头函数,使this是当前组件
this.stuname = data;
});
},
beforeDestroy() {
//销毁$bus上的hello事件
this.$bus.$off('hello')
},
};
</script>
student.vue
<template>
<div class="student">
<h1>{
{ msg }}</h1>
<h2>stuname:{
{ name }}</h2>
<h2>stuage:{
{ stuage }}</h2>
<button @click='sendStudentName'>把学生名给school组件</button>
</div>
</template>
<script>
export default {
name: "StudentInfo",
data() {
return {
msg: "尚硅谷666",
name: "jack",
stuage: 18,
};
},
methods: {
sendStudentName(){
//触发$bus的hello事件
this.$bus.$emit('hello',this.stuname);
}
},
};
</script>
TodoList事件总线
让app能够直接和item通信。之前是把app上的函数一直传递下去,item接收,触发函数。
现在app收数据,item传id。给app绑定事件,事件回调。item传入id触发事件。
此时勾选、删除,触发事件的是$bus,vm
App.vue
mounted() {
this.$bus.$on('checkTodo',this.checkTodo)
this.$bus.$on('deleteTodo',this.deleteTodo)
},
beforeDestroy() {
this.$bus.$off('checkTodo');
this.$bus.$off('deleteTodo');
},
item.vue
<template>
<li>
<label>
<input type="checkbox" :checked="todo.done" @change='handleCheck(todo.id)'/>
<!--eslint-disable-next-line vue/no-mutating-props-->
<!--<input type="checkbox" v-model="todo.done">-->
<span>{
{todo.title}}</span>
</label>
<button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
</li>
</template>
<script>
export default {
name: "OptionItem",
data() {
return {
};
},