[Vuejs]-Whats the simplest and proper way to route in a template

0πŸ‘

βœ…

Its simpler than I thought. I believe the answer is events. The span can simply change to:

<span v-else @load="$router.push('/account')"/>

<span v-else :class="authorized ? '' : $router.push('/account')"/>
  1. Its even simpler because its a one liner
  2. It will work even after mounted() has already fired and authorized becomes false
  3. Actually, I now can delete similar logic in mounted() (DRY principle)

EDITS:
After proper testing I found it actually does not work with my first @load event example.

0πŸ‘

first of all, you do not need to use this in the template.

If you want to route them based on the authorized value, you could probably use a watcher.

Alternatively, I would probably do something in mounted which checks if the user can be there. E.g.

async mounted ()
{
    const authorized = await fetch("something")
    if (!authorized)
    {
        this.$router.push('/account')
    }
}

Leave a comment