How to set data to other Component in Vuejs

2019-09-16 10:29发布

I want to set data from a component to another component with vuejs. Here's my code:
http://quangtri.herokuapp.com/s/ByNN4FE-b Where am I wrong? Please help me! Thank you very much!

标签: vue.js vuejs2
2条回答
女痞
2楼-- · 2019-09-16 11:09

You are using a function in your bus.$on, so this is not what you think it is. Use an arrow function instead and it works.

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>

查看更多
Evening l夕情丶
3楼-- · 2019-09-16 11:11

That's because in that piece of code, this is window, not the component.

bus.$on('applied', function(name){
    alert(name);
    this.$data.name ='Romeo';
})

Also you are setting data using this.$data.name instead of simply this.name, I'm not sure about it, but this could result in reactive data issues.

Solution:

If you are using ES6, you can do this:

bus.$on('applied', (name) => {
    alert(name);
    this.name ='Romeo';
})

This is called arrow function, and when using an arrow function instead of a normal function, the value of this inside the function will be the same as in the parent scope (so, the component instance who contains data).

If you are using vanilla javascript, use .bind(this) at the end:

bus.$on('applied', function (name) {
    alert(name);
    this.name ='Romeo';
}.bind(this))
查看更多
登录 后发表回答