【发布时间】:2017-05-25 16:20:23
【问题描述】:
我想用 vuejs 将数据从一个组件设置到另一个组件。这是我的代码:
http://quangtri.herokuapp.com/s/ByNN4FE-b
我哪里错了?请帮我!非常感谢!
【问题讨论】:
我想用 vuejs 将数据从一个组件设置到另一个组件。这是我的代码:
http://quangtri.herokuapp.com/s/ByNN4FE-b
我哪里错了?请帮我!非常感谢!
【问题讨论】:
您在bus.$on 中使用function,所以this 不是您认为的那样。改用箭头函数就可以了。
const bus = new Vue();
Vue.component('coupon', {
data() {
return {
name: 'tri'
}
},
template: `
<div>
<p>{{ name }}</p>
<button type="button" @click="batdau">Go</button>
</div>
`,
methods: {
batdau(name) {
this.name = 'Maria';
}
},
created() {
},
mounted() {
bus.$on('applied', (name) => {
alert(name);
this.name = 'Romeo';
})
}
});
Vue.component('couponmore', {
template: `
<button type="button" @click="nosukien">Let Set Name</button>
`,
methods: {
nosukien() {
bus.$emit('applied', 'John');
}
}
});
new Vue({
el: '#root',
data: {
couponApplied: false
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<div id="root">
<coupon></coupon>
<couponmore></couponmore>
</div>
【讨论】:
那是因为在那段代码中,this 是窗口,而不是组件。
bus.$on('applied', function(name){
alert(name);
this.$data.name ='Romeo';
})
另外,您正在使用 this.$data.name 而不是简单的 this.name 设置数据,我不确定,但这可能会导致反应性数据问题。
如果你使用的是 ES6,你可以这样做:
bus.$on('applied', (name) => {
alert(name);
this.name ='Romeo';
})
这称为箭头函数,当使用箭头函数而不是普通函数时,函数内部this的值将与父作用域中的值相同(因此,包含data的组件实例)。
如果您使用的是原版 javascript,请在末尾使用 .bind(this):
bus.$on('applied', function (name) {
alert(name);
this.name ='Romeo';
}.bind(this))
【讨论】:
bus.$on('applied', function(name){...}.bind(this))