具体来说,在应用实际加载之前运行的代码。我正在使用vuex
,并且我想做的第一件事(无论用户所走的路线如何)是调度getUser
操作以从API中获取当前的用户详细信息(或者重定向)如果未通过验证)。
如果我将其放在App.vue
mounted
组件中,我认为可能为时已晚?子组件不是在父母之前加载的吗?
答案 0 :(得分:1)
如果我做对了,您想在应用程序初始化之前做一些事情。为此,您可以在应用程序初始化中执行async
方法。像这样的例子:
function initializeApp (vueCreated) {
return new Promise((resolve, reject) => {
switch (vueCreated) {
case false: // "prevue" initialization steps
console.log('vue not yet created, prevue steps happens')
// ...
setTimeout(_ => resolve(), 3500) // async call
break;
case true: // we can continue/prepare data for Vue
console.log('vue created, but waiting for next initialization steps and data')
// ...
setTimeout(_ => resolve('Mounted / shown when app ready'), 3500) // async call
}
})
}
initializeApp(false).then(_ => {
new Vue({
template: '#app',
data: {
content: null
},
async created () {
this.content = await initializeApp(true)
this.$mount('#app')
console.log('all inicialization steps done, data arrived, vue mounted')
}
})
})
我发现一些与您的问题有关的文章可能会对您有所帮助。 Link
答案 1 :(得分:1)
如果您使用的是vue-router
,则可以使用beforeEach
来阻止未经身份验证的用户的某些路由。
您可以阅读更多here。
如果您在这里遇到困难,请提供您尝试使用路由器的代码。
也good example of using navigation guards。
祝你好运!