Restrict access to routes if not logged Vuejs

5

I am developing a Dashboard and I have doubts about how to forbid access to rotas if they are not logados , so I thought of some solutions that would use localStorage , but none is a right solution .

What would be the correct way to do this? I saw many people have this doubt, and I could not find a solution to that.

    
asked by anonymous 02.10.2017 / 16:10

1 answer

0

For those of you who have had the same difficulty with the documentation as I do, follow the code and a brief explanation.

In my main.js I set globally

router.beforeEach((to, from, next) => {
    console.log(to)
    if(to.name == 'Dashboard'){
        alert('dashboard')
    }else{
        next()
    }

})

With this, it is already possible to restrict access without the permission (I did not do any validation in this example), however, when trying to access via URL is still possible, however, I was able to solve with the following code in my page Dashboard

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

With this, it would be enough to verify if the user is logged in, if it were not, he would send it back to the login page / .

    
03.10.2017 / 22:18