gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:37:28 25 4
gpt4 key购买 nike

我在 vuex 上苦苦挣扎了几个小时。这是我第一次使用它,尽管我按照文档进行操作,但有些东西不起作用,但我真的想不通。

所以我有第一个不起作用的 vuex 文档示例。我有一个返回存储状态的 count 计算值。

它显示在页面上。起始值为 0, View 显示为 0。但按下按钮不会改变显示。

如果我直接将商店以常量形式放入 App.js 中,则没问题。

我知道我错过了一些东西......

homeStore.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

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

最佳答案

利用 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')
}
}
})

使用 this.$store.dispatch('increase') 访问操作方法以增加计数,反之亦然以减少

关于javascript - 为什么状态不在计算中更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com