Reputation: 3088
I have two components:
<div>
<advertiser-add-component></advertiser-add-component>
<advertisers-component></advertisers-component>
</div>
These components have the following interface:
First component is a button. I will see a modal dialog when I click on it. The modal contains an Ajax form:
Second component is a table. You already saw it on the first picture So, I would like to rerender the table component after sending the form without page refreshing. Is there some way to "subscribe" to this event (once the modal information is sent) from advertisers-component? How I can organize it with minimum code?
Upvotes: 2
Views: 5783
Reputation: 184
I would encourage you to check this: https://v2.vuejs.org/v2/guide/state-management.html
Basically you have a component (or java class) called a store that holds the data of the table. That data is the one displayed by the table. When submitting the modal, you ask the store to fetch the data again (by sending an event) from your backend where I assume the data is stored.
Since the table displays the data of the store already, the table will update itself automatically.
I have done just that in an application of mine here: https://github.com/Draluy/Jobsearch/blob/master/front/src/components/applications/Application.vue
Upvotes: 1
Reputation: 2123
Im using vue-events package: https://github.com/cklmercer/vue-events
Add events object in your component with the events to listen, and fire the event from the modal, check this example:
Upvotes: 4
Reputation: 82
It seems like you want to wrap your two components in another component that handles the data and the ajax request.
<wrap-component> <!-- This component contains the data and handles the ajax request -->
<advertiser-add-component @click-triggered="ajaxRequest"></advertiser-add-component> <!-- This components emits a click event to the <wrap-component>-component that executes the ajax requests -->
<advertisers-component :tableData="tableData"></advertisers-component> <!-- This component is passed the data via the tableData prop -->
</wrap-component>
<!-- Inside "wrap-component" -->
data() {
return {
tableData: []
}
},
methods: {
ajaxRequest() {
// make the data request here and replace this.tableData with the response data
}
}
<!-- Inside "advertiser-add-component" -->
methods: {
// Execute this function, when the button is clicked
add() {
this.$emit('click-triggered');
}
}
<!-- Inside "advertisers-component" -->
props: {
tableData: {
type: Array // if the data is an array of course..
}
}
Upvotes: 0
Reputation: 498
Yes absolutely, for something like this you could spin up a simple event bus, your component would emit an update to the bus, and the other watches for updates to that event type on the bus.
Here's a good example of how to do it:
https://alligator.io/vuejs/global-event-bus/
Upvotes: 2