文章目录
- 路有基础
- 概念
- 安装
- 使用
- 路由重定向
- 路由链接
- 路由占位符
- 编程式导航
- 实现方法
- 动态路由
- 静态路由
- 动态路由
- 嵌套路由
- 路由传递参数
- 使用router-link标签传递参数
- 使用事件方法传递路由参数
- 全局导航守卫
- 全局前置守卫
- 路由元信息
- 路由懒加载
- 新增路由
路有基础
概念
前端路由主要根据不同的事件,显示不同的页面内容,本质上是用户事件与事件处理函数之间的对应关系;
后台路由则是根据不同的URL请求,返回不同的服务器资源;
Vue专用的路由工具库VueRouter,叫做路由管理器。
- route
- 单数
- 路由
- 理解为单个路由或者某一个路由
- routes
- 复数
- 多个路由的集合
- 官方定义也是表示多个数组的集合
- router
- 路由器
- 包含route和routes的容器
- 管理者,负责从routes中查找route
- 功能:
- 嵌套的路由/视图表
- 模块化的、基于组件的路由配置
- 路由参数、查询、通配符
- 基于过度系统的视图过度效果
- 细粒度的导航控制
- 自定义的滚动条行为
安装
- 创建项目时候,选择上
- 通过命令进行安装
npm i vue-router@next
- 需要通过
()
方法将其纳入到实例中
使用
- 使用
createRouter
方法创建一个路由器router - 指定内容:
- 使用什么方法使用路由(两种方法:history模式和hash模式)
- history模式:
createWebHistory(.BASE_URL)
- hash模式:
createWebHashHistory()
- history模式:
- 路由数组
- 每一个对象都是一个路由对象
- 三部分
- name:链接名称
- path:当前路由规则匹配的hash地址
- component:当前路由规则对应要展示的组件
- 使用什么方法使用路由(两种方法:history模式和hash模式)
import {createRouter, createWebHashHistory} from 'vue-router'
import HelloWorld from '../views/'
const routes = [
// 指定默认路由
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/login',
name: 'login',
component: () => impport('../views/')
}
]
// 创建管理器
const router = createRouter({
// 指定history模式
history: createWebHistory(process.env.BASE_URL),
routers
})
export default router
路由重定向
使用的是路由管理规则的redirect属性来实现的。
import {createRouter, createWebHashHistory} from 'vue-router'
import HelloWorld from '../views/'
const routes = [
// 指定默认路由
{
path: '/',
redirect: '/hello'
},
{
path: '/hello',
name: 'HelloWorld',
component: HelloWorld
}
]
// 创建管理器
const router = createRouter({
// 指定history模式
history: createWebHistory(process.env.BASE_URL),
routers
})
export default router
路由链接
<router-link>
默认会被渲染为<a>
标签,to属性可以用来指定目标地址,会被渲染为href
属性
<router-link to="home">home</router-link>
<!-- 其他写法 -->
<router-link :to="home">home</router-link>
<router-link v-bind:to="home">home</router-link>
<router-link :to="{path: 'home'}">home</router-link>
<!-- 命名路由需要在router/中声明name对应的路由 -->
<router-link :to="{name: 'applename'}">to apple</router-link>
<!-- 带有参数的路由,如果是query,name和path都可以使用,并且会被解析为/apple?color=red -->
<router-link :to="{path: 'apple', query: {color: 'red'}}">apple</router-link>
<!-- 只有是name 的时候,params才会生效,且会被解析为/app/red -->
<router-link :to="{name: 'apple', params: {color: 'red'}}">apple</router-link>
添加一些激活样式可以通过actrive-class
属性来实现
路由占位符
用来将通过路由规则匹配到的组件渲染到组件占位符的位置上
<router-view></router-view>
编程式导航
导航有两种方式:
- 声明式导航
- 通过单击定义的链接实现导航的方式
- 编程式导航
- 通过调用js形式的API来实现导航的形式
- 基本方法
-
()
方法- 可以导航到不同的URL中
- 原理:向history中添加一个新的记录,当用户单击“后退”按钮,会回退到上一次访问的浏览器网页
- 单击
<router-link to=''>
方法等同于调用该方法
-
()
方法- 类似push方法,区别是不想浏览器的history中添加新的记录而是替换当前的history记录
-
()
方法- 参数是一个整数,代表前进或者后退多少步
- 如果history记录不够用,将导航失败
-
// 方法
router.push('home')
router.push({path: 'home'})
router.push({name: 'user', params: {userId: '123'}})
// /register?plan=private
router.push({path: 'home', query: {plan: 'private'}})
router.push({path: `/user/${userId}`})
//
// 前进
router.go(1);
// 后退
router.go(-1);
实现方法
// 1.引入useRouter方法
import {userRouter} from 'vue-router'
// 2.使用和操作,示例如下
const router = useRouter()
const homeClick = () => {
router.push('about');
}
动态路由
静态路由
单个页面实现多个路径信息,比如/user/lb
、/user/wq
等
实现思路:
<router-link to="/user/lb"></router-link>
<router-link to="/user/wq"></router-link>
<!-- 定义路由规则 -->
const routers = [
{path: '/user/lb', component: User},
{path: '/user/wq', component: User}
]
使用vue-router进行穿传递参数的路由称之为静态路由
动态路由
<!-- 动态路径参数 -->
const routers = [
{path: '/user/:userId', component: User}
]
<!-- 在路由组件中通过下面的语句获取参数 -->
嵌套路由
步骤:
- 1.创建对应的子组件,并在路由映射中配置对应的子路由
- 2.在父组件中通过使用
<router-view>
标签
import {createRouter, createWebHashHistory} from 'vue-router'
import Home from '../views/'
const HomeNews = () => import('../components/')
const HomeMsg = () => import('../components/')
const routes = [
{
path: '/home',
name: 'Home',
component: Home,
// 子路由
children: [
// 默认子路由
{
path: '',
component: HomeNews
},
{
path: 'news',
component: HomeNews
},
{
path: 'msg',
component: HomeMsg
},
]
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
路由传递参数
使用router-link标签传递参数
<!-- 使用标签传递参数,通过.参数名进行获取,route对象必须是通过useRoute()方法进行创建的 -->
<router-link :to="{path: '/profile', query: {name: '刘兵', age: 15}}"></router-link>
使用事件方法传递路由参数
使用事件来触发实现路由参数传递
const profileCheck = () => {
router.push({
path: '/profile',
query: {
name: 'zs',
age: 12
}
});
}
全局导航守卫
主要用来监听路由的进入和离开,然后通过vue-router提供的beforeEach和afterEach的生命周期函数分别在路由即将改变前和改变后触发。
全局前置守卫
()
注册一个全局的前置守卫
const router = new VueRouter({...})
router.beforeEach((to, from, next) => {})
一个导航触发时,全局前置守卫按照顺序进行调用。守卫是异步执行的,此时导航的所有守卫解析完成之前一直处于等待中。
参数介绍:
- to:目标路由对象
- from:正要离开的路由
- next:一定要调用该方法来解析这个生命周期函数
- next():执行下一个生命周期函数
- next(false):中断当前的导航。如果浏览器URL改变,那么重置到from路由对应的地址
- next(‘/’)或者next({path: ‘/’}):跳转到一个不同的地址。
()
使用方法同上。
路由元信息
定义路由的时候可以配置meta字段
const routes = [
// 指定默认路由
{
path: '/',
component: Hello,
// meta域
meta: {
// 属性:属性值
requiresAuth: true
}
}
]
一个路由匹配到的所有路由记录都会暴露为route对象的数组。可以通过语句.属性
实现检查路由记录中的meta字段。
路由懒加载
正常打包,webpack会将所有用到的组件全部打包到一个文件中,这样文件会很大,且解析的时候加载时间会变长,所以可以采用懒加载。
const 组件名 = () => import('组件名称');
也可以指定webpackChunkName,将多个组件合并打包成一个JavaScript文件
const Home = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/home')
const Index = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '@/components/index')
案例:
import {createRouter, createWebHashHistory} from 'vue-router'
import Home from '../views/'
import Profile from '../components/'
const HomeNews = () => import('../components/')
const HomeMsg = () => import('../components/')
const routes = [
{
path: '/',
redirect: '/home'
},
{
path: '/profile/',
component: Profile,
meta: {
title: '简介'
}
}
{
path: '/home',
name: 'Home',
component: Home,
meta: {
title: '主页'
}
// 子路由
children: [
// 默认子路由
{
path: '',
component: HomeNews
},
{
path: 'news',
component: HomeNews
},
{
path: 'msg',
component: HomeMsg
},
]
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
router.beforeEach((to, from, next) => {
if(to.matched[0].name ==== 'User'){
console.log('拦截')
}else{
//读取路由元信息,并修改网页标题
document.title = to.meta.title
// 跳转到指定页面
next()
}
});
export default router
新增路由
使用方法:
- 增加单挑路由
({})
- 增加指定父路由的子路由
('父路由名', {})
import {createRouter, createWebHashHistory} from 'vue-router'
const router = createRouter({
history: createWebHashHistory(),
routes
})
router.addRoute({
path: 'msg',
name: 'Msg',
component: () => import('../components/')
})
router.addRoute('Msg', {
path: '/msg/info',
component: () => import('../components/')
})