文章来源地址https://www.toymoban.com/news/detail-609749.html
引入第三方库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)
}
}
文章来源:https://www.toymoban.com/news/detail-609749.html
到了这里,关于Vue消息订阅与发布的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!