main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from "./App";
//关闭Vue的生产提示
Vue.config.productionTip = false
// const Demo = Vue.extend({})
// const d = new Demo()
// Vue.prototype.x = d//创建vm
new Vue({
el:'#app',
render:h=>h(App),
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线
}
})
Student.vue
<button @click="sendStudentName">把学生名给school组件</button>
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
},
School.vue
mounted() {
// console.log("school",this.x)
this.$bus.$on('hello',(data)=>{
console.log('我是school组件,收到了数据',data)
})
},
beforeDestroy() {
this.$off('hello')
},
TodoList案例优化:
main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from "./App";
//关闭Vue的生产提示
Vue.config.productionTip = false
//创建vm
new Vue({
el:'#app',
render:h=>h(App),
beforeCreate() {
Vue.prototype.$bus = this
}
})
App.vue: 删除之前给Mylist绑定的:checkTodo :deleteTodo
mounted() {
this.$bus.$on('checkTodo',this.checkTodo)
this.$bus.$on('deleteTodo',this.deleteTodo)
},
beforeDestroy() {
this.$bus.$off('checkTodo')
this.$bus.$off('deleteTodo')
}
MyList.vue: 删除props接收的checkTodo,deleteTodo,删除给MyItem绑定的:checkTodo :deleteTodo
MyItem.vue: 删除props接收的checkTodo,deleteTodo
methods:{
//勾选or取消勾选
handleCheck(id){
//通知App组件将对应的todo对象的done值取反
// this.checkTodo(id)
this.$bus.$emit('checkTodo',id)
},
//删除
handleDelete(id){
if (confirm('确定删除吗')){ //confirm根据用户的交互来决定到底是布尔值为真还是为假,点击确定为真,点击取消为假
// this.deleteTodo(id)
this.$bus.$emit('deleteTodo',id)
}
}
}