我有这个代码:
html
<div id="app">
{{text}}
<my-component></my-component>
</div>
js
Vue.component('my-component', {
template: '<button @click="click">Click me</button>',
methods: {
click() {
this.$emit('send', 'bye')
}
}
})
new Vue({
el: "#app",
data: {
text: "hello"
},
created() {
this.$on('send', (text) => {
this.text = text;
})
}
})
工作示例:https://jsfiddle.net/rjurado/y4yf6nve/ https://jsfiddle.net/rjurado/y4yf6nve/
为什么事件send
不起作用?
this.$emit
仅参考Vue组件。你需要使用root
实例属性与根实例中的组件进行通信。所以基本上将根添加到事件中:
this.$root.$emit('send', 'bye')
this.$root.$on('send', (text) => {
this.text = text;
})
工作示例:jsFiddle https://jsfiddle.net/pss01r52/1/
Vue.js 中央事件总线
更好的方法是拥有中央事件总线:docs https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
var bus = new Vue();
Vue.component('my-component', {
template: '<button @click="click">Click me</button>',
methods: {
click() {
bus.$emit('send', 'bye')
}
}
})
new Vue({
el: "#app",
data: {
text: "hello"
},
created() {
bus.$on('send', (text) => {
this.text = text;
})
}
})
工作示例:jsFiddle https://jsfiddle.net/uu01tdez/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)