【问题标题】:NuxtJS store state variables keeps returning undefinedNuxtJS 存储状态变量不断返回 undefined
【发布时间】:2021-06-27 02:32:10
【问题描述】:

我的 NuxtJs 商店有问题,它总是返回 undefined 我发现了很多类似的问题,但没有一个能解决问题。这是我的代码:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state(){ 
        return{
            count: 500
        }
    },
    getters: {
        getCount: (state) => {
            state.count
        }
    },
})

然后我试着用这种方式得到它

this.$store.getters.getCount

也试过了

computed: {
        ...mapGetters(['getCount'])
},
created(){
        console.log("count: "+this['getCount'])
}

这是错误:

【问题讨论】:

    标签: vue.js vuex nuxtjs


    【解决方案1】:

    Nuxt 会自动为您设置商店,因此您无需实例化您自己的商店。

    删除设置代码:

    // REMOVE ALL THIS:
    //
    // import Vue from 'vue'
    // import Vuex from 'vuex'
    //
    // Vue.use(Vuex)
    //
    // const store = new Vuex.Store({/*...*/})
    

    并使用以下内容创建store/index.js

    export const state = () => ({
      count: 500,
    })
    
    export const getters = {
      getCount: state => state.count,
    }
    

    现在,您可以在组件中访问商店:

    export default {
      mounted() {
        console.log('count', this.$store.getters.getCount)
      }
    }
    

    demo

    【讨论】:

    • Nuxt 自动从store/ 下的*.js 文件创建模块。你不需要导入它们,也不需要将它们放在store/下的任何目录结构中。
    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多