简体   繁体   English

为什么状态不会在计算中更新?

[英]Why the state doesn't update in computed?

I'm struggling for a couple of hours with vuex.我在 vuex 上挣扎了几个小时。 It's the first time I use it and even though I follow the documentation something is not working but I really can't figure it out.这是我第一次使用它,尽管我按照文档进行了操作,但我确实无法弄清楚。

So I have the first example of the vuex doc that doesn't work.所以我有第一个不起作用的 vuex 文档示例。 I have a count computed value that return the store state.我有一个返回商店状态的count计算值。

It's display on the page.它显示在页面上。 The started value is 0 and the view is displaying 0. But hitting the buttons doesn't change the display.起始值为 0,视图显示为 0。但点击按钮不会改变显示。

If I put directly the store into the App.js in a constant, no problem it works.如果我将 store 直接放入 App.js 中,它可以正常工作。

I know I'm missing something...我知道我错过了一些东西......

homeStore.js家商店.js

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

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment (state) {
            state.count++
        },
        decrement (state) {
            state.count--
        }
    }
})

App.js应用程序.js

import store from '../store/homeStore'

new Vue({
    el: '#app',
    store,
    computed: {
        count () {
            return store.state.count
        },
    },
    methods: {
        increment () {
            store.commit('increment')
        },
        decrement () {
            store.commit('decrement')
        }
    }
})

Make use of Vuex store actions使用 Vuex 存储操作

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
    state: { count: 0 },
    mutations: {
        increment (state) {
            state.count++ 
        },
       decrement (state) {
           state.count-- 
       }
    },
    actions: {
        increase ({ commit }) {
            commit('increment')
        },
        decrease ({ commit }) {
            commit('decrement')
        }
    }
 })

access the action method using this.$store.dispatch('increase') to increment the count and vice versa for decrement使用 this.$store.dispatch('increase') 访问 action 方法来增加计数,反之亦然减少

If you try to console.log(store) , it will returns undefined .如果您尝试使用console.log(store) ,它将返回undefined
The right way to access the store is to use this.$store (should be a component).访问 store 的正确方法是使用this.$store (应该是一个组件)。

As mentioned in the doc:如文档中所述:

By providing the store option to the root instance, the store will be injected into all child components of the root and will be available on them as this.$store .通过为 root 实例提供 store 选项,store 将被注入到root 的所有子组件中,并且可以作为this.$store在它们上使用。

Therefore, your updated code should be:因此,您更新后的代码应该是:

methods: {
    increment () {
        this.$store.commit('increment')
    },
    decrement () {
        this.$store.commit('decrement')
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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