简体   繁体   中英

Vuex state not updating from local storage

I'm having some problems getting the Vuex state to update from local storage when visiting a route directly from the address bar in an incognito window.

When visiting the route /shop/:key? directly (for example clicking a link from an email) the mounted action getDetail is executed and local storage is updated but the state is not reevaluated - it still says undefined as if the key doesn't exist.

Is there a way to get the state to be reevaluate or does it have to be updated in the setDetail mutation?

const state = {
    key: localStorage.getItem('key'),
    details: null
}

const actions = {
    async getDetail({ commit }, key) {
        const details = await Service.detail(key)
        commit('setDetail', details)
    }
}

const mutations = {
    setDetail(state, details) {
        state.details = details
    }
}

const Service = {
    detail: async function(key) {
        const url = `/store/${key}/`
        const response = await ApiService.get(url)
        localStorage.setItem('key', key)
        return response.data
    }
}

The state will be re-evaluated if a mutation (or action) occurs. You could change the state directly but this is advised against as it breaks reactivity.

LocalStorage is not reactive and as such you need to update the state using a mutation or an action .

localStorage might be returning a string instead of a boolean which if not properly handled could lead to vuex not updating state accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM