Access VueRouter Beyond Vue Components

Is it possible to access VueRouter outside of Vue components.

I tried importing Vue into a JavaScript file. In this file I can access Vue.http , but not Vue.router or Vue.$router . The last 2 return undefined.

main.js

 import Vue from 'vue' import VueResource from 'vue-resource' import VueRouter from 'vue-router' import routes from './config/routes' import store from './store' import * as rootUrl from './config/rootUrl' //Routing support Vue.use(VueRouter); //Backend support Vue.use(VueResource); const router = new VueRouter({ mode: 'history', routes: routes }) new Vue({ store, router, }).$mount('#app') Vue.http.get(rootUrl.url, {Accept: "application/json"}).then(response => { let data = response.body store.commit('SET_APP_DATA', { data: { 'title': data.title, 'peopleUrl': data.people, 'eventsUrl': data.events }}) store.commit('SET_READY') }) 
+18
vuejs2 vue-router
source share
4 answers

I used it only from components, but you can try to follow if you use a common template where routes are defined in router / index.js, then you just import it like:

 import Router from '../router'; 

After you can use it in code, for example.

 Router.push('/mypage') 

Not sure if it works, but give it a try.

+14
source share

You have identified your router with this statement.

 const router = new VueRouter({ mode: 'history', routes: routes }) 

So, all you have to do to access it outside of Vue is used

 router.push(...) 

Or whatever you want to do.

If you want to use it in some other file, you may need to open it on window .

+2
source share

I solved this by exporting my router instead of my routes in routes.js (now router.js)

 export default new VueRouter({ mode: 'history', routes: routes }) 

Any file can access the router using

 import router from 'config/router' 
+2
source share

Add the router to the Vue constructor in the same file that you create and initialize your vue instance.

 Vue.$router = router 

Then use it as you first tried.

 Vue.$router.push(...) 

When using Typescript you can extend the VueContructor to include type checking and autocomplete.

mytypes.d.ts

 import {VueRouter} from "vue-router/types/router"; declare module 'vue/types/vue' { interface VueConstructor { $router: VueRouter } } 
0
source share

All Articles