Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access VueRouter outside Vue components

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') }) 
like image 554
GroovyP Avatar asked Apr 22 '17 10:04

GroovyP


People also ask

How do I access my Vue router in component?

To have the Vue-Router routes be rendered you will need to pass the <router-view> tag inside a Vue component. You could also access the routes from an <a> tag, but this will trigger a page re-render, to avoid this behavior you could use router-link with the to property instead of a href .

How do I push my Vue router?

With Vue Router, you can use its router. push() function to programmatically navigate between routes on your site. You can either call push() with a string path, or with an object containing either the path or name of the route.

Can we define multiple router outlets in a component Vue?

Instead of having one single outlet in your view, you can have multiple and give each of them a name. A router-view without a name will be given default as its name.


1 Answers

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.

like image 144
Janne Avatar answered Oct 04 '22 05:10

Janne