[英]Event from parent to child component
我有在父组件中生成的事件,而子组件必须对其做出反应。 我知道这不是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
在无限滚动时被触发,并且事件被发送到子组件搜索。 不仅仅是搜索,而是因为它是根,它正在向所有人广播。
什么是更好的方法。 我知道我应该使用道具,但我不知道在这种情况下我怎么能这样做。
只需要一个变量(称之为moreLoaded
),每次调用moreLoaded
时loadMore
增加该变量。 将currentPosition
和currentPosition
作为道具传递给search
组件。 在“搜索”中,您可以watch moreLoaded
并相应地执行操作。
更新
哈克? 我的解决方案 嗯,我从来没有! ;)
您还可以使用本地化的事件总线 。 设置如下:
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
作为道具(当然),并有一个类似的部分
created() {
this.bus.$on('loadMore', (args) => {
// do something with args.currentPosition
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.