简体   繁体   中英

Vuex mutation doesn't seem to be updating state on load

So i'm committing a mutation on page load but it doesn't seem to be updating the state but if i commit the same mutation on a page, it works fine. Is there something i'm missing when it comes to the state not being ready to be updated once the page is loaded?

main.js:

  new Vue({
     router,
     store,
     jQuery,
     el: '#app',
     mounted() {
        store.dispatch('getImages');
     },
     render: h => h(App)
   });

Store.js

const state = {
    images: []
    };

    const getters = {
    getImages: (state) => {
        return state.images;
    }
    };

    const mutations = {
     getImages: (state, payload) => {
        let that = this;
        $client.getSpace(process.env.VUE_APP_CONTENTFUL_SPACE_ID)
            .then((Environment) => {
                Environment.getAssets()
                    .then((assets) => {
                        let images = [];
                        assets.items.forEach(function (item) {
                            if (!item.fields.title['en-US'].includes('About')) {
                                images.push(item.fields.file['en-US'].url);
                            }
                        });
                        Vue.set(state, 'images', images);

                        localStorage.images = JSON.stringify(images);
                    });
            });
     },
    };

    const actions = {
    getImages({ commit }) {
        setTimeout(function () {
            commit('getImages')
        }, 500)
    }
};

    export default new Vuex.Store({
     state,
     mutations,
     getters,
     actions
    })

You need to pass your store to your app instance.

import store from './store' // correct path to your store

new Vue({
  router,
  store,  <---
  // ...
})

I don't understand why you wrap your Vue app in a setTimeout.

I suggest you read the Vuex documentation. You are doing asynchronous work in a mutation, where this type of thing belongs in an action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM