6

I'm trying to access the router from a plain .js file in a Quasar project but I'm not being able to. I have search how to do it in vue and people seem to import the Router object from /src/router/index, like this: import { Router } from 'src/router/index'.

But Quasar doesn't expose the Router object, but a function called route that accepts another function as an argument that returns the Router object.

export default route(function (/* { store, ssrContext } */) {
    const createHistory = process.env.SERVER
        ? createMemoryHistory
        : process.env.VUE_ROUTER_MODE === 'history'
        ? createWebHistory
        : createWebHashHistory;

    const Router = createRouter({
        scrollBehavior: () => ({ left: 0, top: 0 }),
        routes,

        // Leave this as is and make changes in quasar.conf.js instead!
        // quasar.conf.js -> build -> vueRouterMode
        // quasar.conf.js -> build -> publicPath
        history: createHistory(process.env.MODE === 'ssr' ? void 0 : process.env.VUE_ROUTER_BASE),
    });
    return Router;
});

How can I use the Router object outside a SFC with Quasar?

Paolo
  • 20,112
  • 21
  • 72
  • 113
Héctor
  • 399
  • 3
  • 16

1 Answers1

8

Ideally, you shouldn't need the router outside Vue components, outside boot files, outside src/router/index.js, outside src/store/index.js, and except the places where you define a function that gets called in Vue files(e.g. composables/helpers). Here are all the ways to access the router, both inside and outside SFCs:

Inside .vue files:

  • Composition API(inside setup() or <script setup>): const router = useRouter()
  • Options API: this.$router
  • Inside the <template> section: @whatever="$router.push('...')"

Inside boot files:

// src/boot/whatever.js
export default boot(({ router }) => {
  router.beforeEach(...)
})

Inside src/router/index.js(using boot files are better):

const router = createRouter(...)

router.beforeEach(...)

Inside a function/composable that you use in .vue files:

// /src/composables/whatever.js
export function useWhatever() {
  const router = useRouter()

  // ...

  function changeRoute () {
    router.push('...')
  }

  return {
    changeRoute,
    // ...
  }
}

// Inside setup() or <script setup>
const { changeRoute } = useWhatever()
changeRoute()

As a last resort / lazy way (won't work with SSR):

// src/router/index.js
// Remove export default function route(...), and use it like this:
const router = createRouter(...)
export default router;

// src/whatever.js
import router from 'src/router';

router.push('...');
Yusuf Kandemir
  • 810
  • 7
  • 16