【问题标题】:How to set data to other Component in Vuejs如何在 Vuejs 中将数据设置到其他组件
【发布时间】:2017-05-25 16:20:23
【问题描述】:

我想用 vuejs 将数据从一个组件设置到另一个组件。这是我的代码:
http://quangtri.herokuapp.com/s/ByNN4FE-b 我哪里错了?请帮我!非常感谢!

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    您在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>

    【讨论】:

      【解决方案2】:

      那是因为在那段代码中,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))
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2020-03-24
      相关资源
      最近更新 更多