Vue.js的事件机制
vm.$on, vm.$emit, vm.$dispatch, vm.$broadcast 是 Vuejs 事件机制的重要成员。
·
监听事件
vm.$on(event, callback)
在vm实例监听事件。vm.$emit
, vm.$dispatch
或 vm.$broadcast
均可抛事件。
vm.$on('test', function(msg){
console.log(msg)
})
vm.$emit('test', 'hi')
监听单次事件
vm.$once(event, callback)
仅监听一次事件。
移除回调函数
vm.$off([event, callback])
- 如果参数为空,则移除所有回调函数
- 如果仅提供事件名,则移除对应该事件的全部回调函数
- 如果提供事件名和函数名,则只移除该事件对应的回调函数。
向自己抛事件
vm.$emit(event, […args])
vm实例抛出事件。除事件名外的其他参数都会传递到回调函数。
向上级抛事件
vm.$dispatch(event, […args])
向上抛出事件。先触发实例本身,然后沿父级链向上传递。如果回调函数没有返回 true,传播过程触发到第一个回调函数就会停止。
var parent = new Vue()
var child1 = new Vue({ parent:parent })
var child2 = new Vue({ parent: child1 })
parent.$on('test', function(){
console.log('parent notified')
})
child1.$on('test', function(){
console.log('child1 notified')
return true
})
child2.$on('test', function(){
console.log('child2 notified')
})
child2.$dispatch('test')
向下级抛事件
vm.$broadcast(event, […args])
向下传递事件。注意,该方法不会在当前实例触发事件。
var parent = new Vue()
var child1 = new Vue({ parent: parent })
var child2 = new Vue({ parent: parent })
var child3 = new Vue({ parent: child2 })
parent.$on('test', function(){
console.log('parent notified')
})
child1.$on('test', function(){
console.log('child1 notified')
return true
})
child2.$on('test', function(){
console.log('child2 notified')
})
child3.$on('test', function(){
console.log('child3 notified')
})
parent.$broadcast('test')
参考资料
更多推荐
已为社区贡献2条内容
所有评论(0)