Vuex 状态或 getter 总是 returns undefined

Vuex state or getters always returns undefined

我已经在 Vuex 4 中构建了一些模块,但我似乎无法从中获取任何数据,可能是它没有保存或者我的逻辑有问题。

store/mutation-types.js

export const SET_LOCALE   = 'SET_LOCALE'
export const SET_LANGUAGE = 'SET_LANGUAGE'

store/index.js

import { createStore } from 'vuex'

const requireContext = require.context('./modules', false, /.*\.js$/)

const modules = requireContext.keys()
    .map(file =>
        [file.replace(/(^.\/)|(\.js$)/g, ''), requireContext(file)]
    )
    .reduce((modules, [name, module]) => {
        if (module.namespaced === undefined) {
            module.namespaced = true
        }
        return { ...modules, [name]: module }
    }, {})
    
const store = createStore({
     modules
})

export default store

store/modules/i18n.js

import * as types from '../mutation-types.js'

export const state = {
    locale: 'en-US',
    language: 'en'
}

export const getters = {
    locale: state => state.locale,
    language: state => state.language
}

export const mutations = {
    [types.SET_LOCALE] (state, { locale }) {
        state.locale = locale;
    },
    [types.SET_LANGUAGE] (state, { language }) {
        state.language = language;
    }
}

export const actions = {
    setLocale ({ commit }, { locale }) {
        commit(types.SET_LOCALE, { locale })
    },
    setLanguage({ commit }, { language }) {
        commit(types.SET_LANGUAGE, { language })
    }
}

component.vue

<script>
    import { mapGetters } from 'vuex'
    
    export default {
        computed: {
            ...mapGetters(
                {
                    language: 'i18n/language'
                }
            ),
            getLanguage () {   
               console.log('I am using the language..')// returns
               console.log(this.$store.getters.language)// returns undefined
            }
        },
    };
</script>

getter 键存储为 "__namespace__/__gettername__"。在你的例子中,它将是 "i18n/language",所以你会这样读它:

this.$store.getters['i18n/language']

示例:

<template>
  <div>{{ getLanguage }}</div>
</template>

<script>
export default {
  computed: {
    getLanguage () {
      return this.$store.getters['i18n/language']
    }
  }
}
</script>

使用VuexmapGetters helper,简单写成:

<template>
  <div>{{ language }}</div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters('i18n', ['language'])
  }
}
</script>