我的 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'])
}
答案 0 :(得分: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)
}
}