在vue.js中,我可以在哪里放置“应用程序初始化"?代码? [英] In vue.js, where can I place "app initialization" code?

查看:40
本文介绍了在vue.js中,我可以在哪里放置“应用程序初始化"?代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是在应用实际加载之前运行的代码.我正在使用 vuex 并且我想做的第一件事(无论用户在什么路线上)是调度一个 getUser 操作以从API(或者,如果未通过身份验证,则重定向).

Specifically, code that runs before the app actually loads. I'm using vuex and the first thing I want to do (regardless of what route the user is on) is to dispatch a getUser action to get currently user details from the API (or alternatively, redirect if not authenticated).

如果我将它放在我的 App.vue mounted 组件中,我认为可能为时已晚?子组件不是在父组件之前加载吗?

If I place it in my App.vue mounted component, I believe it might be too late? Don't children components load before parents?

推荐答案

如果我猜对了,你想在应用程序初始化之前做一些事情.为此,您可以在应用程序初始化中执行 async 方法.像这样的例子:

If I get it right you want to do something before the application initialize. For that you can just perform async method in app initialization. Something like that as an example:

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')
    }
  })
})

我找到了一些与您的问题相关的文章,可能对您有所帮助.链接

I have found some article related to your question may be this help you out. Link

这篇关于在vue.js中,我可以在哪里放置“应用程序初始化"?代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆