vue-router 使用

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')

4.项目结构

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值