Search code examples
vue.jsvuejs2vue-routervue-mixin

Vue.js / Mixins - Is there a way to get the global mixin-object outside of the vue component?


I am new with Vue.js

I am using Vue.js 2.4.4. I have created the global mixin in my app.js file:

...
import router from './router'
...(some imports and plugins definitions)

Vue.use(VeeValidate);
Vue.component(VuePassword);
...

Vue.mixin({
    data: function(){
        return {
            get auth(){
                return Auth;
            }
        }
    }
    });

const app = new Vue({
    el: '#root',
    template: `<app></app>`,
    components: { App },
    router
});

This mixin imports some Auth object with validation methods e.t.c which needed to be in every component. All of my components can check this mixin and it's working fine.

But I need to check the auth state after every route request, and I want to use my currently existing mixin, so I am trying to make something like this in my router.js file:

import Vue from 'vue'
import VueRouter from 'vue-router'
...

Vue.use(VueRouter);

const router = new VueRouter({
    routes:[
      ...
    ]
});
router.beforeEach((to, from, next) => {
    if(to.meta.requiresAuth) {
        if(...call to mixin method) {
            next();
        } else {
            next('/');
        }
    } else {
        next();
    }
});

export default router

Question: Is there a way to get the global mixin object and change it's inner values or can you please give some small advise or example what is the right solution to this kind of tasks? Or should I use the plugins instead of mixins?


Solution

  • I would rather create a seperate file for auth and not make it a mixin. Then using Vue.use() which will set auth on the vue object. A sample of what the files might look like:

    auth.js

    export default function(Vue) {
        Vue.auth = {
            // do your auth logic
        }
    }
    

    Then in your main js file main.js

    import Auth from './auth.js'
    Vue.use(Auth);
    

    Then you should be able to use Vue.auth Another option would be keep using the mixin and pass the value to a store (like vuex) or create your own if your project is small...