E
E
Evgeny Khripunov2018-07-09 20:31:48
Vue.js
Evgeny Khripunov, 2018-07-09 20:31:48

How can you prevent a vue component from being rendered based on state in vuex?

There is a SPA application with access via api. There is, for example, a state in vuex : isUserLogged = true/false (whether the user is logged in to the site), or the necessary input parameters for the component.
What is the best way to check if the vue component is rendered to the user? This implementation seems a bit irrational.

<template v-if="isUserLogged">
...
</template>

Maybe you can do a check in the life cycles of the component? For example in beforeCreate() or in create() ?
The backend is implemented on laravel and the problem arises if an unauthorized user in the browser line enters an address that should be available only to an authorized user or have any input parameters.
In web.php file
Route::get('/{any}', '[email protected]')->where('any', '.*');

The api file contains middleware that prohibits the "guest" from performing any actions, but I would like to somehow restrict its access / display to the pages themselves. Or, so that an authorized user cannot manually enter the address of a page that requires any input parameters from the previous page and see the page.
Update:
Evgeny Kulakov , thanks, the problem turned out to be that router.beforeEach(...) depends on the location in the app.js
file It was like this and apparently, according to the logic, the vue instance was first created, and then the rule router.beforeEach( ):
const router = new VueRouter({
    mode: 'history',
    routes,    
});

const app = new Vue({
    el: '#app',
    store,
    components: {MainApp},
    router,
});
router.beforeEach((to, from, next) => {    
    if (to.matched.some(route => route.meta.requiresAuth) && (!store.state.isLoggedIn)) {       
        next({name: 'login'});
        return
    }    
    if (to.path === '/login' && store.state.isLoggedIn) {
        next({name: 'dashboard'});
        return
    }
    next()
});

Changed the order and it worked:
const router = new VueRouter({
    mode: 'history',
    routes,    
});
router.beforeEach((to, from, next) => {   
    if (to.matched.some(route => route.meta.requiresAuth) && (!store.state.isLoggedIn)) {        
        next({name: 'login'});
        return
    }    
    if (to.path === '/login' && store.state.isLoggedIn) {
        next({name: 'dashboard'});
        return
    }
    next()
});
const app = new Vue({
    el: '#app',
    store,
    components: {MainApp},
    router,
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question