如何将变量值从组件一发送到组件二? (vue.js 2)
How to send value of variable from component one to component two? (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>
我的 search-filter-view 组件是这样的:
<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 方法(组件二)
我该怎么做?
我将详细说明 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 ...
});
对于比简单 component-to-component 通信更复杂的问题,应研究 Vuex(Vue 相当于 React 的 Redux)。
我的看法是这样的:
<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>
我的 search-filter-view 组件是这样的:
<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 方法(组件二)
我该怎么做?
我将详细说明 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 ...
});
对于比简单 component-to-component 通信更复杂的问题,应研究 Vuex(Vue 相当于 React 的 Redux)。