首页 文章

vuex状态和getter已更新,但计算值不响应

提问于
浏览
0

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

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

正如您在视频中看到的那样,数据在状态中成功更改,并且getter返回正确的值,但是我的组件的计算值不会对更改做出反应 .

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

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

任何帮助,将不胜感激 .

1 回答

  • 1

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

相关问题