我有在父组件中生成的事件,子组件必须对其使用react。我知道这不是 vuejs2
中推荐的方法,我必须执行一个非常糟糕的 $root
emit。所以我的代码是这样的。
<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
在无限滚动时被触发,事件被发送到子组件搜索。好吧,不仅是搜索,而且因为它是根目录,所以它被广播给所有人。
对此有什么更好的方法。我知道我应该使用 Prop ,但我不确定在这种情况下我该怎么做。
最佳答案
只要有一个变量(称它为 moreLoaded
),每次调用 loadMore
时它都会递增。将它和 currentPosition
作为 Prop 传递给您的 search
组件。在搜索中,您可以watch moreLoaded
并采取相应的行动。
更新
哈基? 我的解决方案?嗯,我从来没有! ;)
你也可以使用 localized event bus .像这样设置它:
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>
这将把 bus
作为 Prop (当然),并且有一个像这样的部分
created() {
this.bus.$on('loadMore', (args) => {
// do something with args.currentPosition
});
}
关于javascript - 从父组件到子组件的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43256978/