【问题标题】:Vuex mutation doesn't seem to be updating state on loadVuex 突变似乎没有在加载时更新状态
【发布时间】:2019-07-26 08:45:58
【问题描述】:

所以我在页面加载时提交了一个突变,但它似乎没有更新状态,但如果我在页面上提交相同的突变,它工作正常。当页面加载后状态未准备好更新时,我是否遗漏了什么?

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
    })

【问题讨论】:

    标签: vue.js vuejs2 vuex vue-cli


    【解决方案1】:

    您需要将您的商店传递给您的应用实例。

    import store from './store' // correct path to your store
    
    new Vue({
      router,
      store,  <---
      // ...
    })
    

    我不明白您为什么将 Vue 应用程序包装在 setTimeout 中。

    我建议你阅读 Vuex 文档。你在一个mutation中做异步工作,这种类型的东西属于action

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 2020-12-18
      • 2019-11-30
      • 2018-05-24
      • 2019-12-12
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      相关资源
      最近更新 更多