Hide component outside the router-viewer

2

I'm using Vue Rotuer to control the routes of my project, so I've seen the need to use Navigation Guards .

<script>
    export default{
        beforeRouteEnter(to, from, next){
            if(to.meta.adminOnly === false){
                //alert('f')
                next()
            }
        }
    }
</script>

At the same time, I saw a difficulty, because it is a dashboard , I have the login page and the other pages. In my page app.vue I have the following structure.

<template>
    <div id="app">
        <Menu></Menu>
        <router-view class="containerView"></router-view>
    </div>
</template>

The component Menu has all my menu side and top, because I want to change the page, it remains and only the contents change, so I left out the <router-view></router-view> .

However, I'm having a hard time hiding it, if my user is not logged in (it's on the login page), and I could not solve it, I tried to use beforeRouterEnter on page app.vue to validate on what page user is and if the page contains meta adminOnly , but it did not work, and I did not want to use localStorage to do this validation, because it would keep my system too insecure.

    
asked by anonymous 04.10.2017 / 22:17

1 answer

1

The tools that the vue-router has are:

  • beforeEach
  • fields meta

Configures each route that needs authentication with meta: { requiresAuth: true } . You can put this in children as it is in the documentation:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

Then check this before each route. The beforeEach passes to which is the route that was requested. There you can check if this route needs authorization. If you need and are not logged in, redirects to the login page.

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // make sure to always call next()!
  }
})

The part of keeping the information from being logged in or there are no different ways. You can save only a variable with state true|false , via localStorage etc.

There is a video about this useful: link

    
04.10.2017 / 23:07