问题描述
我有在父组件中生成的事件,而子组件必须对其做出反应。我知道这不是 vuejs2
中的推荐方法,而且我必须做一个 $ root
emit,这非常糟糕。所以我的代码就是这样。
I have event that is generated in parent component and child has to react to it. I know that this is not recommended approach in vuejs2
and i have to do a $root
emit which is pretty bad. So my code is this.
<template>
<search></search>
<table class="table table-condensed table-hover table-striped" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
<tbody id="trans-table">
<tr v-for="transaction in transactions" v-model="transactions">
<td v-for="item in transaction" v-html="item"></td>
</tr>
</tbody>
</table>
</template>
<script>
import Search from './Search.vue';
export default {
components: {
Search
},
data() {
return {
transactions: [],
currentPosition: 0
}
},
methods: {
loadMore() {
this.$root.$emit('loadMore', {
currentPosition: this.currentPosition
});
}
}
}
</script>
如你所见, loadMore
被触发无限滚动和事件被发送到子组件搜索。不仅仅是搜索,而是因为它是root,它正在向所有人广播。
As You can see loadMore
is triggered on infinite scroll and event is being sent to child component search. Well not just search but since it's root it's being broadcast to everyone.
有什么更好的方法。我知道我应该使用道具,但我不知道在这种情况下我怎么能这样做。
What is better approach for this. I know that i should use props but I'm not sure how can i do that in this situation.
推荐答案
只是有一个每次调用 loadMore
时增加的变量(称为 moreLoaded
)。将此和 currentPosition
作为道具传递到搜索
组件。在搜索中,您可以观看moreLoaded
并采取相应的操作。
Just have a variable (call it moreLoaded
) that you increment each time loadMore
is called. Pass that and currentPosition
to your search
component as props. In Search, you can watch moreLoaded
and take action accordingly.
更新
Hacky? 我的解决方案?嗯,我从来没有! ;)
Update
Hacky? My solution? Well, I never! ;)
您还可以使用。设置如下:
You could also use a localized event bus. Set it up something like this:
export default {
components: {
Search
},
data() {
return {
bus: new Vue(),
transactions: [],
currentPosition: 0
}
},
methods: {
loadMore() {
this.bus.$emit('loadMore', {
currentPosition: this.currentPosition
});
}
}
}
并将其传递给搜索:
<search :bus="bus"></search>
将巴士
作为道具(当然),并有一个类似
which would take bus
as a prop (of course), and have a section like
created() {
this.bus.$on('loadMore', (args) => {
// do something with args.currentPosition
});
}
这篇关于从父组件到子组件的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!