如何将变量的值从组件1发送到组件2? (vue.js 2)

如何将变量的值从组件1发送到组件2? (vue.js 2)

问题描述:

我的观点是这样的:如何将变量的值从组件1发送到组件2? (vue.js 2)

<div class="row"> 
    <div class="col-md-3"> 
     <search-filter-view ...></search-filter-view> 
    </div> 
    <div class="col-md-9"> 
     <search-result-view ...></search-result-view> 
    </div> 
</div> 

我的搜索过滤器视图分量是这样的:

<script> 
    export default{ 
     props:[...], 
     data(){ 
      return{ 
       ... 
      } 
     }, 
     methods:{ 
      filterBySort: function (sort){ 
       this.sort = sort 
       ... 
      } 
     } 
    } 
</script> 

我的搜索结果-视图分量是这样的:

<script> 
    export default { 
     props:[...], 
     data() { 
      return { 
       ... 
      } 
     }, 

     methods: { 
      getVueItems: function(page) { 
       ... 
      } 
     } 
    } 
</script> 

欲排序参数(filterBySort方法,部件中的一个),以getVueItems方法的显示值(组分2)

我该怎么办?

+0

在vuex的帮助下,这些东西可以变得简单,请看https://vuex.vuejs.org/en/。 –

+0

一个简单的例子,您可以使用虚拟vue在两者之间传递数据,如文档中所述:https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication – Serge

我会详细说明Serge引用的内容。在Vue v1中,组件可能只是向全世界发送消息,而其他人可能只是倾听并采取行动。在Vue2中,更加明确的是更加明确。

您需要做的是创建一个单独的Vue实例作为可用于您的两个现有组件的信使或通信总线。实施例(使用ES5):

// create the messenger/bus instance in a scope visible to both components 
var bus = new Vue(); 

// ... 

// within your "result" component 
bus.$emit('sort-param', 'some value'); 

// ... 

// within your "filter" component 
bus.$on('sort-param', function(sortParam) { 
    // ... do something with it ... 
}); 

对于除简单的组件到组件通信Vuex(Vue公司的同等阵营的终极版的)应进行调查更为复杂的问题。