STARTING POINT
Within the file main.js
(the one where all modules are installed and a Vue
instance is created, like in src/main.js
):
const vm = new Vue({
el: '#app',
router,
store,
apolloProvider,
components: { App },
template: '<App/>'
})
export { vm }
This serves as an example, with focus on const vm
and router
in our context.
In your store
:
import { vm } from '@/main'
yourMutation (state, someRouteName) {
vm.$router.push({name: someRouteName})
}
P.S. By using import { vm } from '@/main'
, we gain access to necessary elements in Vuex
like vm.$root
required by certain components of bootstrap-vue
.
P.P.S. It's important to note that we can utilize vm
only when everything is fully loaded. In simpler terms, cannot use vm
inside someMutation
if called within mounted()
because mounted()
occurs prior to the creation of vm
.
FRESH PERSPECTIVE
Constantin's response (the accepted one) as explained here is more effective than mine, aimed at guiding beginners on its implementation.
Within the core directory (located in /src
for me), alongside files like App.vue
and main.js
, I have a file named router.js
structured as follows:
import Vue from 'vue'
import Router from 'vue-router'
// Traditional loading
import Home from '@/components/pages/Home/TheHome'
// Lazy loading (loaded when corresponding route is accessed)
const Page404 = () => import(/* webpackChunkName: "Page404" */ '@/components/pages/404)
const Page503 = () => import(/* webpackChunkName: "Page503" */ '@/components/pages/503)
Vue.use(Router)
const router = new Router({
mode: 'hash',
base: process.env.BASE_URL,
linkExactActiveClass: 'active',
routes: [
{
path: '*',
name: 'Page404',
component: Page404
},
{
path: '*',
name: 'Page503',
component: Page503
},
{
path: '/',
name: 'Home',
component: Home
},
// Additional routes
{....},
{....}
]
})
// Universal section allowing actions before entering a new route.
router.beforeEach(async (to, from, next) => {
next()
})
export default router
Include our router in main.js
:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
const vm = new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
export { vm }
Lastly, be it within a component, Vuex, or any other place, remember to import router from './router'
and proceed accordingly, such as invoking router.push(...)