jun*_*ihh 6 javascript vue.js vuex nuxt.js
我尝试将 Vuex 添加到我的 Nuxt.js 项目中。我制作了一个自定义 ligthbox 并通过所有页面共享我将代码写入默认布局页面。
从页面中,要隐藏或显示 ligthbox,我需要更改状态值。这是“store”文件夹中的所有模块:
// state.js
export const state = () => ({
lightbox: false,
});
Run Code Online (Sandbox Code Playgroud)
// getters.js
export const getters = {
getLightbox(state)
{
return state.lightbox
},
}
Run Code Online (Sandbox Code Playgroud)
// actions.js
export const actions = {
showLightbox({commit})
{
commit('UPDATE_LIGHTBOX', true)
},
hideLightbox({commit})
{
commit('UPDATE_LIGHTBOX', false)
},
}
Run Code Online (Sandbox Code Playgroud)
// mutations.js
export const mutations = {
UPDATE_LIGHTBOX(state,value)
{
state.lightbox = value
},
}
Run Code Online (Sandbox Code Playgroud)
然后,当我尝试从方法中调用“this.$store.state.lightbox”时,我收到 500 错误:
TypeError: Cannot read property 'getters' of undefined
Run Code Online (Sandbox Code Playgroud)
即使我尝试使用这种方式,我也会遇到同样的错误:
TypeError: Cannot read property 'getters' of undefined
Run Code Online (Sandbox Code Playgroud)
后来我尝试使用 asyncData 但控制台打印一个“未定义”值:
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['getLightbox']),
lightboxState()
{
return this.getLightbox
},
}
mounted()
{
console.log( this.lightboxState )
}
}
Run Code Online (Sandbox Code Playgroud)
那么,在 Nuxt.js 中使用 Vuex 的正确方法是什么?也许我需要向“nuxt.config.js”添加其他内容?
如果您使用单独的文件state.js
、getters.js
和,mutations.js
则actions.js
它们应该只有一个默认导出。
所以而不是
// getters.js
export const getters = ...
Run Code Online (Sandbox Code Playgroud)
你应该使用
// getters.js
export default {
getLightbox: state => state.lightbox
}
Run Code Online (Sandbox Code Playgroud)
这适用于目录中的所有文件store
。
请参阅https://nuxtjs.org/guide/vuex-store/#modules-mode
归档时间: |
|
查看次数: |
2925 次 |
最近记录: |