确保 Vuex Store 在渲染组件之前完全初始化
Ensure that Vuex Store is fully inialized before rendering component
我一直在使用 Optimistic Offline-First Apps With Vuex 中描述的方式在重新加载期间保留我的 Vuex 实例。我已经把相关部分复制到这里了。
但是有一个问题。在组件安装和正在应用的缓存存储之间似乎存在竞争条件。
const store = new Vuex.Store({
state: {
initialized: false,
},
mutations: {
loadFromCache(state, cached) {
if (cached) {
Object.keys(cached).forEach((key) => {
state[key] = Object.assign({}, state[key], cached[key]);
});
}
state.initialized = true;
},
}
});
function startLoadFromCache() {
if (store.initialized) {
return Promise.resolve();
}
return getState()
.then(state => store.commit('loadFromCache', state));
}
startLoadFromCache();
new Vue({
el: '#app',
components: { App },
template: '<App/>',
store
});
作为getState()
returns 承诺,变更不会同步提交。那我怎么可能:
- 阻止执行直到存储完全初始化
- 检测到商店未初始化并且可能同时显示微调器?
您可以做的是动态创建渲染组件
<div v-if="activeComponent">
<component :is="activeComponent"></component>
</div>
然后 return 来自计算 属性 的组件。
computed: {
activeComponent(){
return this.$store.state.initialized ? App : null;
}
}
如果您正在使用 vue-router
,您可以使用 beforeEach
守卫来防止在应用程序初始化之前到达渲染页面。
我一直在使用 Optimistic Offline-First Apps With Vuex 中描述的方式在重新加载期间保留我的 Vuex 实例。我已经把相关部分复制到这里了。
但是有一个问题。在组件安装和正在应用的缓存存储之间似乎存在竞争条件。
const store = new Vuex.Store({
state: {
initialized: false,
},
mutations: {
loadFromCache(state, cached) {
if (cached) {
Object.keys(cached).forEach((key) => {
state[key] = Object.assign({}, state[key], cached[key]);
});
}
state.initialized = true;
},
}
});
function startLoadFromCache() {
if (store.initialized) {
return Promise.resolve();
}
return getState()
.then(state => store.commit('loadFromCache', state));
}
startLoadFromCache();
new Vue({
el: '#app',
components: { App },
template: '<App/>',
store
});
作为getState()
returns 承诺,变更不会同步提交。那我怎么可能:
- 阻止执行直到存储完全初始化
- 检测到商店未初始化并且可能同时显示微调器?
您可以做的是动态创建渲染组件
<div v-if="activeComponent">
<component :is="activeComponent"></component>
</div>
然后 return 来自计算 属性 的组件。
computed: {
activeComponent(){
return this.$store.state.initialized ? App : null;
}
}
如果您正在使用 vue-router
,您可以使用 beforeEach
守卫来防止在应用程序初始化之前到达渲染页面。