当Vuex商店状态发生突变时,Vue应用程序状态不会更新

时间:2019-05-17 16:47:30

标签: javascript vuejs2 vuex

我已经使用Vue几个月了,现在我正在尝试将Vuex与我的应用程序集成,但是当Vuex商店发生突变时,我无法更新状态。

我创建了一个新应用并实现了一个简单的计数,只是看它是否有效,但是在更改count时它仍然不会更新store.count。 我的测试代码如下。

index.html

<div id="app">
    <template>
        <h1>{{count}}</h1>
        <button @click="add">Add 1</button>
    </template>
</div>

index.js

import Vue from 'vue/dist/vue.js';

import store from './store';

new Vue({
    el: '#app',
    store,
    data: {},
    computed: {
        count: () => store.state.count
    },
    methods: {
        add: () => store.commit('add')
    }
});

store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        add: (state) => state.count++
    }
});

我知道store.count正在更新,因为我可以在Vue开发工具中看到它。我只是不知道为什么count值也不会更新,我还缺少什么?

2 个答案:

答案 0 :(得分:0)

问题很可能是您在Vue中导入了index.js。尝试从以下位置进行更改:

import Vue from 'vue/dist/vue.js';

只是:

import Vue from 'vue';

这将有助于确保Vuex已正确注册。

我使用@vue/cli和Vuex创建了一个项目。从vue/dist/vue.js而不是仅从vue导入主/索引无法有效地注册Vuex,包括能够在子组件中访问this.$store

希望有帮助!

答案 1 :(得分:0)

如有关actions的文档

所述
  

动作可以包含任意异步操作。

在您的情况下,单击add按钮将执行异步代码。 另一方面,Mutations是同步的,可以使整个应用程序中的值保持不变。 可以通过commit语句进行更改,例如store.commit("add")

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  // Synchronous methods for modifying the values in the state.
  // They are handed a `state` from the store.
  mutations: {
    add: state => state.count++
  },
  // Asynchronous methods that can call mutation methods to mutate the state via commits.
  // They are handed a context of the `store`.
  actions: {
    add: store => store.commit("add")
  }
});

请参见CodeSandbox上的完整示例。

相关问题