Jerodev
Jerodev

Reputation: 33216

Reload component data based on vuex state

I am creating one single admin panel for several web shops. To keep track of what website I am currently editing I have a website object in my vuex state. The website can be changed by a button that dispatches an action on the state.

The admin dashboard page is a page showing statistics for the selected website, the data for these statistics is currently saved on the page component itself.

Now I have a problem when I change to another website when I am on the dashboard. Because the url is the same for the dashboards, the statistics don't change. I suppose this is because vue-router has not detected a change to the url so there is no need to reload the component, however I would like this to happen when the website is changed. Or at least a way to know that the website has changed so I could manually call the ajax source again.

I have just started using vue a few weeks ago and did not find a way to accomplish this.

Upvotes: 0

Views: 1860

Answers (1)

Moisés Hiraldo
Moisés Hiraldo

Reputation: 378

You can subscribe to Vuex mutations and actions: https://vuex.vuejs.org/api/#subscribe

On the created hook of your admin dashboard component, assuming you're injecting the Vuex store, you could have something like:

created: function() {
    this.unsubscribe = this.$store.subscribe((action, state) => {
        if (action.type === 'changeWebsite') {  // Whatever your action is called
            this.updateWebsiteData(action.payload); // Method to update component data 
        }
    });
},
beforeDestroy: function() {
    this.unsubscribe();
},

Upvotes: 4

Related Questions