简体   繁体   English

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

[英]How to send value of variable from component one to component two? (vue.js 2)

My view is like this : 我的看法是这样的:

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

My search-filter-view component is like this : 我的search-filter-view组件是这样的:

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

My search-result-view component is like this : 我的搜索结果视图组件是这样的:

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

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

I want display value of sort parameter (filterBySort method, component one) to getVueItems method (component two) 我想将排序参数(filterBySort方法,组件一)的值显示为getVueItems方法(组件二)

How can I do it? 我该怎么做?

I'll elaborate on what Serge referenced. 我将详细说明Serge所引用的内容。 In Vue v1 components could just broadcast messages to the world and others could just listen and act on them. 在Vue v1中,组件可以向世界广播消息,而其他组件则可以侦听消息并对其采取行动。 In Vue2 it's a bit more refined to be more explicit. 在Vue2中,它进行了一些改进以更加明确。

What you need to do is create a separate Vue instance as a messenger or communication bus visible to both of your existing components. 您需要做的是创建一个单独的Vue实例,作为两个现有组件都可见的Messenger或通讯总线。 Example (using ES5): 示例(使用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 ...
});

For more complicated matters than simple component-to-component communication Vuex (Vue's equivalent of React's Redux) should be investigated. 对于比简单的组件到组件通信更复杂的事情,应该研究Vuex(Vue等同于React的Redux)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM