引入第三方库pubsub.js:
npm i pubsub-js
Student.vue
import pubsub from 'pubsub-js'
methods:{
sendStudentName(){
// this.$bus.$emit('hello',this.name)
pubsub.publish('hello',666)
}
},
School.vue
import pubsub from 'pubsub-js'
mounted() {
// console.log("school",this.x)
/* this.$bus.$on('hello',(data)=>{
console.log('我是school组件,收到了数据',data)
})*/
this.pubId = pubsub.subscribe('hello',function (msgName,data){
console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
})
},
beforeDestroy() {
// this.$off('hello')
pubsub.unsubscribe(this.pubId)
},
}
TodoList案例使用消息订阅实现删除功能:
App.vue:
import pubsub from 'pubsub-js'
mounted() {
this.$bus.$on('checkTodo',this.checkTodo)
this.pubId = pubsub.subscribe('deleteTodo',this.deleteTodo)
},
beforeDestroy() {
this.$bus.$off('checkTodo')
pubsub.unsubscribe(this.pubId)
}
}
MyItem.vue:
import pubsub from 'pubsub-js'
methods:{
//勾选or取消勾选
handleCheck(id){
//通知App组件将对应的todo对象的done值取反
// this.checkTodo(id)
this.$bus.$emit('checkTodo',id)
},
//删除
handleDelete(id){
if (confirm('确定删除吗')){ //confirm根据用户的交互来决定到底是布尔值为真还是为假,点击确定为真,点击取消为假
// this.deleteTodo(id)
pubsub.publish('deleteTodo',id)
}
}