簡體   English   中英

將 Vuex 與 Nuxt.js 一起使用 - 正確的方法

[英]Using Vuex with Nuxt.js - The right way

我嘗試將 Vuex 添加到我的 Nuxt.js 項目中。 我制作了一個自定義 ligthbox 並通過所有頁面共享,我將代碼寫入默認布局頁面。

從頁面中,要隱藏或顯示 ligthbox,我需要更改 state 值。 這是“存儲”文件夾中的所有模塊:

// 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);
    }
}

那么,將 Vuex 與 Nuxt.js 一起使用的正確方法是什么? 也許我需要在“nuxt.config.js”中添加其他內容?

如果您為state.jsgetters.jsmutations.jsactions.js使用單獨的文件,它們應該只有一個默認導出。

所以而不是

// getters.js
export const getters = ...

你應該使用

// getters.js
export default {
  getLightbox: state => state.lightbox
}

這適用於store目錄中的所有文件。

https://nuxtjs.org/guide/vuex-store/#modules-mode

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM