如何加载 JSON 配置文件并让 Vue 应用程序等待它?
How can I load JSON config file and let the Vue app wait for this?
我的典型情况是:
- 一个 Vue 应用程序(用 webpack 打包,顺便说一句)
- 用于配置应用程序的单独配置文件
配置文件应该不包含在 webpacked 部署包中,因为它依赖于服务器(数据库凭据等)
出于某种原因,我不打算在这里详细说明,我将配置保存在 JSON 文件中。
所以问题是:
我如何延迟 "starting" Vue 应用程序直到 JSON 配置文件从后端加载(并解析)?
我知道如何加载和解析,但对我来说问题是特定于 Vue 的:在开始整个事情之前 "wait" 最好的做法是什么?
(App.vue
组件中的 beforeCreate
生命周期挂钩是可行的方法吗?它是否适合异步任务,例如通过网络加载 JSON 文件?
我用来解决此类问题的一种方法是使用 router.beforeEach。这是我的代码示例:
router.beforeEach(async (to, from, next) => {
if (!store.state.initialized) {
// the store initialize will set initialized to true
await store.dispatch('initialize')
}
// if user not logged in or the route is not public
if (!store.state.user && !to.meta.public) {
next('/login')
} else {
next();
}
});
我的典型情况是:
- 一个 Vue 应用程序(用 webpack 打包,顺便说一句)
- 用于配置应用程序的单独配置文件
配置文件应该不包含在 webpacked 部署包中,因为它依赖于服务器(数据库凭据等)
出于某种原因,我不打算在这里详细说明,我将配置保存在 JSON 文件中。
所以问题是:
我如何延迟 "starting" Vue 应用程序直到 JSON 配置文件从后端加载(并解析)?
我知道如何加载和解析,但对我来说问题是特定于 Vue 的:在开始整个事情之前 "wait" 最好的做法是什么?
(App.vue
组件中的 beforeCreate
生命周期挂钩是可行的方法吗?它是否适合异步任务,例如通过网络加载 JSON 文件?
我用来解决此类问题的一种方法是使用 router.beforeEach。这是我的代码示例:
router.beforeEach(async (to, from, next) => {
if (!store.state.initialized) {
// the store initialize will set initialized to true
await store.dispatch('initialize')
}
// if user not logged in or the route is not public
if (!store.state.user && !to.meta.public) {
next('/login')
} else {
next();
}
});