动态路由上的页面重新加载会清空 Vuex 存储 (NuxtJS)
Page reload on a dynamic route empties Vuex store (NuxtJS)
我的 Nuxt
页面是这样排序的:
pages
\ agencies
_agency.vue
error.vue
index.vue
其中 _agency.vue
显示存储在我的 store
中的数据,特别是我的 agencies
数组:
// store/index.js
import Vuex from 'vuex';
const createStore = () =>
new Vuex.Store({
state: {
agencies: []
},
mutations: {
changeAgencies(state, agencies) {
state.agencies = agencies.sort(
(agencyA, agencyB) =>
agencyA.weather.currently.cloudCover - agencyB.weather.currently.cloudCover,
);
}
}
});
export default createStore;
所述数组使用fetch
方法填充在index
页面中。
一切正常,除了当我导航到 /agencies/myAgency 并重新加载页面时,这给了我以下错误:
Cannot read property 'weather' of undefined
好像我商店的数据在重新加载时消失了。
现在我知道数据不会在重新加载之间持续存在,所以我试图使用 vuex-persistedstate 来解决我的问题但无济于事。
问题的根源是我上面所说的吗?我该如何用 NuxtJS
?
解决它
是的,重新加载时,存储中的数据将会消失。正确的方法是,如果整个应用程序都需要数据 -> 在 nuxtServerInit 操作
中加载它
如果需要几页的数据,你只需要检查数据是否可用,如果不可用,则在fetch方法中加载它。
您也可以尝试使用 vuex perrsisted state,但它可能有其自身的怪癖。 https://github.com/robinvdvleuten/vuex-persistedstate/issues/54#issuecomment-414605839
这样做,你的问题就会解决
npm install vuex-persistedstate
// store/index.js
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'
const createStore = () =>
new Vuex.Store({
plugins: [createPersistedState()],
state: {
agencies: []
},
mutations: {
changeAgencies(state, agencies) {
state.agencies = agencies.sort(
(agencyA, agencyB) =>
agencyA.weather.currently.cloudCover - agencyB.weather.currently.cloudCover,
);
}
}
});
export default createStore;
我的 Nuxt
页面是这样排序的:
pages
\ agencies
_agency.vue
error.vue
index.vue
其中 _agency.vue
显示存储在我的 store
中的数据,特别是我的 agencies
数组:
// store/index.js
import Vuex from 'vuex';
const createStore = () =>
new Vuex.Store({
state: {
agencies: []
},
mutations: {
changeAgencies(state, agencies) {
state.agencies = agencies.sort(
(agencyA, agencyB) =>
agencyA.weather.currently.cloudCover - agencyB.weather.currently.cloudCover,
);
}
}
});
export default createStore;
所述数组使用fetch
方法填充在index
页面中。
一切正常,除了当我导航到 /agencies/myAgency 并重新加载页面时,这给了我以下错误:
Cannot read property 'weather' of undefined
好像我商店的数据在重新加载时消失了。
现在我知道数据不会在重新加载之间持续存在,所以我试图使用 vuex-persistedstate 来解决我的问题但无济于事。
问题的根源是我上面所说的吗?我该如何用 NuxtJS
?
是的,重新加载时,存储中的数据将会消失。正确的方法是,如果整个应用程序都需要数据 -> 在 nuxtServerInit 操作
中加载它如果需要几页的数据,你只需要检查数据是否可用,如果不可用,则在fetch方法中加载它。
您也可以尝试使用 vuex perrsisted state,但它可能有其自身的怪癖。 https://github.com/robinvdvleuten/vuex-persistedstate/issues/54#issuecomment-414605839
这样做,你的问题就会解决
npm install vuex-persistedstate
// store/index.js
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate'
const createStore = () =>
new Vuex.Store({
plugins: [createPersistedState()],
state: {
agencies: []
},
mutations: {
changeAgencies(state, agencies) {
state.agencies = agencies.sort(
(agencyA, agencyB) =>
agencyA.weather.currently.cloudCover - agencyB.weather.currently.cloudCover,
);
}
}
});
export default createStore;