gpt4 book ai didi

javascript - vuex 状态和 getter 已更新,但计算值没有反应

转载 作者:行者123 更新时间:2023-12-03 02:05:25 24 4
gpt4 key购买 nike

我目前正在尝试实现一个简单的主题切换功能,其中事件主题保存在 vuex 存储状态中。按下按钮后,主题应该会切换。

Here is a video with vue-devtools, demonstrating the problem

正如您在视频中看到的,数据已在状态中成功更改,并且 getter 返回正确的值,但是我的组件的计算值不会对更改使用react。

/src/main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import Vuex from 'vuex'
import Icon from 'vue-awesome/components/Icon'

Vue.use(Vuex)
Vue.component('icon', Icon)

new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})

/src/App.vue

<template>
<div id="app"
:class="themeName">
<div id="themeSwitch"
v-on:click="switchTheme">
<icon name="lightbulb"
:class="themeName"></icon>
</div>
<router-view/>
</div>
</template>

<script>
import "vue-awesome/icons/lightbulb"

import { mapState, mapGetters } from "vuex"

var app = {
name: "App",
beforeCreate() {
this.$store.dispatch("LOAD_THEME")
},
computed: {
themeName() {
return this.$store.getters.GET_THEME
}
},
methods: {
switchTheme: function(event) {
this.$store.dispatch("SWITCH_THEME")
}
}
};

export default app;
</script>

/src/store/index.js

import Vue from "vue/dist/vue.common.js"
import Vuex from "vuex/dist/vuex.js"
import * as Cookies from "tiny-cookie"

Vue.use(Vuex);

const themes = ["dark", "light"];
const store = new Vuex.Store({
state: {
themeName: ''
},
actions: {
LOAD_THEME({ commit, state }) {
if (state.themeName.length > 0) return

var themeId = Cookies.getCookie("themeId")
if (!themeId) commit("SET_COOKIE", themeId = 1)

commit("SET_THEME", themeId)
},
SWITCH_THEME({ commit, state }){
var id = themes.indexOf(state.themeName) < 1 ? 1 : 0
commit("SET_THEME", id)
commit("SET_COOKIE", id)
}
},
getters: {
GET_THEME: state => {
return state.themeName
}
},
mutations: {
SET_COOKIE: (state, id) => {
Cookies.setCookie("themeId", id, { expires: "1M" })
},
SET_THEME: (state, id) => {
state.themeName = themes[id]
}
}
});

export default store;

我尝试了几种不同的计算属性方法,这些方法是我在互联网上找到的。但它们都没有任何区别。

computed: mapState({
themeName: state => state.themeName
})

computed: {
...mapGetters({
themeName: 'GET_THEME'
})
}

如果我使用数据而不是计算,并且手动设置字符串,它可以工作,但如果我必须手动设置每个组件中的每个局部变量,那就违背了状态的目的。

如有任何帮助,我们将不胜感激。

最佳答案

看起来您正在使用两个不同的 Vue 实例。在 main.js 中,您正在导入 vue,但在 src/store/index.js 中,您正在导入 vue/dist/vue。 common.js 并告诉每个人使用 Vuex。尝试使用 vue 进行这两个导入。

关于javascript - vuex 状态和 getter 已更新,但计算值没有反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49833984/

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