【问题标题】:Vue.js/Laravel: How to pass data between multiple componentsVue.js/Laravel:如何在多个组件之间传递数据
【发布时间】:2020-12-28 17:42:40
【问题描述】:
require('./bootstrap');

window.Vue = require('vue');

Vue.component('exampleComponent1', require('./components/exampleComponent1.vue'));
Vue.component('exampleComponent2', require('./components/exampleComponent2.vue'));

const app = new Vue({
    el: '#app'
});

从上面的代码中,当exampleComponent1 发生一些event 时,我想将数据从exampleComponent1 传递到exampleComponent2

这个问题的最佳解决方案是什么??

【问题讨论】:

    标签: javascript laravel vue.js vuejs2


    【解决方案1】:

    这里的关键是将他们的parent 组件设置为从第一个接收(使用emit)并发送到第二个(使用props)的组件:

    const component1 = Vue.component('component1', { 
      template: '#component1',
      data() { return { name: '' } },
      methods: {
        updateName() { this.$emit("namechanged", this.name); }
      }
    });
    
    const component2 = Vue.component('component2', { 
      template: '#component2',
      props: ['name'],
    });
    
    new Vue({
      el: "#app",
      components: { component1, component2 },
      data() { return { name: '' } },
      methods: {
        updateName(newName) { this.name = newName; }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    
    <div id="app">
      <div><component1 @namechanged="updateName"/></div>
      <div><component2 :name="name"/></div>
    </div>
    
    <template id="component1"><input v-model="name" @input="updateName"/></template>
    
    <template id="component2"><p>Input From component 1: {{name}}</p></template>

    【讨论】:

      【解决方案2】:

      您可以为此使用Event Bus

      // in some global file
      const EventBus = new Vue();
      
      // creating or emitting event
      EventBus.$emit('someEvent', 'some-data')
      
      // listen to the event
      EventBus.$on('someEvent', function(data) {
        console.log(data) // 'some-data
      })
      

      【讨论】:

        猜你喜欢
        • 2020-03-05
        • 2020-10-23
        • 2019-06-24
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        • 2021-02-24
        • 2023-03-09
        相关资源
        最近更新 更多