mad*_*eye 4 javascript vue.js vue-component vuejs2
我有在父组件中生成的事件,而子组件必须对其做出反应.我知道这不是推荐的方法vuejs2,我必须做一个$root非常糟糕的发射.所以我的代码是这样的.
<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>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样loadMore,在无限滚动时触发,并且正在将事件发送到子组件搜索.不仅仅是搜索,而是因为它是根,它正在向所有人广播.
什么是更好的方法.我知道我应该使用道具,但我不知道在这种情况下我怎么能这样做.
Roy*_*y J 17
只需要一个变量(调用它moreLoaded),每次调用时都会递增loadMore.currentPosition将其search作为道具传递给您的组件.在搜索中,您可以相应地watch moreLoaded采取相应措施.
更新
Hacky?我的解决方案 嗯,我从来没有!;)
您还可以使用本地化的事件总线.设置如下:
export default {
components: {
Search
},
data() {
return {
bus: new Vue(),
transactions: [],
currentPosition: 0
}
},
methods: {
loadMore() {
this.bus.$emit('loadMore', {
currentPosition: this.currentPosition
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
并将其传递给搜索:
<search :bus="bus"></search>
Run Code Online (Sandbox Code Playgroud)
这将bus作为道具(当然),并有一个像
created() {
this.bus.$on('loadMore', (args) => {
// do something with args.currentPosition
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4304 次 |
| 最近记录: |