【问题标题】:Vue app state not updating when Vuex store state mutates当 Vuex 存储状态发生变化时,Vue 应用程序状态不会更新
【发布时间】:2019-10-05 00:41:10
【问题描述】:

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

我创建了一个新应用并实现了一个简单的计数,只是为了看看它是否有效,但当 store.count 更改时,它仍然不会更新 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 值也不会更新,我错过了什么?

【问题讨论】:

    标签: javascript vuejs2 vuex


    【解决方案1】:

    问题很可能是您在index.js 中导入了Vue。尝试将其更改为:

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

    只是:

    import Vue from 'vue';
    

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

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

    希望对您有所帮助!

    【讨论】:

    • 感谢您的回答,问题是,如果我这样做,我会收到以下错误:[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
    • 你是在使用@vue/cli 还是有自定义的 webpack 配置?
    • 我正在使用 webpack。
    • 这个导入是专门导致 Vuex 无法有效注册的问题。你可能想用你的 webpack 配置发布另一个问题,因为你应该能够从 vue 而不是 vue/dist 导入。如果您使用 @vue/cli 项目尝试您的代码,您可以复制问题和解决方案。
    • 好的,谢谢。至少现在我知道问题出在哪里。 :)
    【解决方案2】:

    如关于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查看完整的工作示例。

    【讨论】:

    • 感谢您的回答,我知道动作和突变应该如何工作。这两种方法都不起作用。
    猜你喜欢
    • 2020-08-04
    • 2017-02-11
    • 2019-08-06
    • 2020-10-31
    • 2020-10-21
    • 2021-07-05
    • 2019-09-25
    • 2019-11-30
    • 2018-03-27
    相关资源
    最近更新 更多