我想在外部文件中定义我的路由以便于阅读。
我的main.js
文件是我启动Vue应用的地方。见下文:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
vue.use(VueRouter)
// I would like these route definitions to be contained in their own file
var Monday = Vue.extend({ template: '<div>Monday view<div>' })
var Tuesday = Vue.extend({ template: '<div>Tuesday view<div>' })
...
var router = new VueRouter()
router.map({
'/monday': { component: Monday },
'/tuesday': { component: Tuesday }
router.start(App, 'body)
我希望在应用程序扩展时将路由定义var Monday = Vue.extend({ ... })
等分成它们自己的文件以便于阅读。
问题:如果我要创建RouteDefinitions.js
文件,我无法访问“Vue”,我需要定义Vue.extend
。我应该从RouteDefinitions.js内import Vue from 'vue'
再次吗?这是一面红旗吗?或者我应该将所有路由逻辑保留在main.js中?
答案 0 :(得分:4)
你可以做到。在main.js
做类似的事情
import Vue from 'vue'
import router from './config/router'
Vue.router = router
new Vue({
router,
el: '#app',
render: h => h(App)
})
然后在router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter({
routes: [
/* your routes definition here */
]
})
router.beforeEach((route, redirect, next) => {
/* your route hooks */
next()
})
router.afterEach(function (transition) {
/* your route hooks */
})
export default router