gpt4 book ai didi

javascript - 将 Vuex 与 Nuxt.js 一起使用——正确的方法

转载 作者:行者123 更新时间:2023-12-03 14:42:17 25 4
gpt4 key购买 nike

我尝试将 Vuex 添加到我的 Nuxt.js 项目中。我制作了一个自定义 ligthbox 并通过所有页面共享,我将代码写入默认布局页面。
从页面中,要隐藏或显示 ligthbox,我需要更改状态值。这是“存储”文件夹中的所有模块:

// state.js
export const state = () => ({
lightbox: false,
});
// getters.js
export const getters = {
getLightbox(state)
{
return state.lightbox
},
}
// actions.js
export const actions = {
showLightbox({commit})
{
commit('UPDATE_LIGHTBOX', true)
},
hideLightbox({commit})
{
commit('UPDATE_LIGHTBOX', false)
},
}
// mutations.js
export const mutations = {
UPDATE_LIGHTBOX(state,value)
{
state.lightbox = value
},
}
然后,当我尝试从方法中调用“this.$store.state.lightbox”时,我收到 500 错误:
TypeError: Cannot read property 'getters' of undefined
即使我尝试使用这种方式,我也会得到同样的错误:
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['getLightbox']),
lightboxState()
{
return this.getLightbox
},
}
mounted()
{
console.log( this.lightboxState )
}
}
后来我尝试使用 asyncData 但控制台打印一个“未定义”值:
export default {
asyncData({ store })
{
console.log('Store =',store);
}
}
那么,在 Nuxt.js 中使用 Vuex 的正确方法是什么?也许我需要在“nuxt.config.js”中添加其他内容?

最佳答案

如果您对 state.js 使用单独的文件, getters.js , mutations.jsactions.js ,它们应该只有一个默认导出。
所以而不是

// getters.js
export const getters = ...
你应该使用
// getters.js
export default {
getLightbox: state => state.lightbox
}
这适用于您的 store 中的所有文件。目录。
https://nuxtjs.org/guide/vuex-store/#modules-mode

关于javascript - 将 Vuex 与 Nuxt.js 一起使用——正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62504794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com