- VueRouter:构造函数,通过它实例化路由模块对象
- routes:添加路由配置
- router:注入路由
- router-view:路由所映射组件的展示区域
- router-link:路由超链接
- $route:获取路由参数,它是一个对象
- $router:实现路由跳转,以代码的方式来实现
一、npm安装
npm install vue-router
二、在src中创建router文件夹,文件名为index.js
//当前项目的路由模块
//如果在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装路由功能
import Vue from 'vue'
//安装好后就会有vue-router
import VueRouter from 'vue-router'
//在当前项目中安装路由
Vue.use(VueRouter)
// 1.创建路由对象
const router = new VueRouter({
// 2.添加路由配置,通过routes来添加路由配置
routes: [
//3.添加具体的路由配置:配置的本质就是将路由映射到组件
//一般来说,我们可以设置为如下几个选项:name path component redirect children
// name:路由名称
//path:路由路径
//component:路由所映射的组件对象
{
name: 'index',
path: '/index',
// 异步引入组件,确保匹配了路由才加载组件,否则不利于优化
component: () => import('@/views/index.vue')
}
]
})
// 4.暴露
export default router
三、在main.js中注入路由
//引入路由模块
import router from '@/router/index.js'
new Vue({
router,
render: h => h(App),
}).$mount('#app')
四、在根组件APP.vue全局映射
<template>
<div id="app">
<router-view />
</div>
</template>
五、路由嵌套
1.路径path、名称name、调用组件component、默认展示组件redirect。路由对象数组routes中存放着所有路由的路径和组件,二级路由以children数组的形式挂在一级路由对象里面,三级路由也挂在二级路由对象中的children数组里面。
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import Home from './components/Home'
import Menu from './components/Menu'
import Admin from './components/Admin'
import About from './components/about/About'
import Login from './components/Login'
import Register from './components/Register'
// 二级路由
import Contact from './components/about/Contact'
import Delivery from './components/about/Delivery'
import History from './components/about/History'
import OrderingGuide from './components/about/OrderingGuide'
//三级路由
import Phone from './components/about/contact/Phone'
import PersonName from './components/about/contact/PersonName'
Vue.use(VueRouter)
const routes = [{
path: '/',
name: "homeLink",
component: Home
}, {
path: '/menu',
name: "menuLink",
component: Menu
}, {
path: '/admin',
name: "adminLink",
component: Admin
}, {
path: '/about',
name: "aboutLink",
component: About,
redirect: '/about/contact',
children: [{
path: '/about/contact',
name: "contactLink",
redirect: '/about/contact/personname',
component: Contact,
children: [{
path: '/about/contact/phone',
name: 'phoneNumber',
component: Phone
}, {
path: '/about/contact/personname',
name: 'personName',
component: PersonName
}, ]
}, {
path: '/about/delivery',
name: "deliveryLink",
component: Delivery
}, {
path: '/about/history',
name: "historyLink",
component: History
}, {
path: '/about/orderingGuide',
name: "orderingGuideLink",
component: OrderingGuide
}, ]
}, {
path: '/login',
name: "loginLink",
component: Login
}, {
path: '/register',
name: "registerLink",
component: Register
}, {
path: '*',
redirect: '/'
}, ];
const router = new VueRouter({
routes,
mode: "history"
})
new Vue({
router,
el: '#app',
render: h => h(App)
})