1.全局注册vue-router
在mian.js中注册
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
new Vue({
render: h => h(App),
}).$mount('#app')
2.实例化一个vue-router
import VueRouter from 'vue-router'
import MainView from '../components/MainView'
import Exception404 from '../error/404'
const defaultRouters = [
{path: '/', redirect: '/index'},
{path: '*', redirect: '/404', hidden: true},
{path: '/index', component: MainView},
{path: '/404', component: Exception404}
]
export const routerConfig =new VueRouter({
mode: 'history',
routes: defaultRouters
})
2.1 vue-router构建选项详解
import VueRouter from 'vue-router'
import MainView from '../components/MainView'
import Exception404 from '../error/404'
const defaultRouters = [
{path: '/', redirect: '/index'},
{path: '*', redirect: '/404', hidden: true},
{path: '/index', component: MainView},
{path: '/404', component: Exception404}
]
const defaultVueRouterConfiguration = {
mode: 'history',
routes: defaultRouters,
base:'/'
}
export const routerConfig =new VueRouter(defaultVueRouterConfiguration)
2.1.1 路由组件配置项
interface RouteConfig = {
path: string,
component?: Component,
name?: string, // 命名路由
components?: { [name: string]: Component }, // 命名视图组件
redirect?: string | Location | Function,
props?: boolean | Object | Function,
alias?: string | Array<string>,
children?: Array<RouteConfig>, // 嵌套路由
beforeEnter?: (to: Route, from: Route, next: Function) => void,
meta?: any,
// 2.6.0+
caseSensitive?: boolean, // 匹配规则是否大小写敏感?(默认值:false)
pathToRegexpOptions?: Object // 编译正则的选项
}
3.挂载vue-router至app根节点
main.js中
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import {routerConfig} from './router/routerconfig.js'
Vue.config.productionTip = false
Vue.use(VueRouter)
new Vue({
router:routerConfig,
render: h => h(App),
}).$mount('#app')