vuex状态和getter已更新,但计算值未作出反应

时间:2018-04-14 17:02:12

标签: javascript vue.js vuejs2 vuex

我目前正在尝试实现一个简单的主题切换功能,其中活动主题以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 个答案:

答案 0 :(得分:1)

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