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>
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.
Just have a variable (call it
moreLoaded
) that you increment each timeloadMore
is called. Pass that andcurrentPosition
to yoursearch
component as props. In Search, you canwatch moreLoaded
and take action accordingly.Update
Hacky? My solution? Well, I never! ;)
You could also use a localized event bus. Set it up something like this:
and pass it to Search:
which would take
bus
as a prop (of course), and have a section like