如何在Vuejs中为其他组件设置数据 [英] How to set data to other Component in Vuejs

查看:21
本文介绍了如何在Vuejs中为其他组件设置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

您在 bus.$on 中使用了 function,所以 this 不是你想的那样.改用箭头函数即可.

const bus = new Vue();Vue.component('优惠券', {数据() {返回 {名称:'三'}},模板:`<div><p>{{名称}}</p><button type="button" @click="batdau">Go</button>

`,方法: {batdau(姓名){this.name = '玛丽亚';}},创建(){},安装(){bus.$on('applied', (name) => {警报(名称);this.name = '罗密欧';})}});Vue.component('couponmore', {模板:`<button type="button" @click="nosukien">设置名称</button>`,方法: {nosukien() {bus.$emit('applied', 'John');}}});新的 Vue({el: '#root',数据: {优惠券已应用:false}});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script><div id="root"><优惠券></优惠券><couponmore></couponmore>

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!

解决方案

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>

这篇关于如何在Vuejs中为其他组件设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆