Gro*_*vyP 27 vue-router vuejs2
是否可以访问Vue组件外部的VueRouter.
我试过在JavaScript文件中导入Vue.在这个文件中我可以访问Vue.http,但不能Vue.router或Vue.$router.最后2个返回undefined.
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')
})
Run Code Online (Sandbox Code Playgroud)
Jan*_*nne 23
我只是从组件中使用它,但你可以尝试跟随以防万一你使用常见的样板文件路由在router/index.js下定义然后你只需导入它:
import Router from '../router';
Run Code Online (Sandbox Code Playgroud)
之后可以在代码中使用它,例如
Router.push('/mypage')
Run Code Online (Sandbox Code Playgroud)
不确定它是否有效但试一试.
我通过导出我的路由器而不是routes.js(现在的router.js)中的路由来解决这个问题
export default new VueRouter({
mode: 'history',
routes: routes
})
Run Code Online (Sandbox Code Playgroud)
然后任何文件都可以访问路由器
import router from 'config/router'
Run Code Online (Sandbox Code Playgroud)