伙计。我是新手程序员。
我对 nuxt 使用 vuex 获取 api 数据有疑问。
所以 vue 中的数据调用值为 null 但在开发工具中 vue 有数据。
如何在 nuxt 中使用 getter。
在 getter 和 state chachange 中:menuList 有数组数据,但在组件中没有数据。
Component MenuList> 计算的> menuList:未定义。
这是我的 menu_list.vue 代码。
computed: {
menuList () {
// eslint-disable-next-line no-console
return this.$store.getters.getMenuList
}
},
beforeCreated () {
// eslint-disable-next-line no-console
console.log(this.$store.state)
this.$store.dispatch('chachang/fetchMenu')
},
created () {
// eslint-disable-next-line no-console
console.log(this.$store.state)
this.$store.dispatch('chachang/fetchMenu')
}
这个 vuex 代码。 茶场/state.js
export default () => ({
menuList: []
})
茶场/actions.js
export default {
async fetchMenu ({ commit }) {
const response = await this.$axios.get('https://hlkittipan.github.io/rock-paper-scissors/menu.json')
commit('SET_MENU', response.data)
}
}
Chachang/mutations.js
export default {
SET_MENU (state, menu) {
state.menuList = menu
}
}
茶仓/getters.js
export default {
getMenuList: (state) => {
return state.menuList
}
}
这家商店/index.js
import chachangActions from './chachang/actions'
import chachangStates from './chachang/state'
import chachangGetters from './chachang/getters'
import chachangMutations from './chachang/mutations'
export const state = () => ({
...chachangStates.state,
})
export const mutations = {
...chachangMutations.mutations,
}
export const actions = {
...chachangActions.actions
}
export const getters = {
...chachangGetters.getters
}
我建议你使用从 vuex 导入的 mapActions 和 mapGetters。
从'vuex'导入{ mapGetters, mapActions }
export default{
...
methods:{
...mapActions('chachang',[ 'fetchMenu' ])
},
mounted(){
this.fetchMenu() // better to use fetchData instead
}
computed:{
...mapGetters('chachang', [ 'menuList' ])
}
..
}
试试这个。
async beforeMount () {
const data = await this.$store.dispatch('chachang/fetchMenu')
// eslint-disable-next-line no-console
console.log(data)
},computed: {
menuList () {
// eslint-disable-next-line no-console
return this.$store.getters['chachang/getMenuList']
}
},