[Vuejs]-Dynamic render function in Vue instance based on authentication check

0πŸ‘

How can I fix this? I think I should use await but I can’t get it to work properly.

It depends on what is this.$auth.check() return. If it returns a promise, the answer is yes you should use await.

But unfortunately render function must be synchronous. What you can do is use one more wrapper component.

new Vue({
  render(createElement) {
    return createElement({
      data: () => ({
        component: null
      }),
      async created() {
        this.component = await checkAuth() ? App : Login
      },
      render(createElement) {
        return createElement(this.component)
      }
    })
  }
}).$mount('#app')

Demo

Note:

  • I would prefer to create a wrapper component as single-file component.

  • It seems you are using vue-router you might consider to use Navigation Guards instead.

Update

As you may be already notice you have no need a wrapper component at all.

new Vue({
  data: () => ({
    component: null
  }),
  async created() {
    this.component = await checkAuth() ? App : Login
  },
  render(createElement) {
    return createElement(this.component)
  }
}).$mount('#app')

Leave a comment