Search code examples
vue.jsvue-routervuejs3vue-composition-api

Vue 3 access to app level provided instances from vue-router


I want to write some complicated guard logics in vue-router in Vue 3 to protect entering some routes according to store and my other provided modules. For example, I want to check if user profile info is present or not:

router.afterEach((to, from) => {
    console.log('store: ', useStore());
    const puex = usePuex();
    puex.isReady().then(() => {
        const me = puex.me.compute();
        watch(me, (...params) => console.log('router: ', ...params));
    });
});

In the above code, useStore and usePuex both try to inject store and puex instances from Vue app which are provided while being used in main.js bootstrap. But both use functions return undefined and I guess that the inject in this scope searches a different place where app-level provided instances do not exist.
So how can I inject them in the router file, or in other words how can I get store and puex instance using useStore and usePuex here?


Solution

  • I have found a way according this question but I still don't know if it is the best available solution. I can export the app instance from main.js file and then use app.$store and app.$puex instead. Although it works, I still think about a better solution to inject the store and puex instance using use functions (inject).