Vuex 状态或 getter 总是返回 undefined

时间:2021-06-05 18:26:35

标签: vue.js vuex vuex-modules

我在 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>

1 个答案:

答案 0 :(得分:1)

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>

使用Vuex mapGetters helper,简单写成:

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

<script>
import { mapGetters } from 'vuex'

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