In vue.js, where can I place “app initialization” code?

て烟熏妆下的殇ゞ 提交于 2021-02-10 11:55:48

问题


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).

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


回答1:


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




回答2:


If you are using vue-router you can use beforeEach to prevent some routes of unauthenticated users.

You can read more here.

If you get stuck here provide code what you tried with router.

Also good example of using navigation guards.

Good luck!



来源:https://stackoverflow.com/questions/57544329/in-vue-js-where-can-i-place-app-initialization-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!