45

Is it possible to access the VueRouter outside of Vue components.

I've tried importing Vue in 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')
})
Community
  • 1
  • 1
GroovyP
  • 798
  • 1
  • 6
  • 15

4 Answers4

46

I've used it only from components but you could try following in case you're using common boilerplate where routes are defined under router/index.js then you just import it like:

import Router from '../router'; 

After it is possible to use it in code e.g.

Router.push('/mypage')

Not sure if it works but give it a try.

Janne
  • 1,665
  • 15
  • 22
6

I resolved 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 then access the router with

import router from 'config/router'
GroovyP
  • 798
  • 1
  • 6
  • 15
3

You've defined your router with this statement

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

So all you need to do to access it outside Vue is use

router.push(...)

Or whatever else you want to do.

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

Bert
  • 80,741
  • 17
  • 199
  • 164
3

Add the router to your 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(...)

If using Typescript, you can augment the VueContructor to enable type checking and autocompletion.

mytypes.d.ts

import {VueRouter} from "vue-router/types/router";
declare module 'vue/types/vue' {
  interface VueConstructor {
    $router: VueRouter
  }
}
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78