Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject data get in router.beforeEach in my vuejs component?

I use router.beforeEach to protect some view. I fetch my user before entering in my vue. I want to use this user in all my authenticated pages. How can I inject data get in router.beforeEach in my vuejs component?

Here my routes definition:

import Vue from 'vue';
import VueRouter from 'vue-router';
import AuthService from './services/AuthService';

import Index from './pages/Index.vue';

Vue.use(VueRouter);

const routes = [
    {path: '/', name: 'index', component: Index, meta: {requiresAuth: true}},
    ...
];

const router = new VueRouter({
    routes
});

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        AuthService().getUser(user => {
            if (user) {
                next(vm => {
                    vm.user = user
                });
            } else {
                ...
            }
        });
    }
    ...
});

export default router;

here my Index.vue

<template>
    <div>
        {{user}}
    </div>
</template>
<script type="text/ecmascript-6">
    export default {
        data(){
            console.log(this.user);
            console.log(this.$route.user);
            return {}
        },
        mounted(){
            console.log(this.user);
            console.log(this.$route.user);
        }
    }
</script>

Everything is undefined

I don't want to make a beforeRouteEnter in my component because it will make a second API call.

like image 870
Guillaume Vincent Avatar asked Jan 20 '17 08:01

Guillaume Vincent


People also ask

How do I access my vue router in component?

To have the Vue-Router routes be rendered you will need to pass the <router-view> tag inside a Vue component. You could also access the routes from an <a> tag, but this will trigger a page re-render, to avoid this behavior you could use router-link with the to property instead of a href .

How do I reload my Vuejs router?

To reload a route with Vue Route, we can call the this. $router.go() method. If it has no arguments, then it'll reload the current route. This way, it'll notice when the path changes and it'll trigger a reload of the component with new data.

What is beforeEach in Vuejs?

It looks like this beforeEach is being defined inside an initialized component, which means the first routing has already occured. Define it in the router module with your routes instead: const router = new VueRouter({ ... }) router.


2 Answers

I normally separate the files and then import the js file to my page, here is how I implement beforeEach rule:

  1. Routes file:

    import VueRouter from 'vue-router';
    
    let routes = [
      {
        path: '/',
        component: require('./views/Home')
      },
      {
        path: '/about',
        component: require('./views/About'),
      }
    ];
    
    export default new VueRouter({
        routes,
    });
    
  2. Vue App file:

    import router from './routes';
    
    // Here goes my logic
    router.beforeEach((to, from, next) => {
        if ( from.name == 'About' ) {
            next(false);
        } else {
            next();
        }
    });
    
    const app = new Vue({
        el: '#app',
    
        router
    });
    

Hope it helps!

like image 131
Evis Avatar answered Dec 24 '22 23:12

Evis


I see 3 issues:

1) The vue-router documentation shows you can access the vm in next in a component's beforeRouteEnter, not a global beforeEach.

2) In next, the vm has already been created because you can access its properties, so you wouldn't be able to see this.user in the data function. Maybe in the mounted function, but we don't know if the vm is returned before or after the component is mounted.

3) You shouldn't set top-level properties on a vm because they will not be reactive: see https://vuejs.org/v2/api/#data and https://vuejs.org/v2/api/#Vue-set .

Perhaps your AuthService could store the user and your components get the user from there?

like image 36
Philip Holly Avatar answered Dec 25 '22 00:12

Philip Holly