路由模块封装p76
将路由模块抽离出来
拆分模块,利于维护放到router文件夹
要导入vue和导出router
@是src,绝对路径
声明式导航p77-79
导航链接
router-link取代了a herf,配置to属性指定路径(不用加#号)本质还是a标签
但和a标签的区别是能高亮,默认就会提供高亮类名,可以直接设置高亮样式
<style>
.app a.router-link-active{
background-color: antiquewhite;
}
</style>
两个类名
- router-link-active模糊定位(用的多)
- router-link-exact-active精确匹配
类名定制
const router = new VueRouter({
//routes路由规则们
routes:[{
path:'/sb',component:Sb
}],
linkActiveClass:'类名一',
linkExactActiveClass:'类名二'
})
<style>
.app a.router-link-active{
background-color: antiquewhite;
}
</style>
<style>
.app a.类名一{
background-color: antiquewhite;
}
</style>
跳转传参
1. 查询参数传参(适合传多个参数)
(1)传
<router-link to="/path?参数名=值"></router-link>
(2)获取对应页面组件接收传递过来的值
<p>关键字:{{ $route.query.参数名 }}</p>(获取查询参数)
2. 动态路由传参(优雅简洁,传单个参数方便)
(1)配置动态路由
const router = new VueRouter({
//routes路由规则们
routes:[{
path:'/sb/:参数名?',
component:Sb
}],
linkActiveClass:'类名一',
linkExactActiveClass:'类名二'
})
(2)配置导航链接
to=“/path/参数值”
(3)对应页面组件接收传递过来的值
$route.params.参数名(获取动态路由参数)
动态路由参数可选符
正则表达式,?是零个或一个
vue路由
重定向p80
网页打开,url默认是/路径,未匹配到组件时,会出现空白
重定向-匹配path后,强制跳转path路径到redirect的路径
语法:{path:匹配路径,redirect:重定向到的路径},
404
作用:当路径找不到匹配时,给个提示页面
位置:配在路由最后
语法:path:‘*’(任意路径)-前面不匹配就命中最后这个
模式设置
- hash路由(默认) 例如:http://localhost:8080/#/home
- history路由(默认) 例如:http://localhost:8080/home(以后上线需要服务端支持),一旦采用history模式,地址栏就没有#,需要后台配置
const router =new VueRouter({
routes,
mode:“history”
})
编程式导航p81
基本跳转
点击按钮跳转
编程式导航:用js代码进行跳转
语法:
(1)path路径跳转(简易方便)
//简写
方法(){
this.$router.push('路由路径')
}
//完整写法
方法(){
this.$router.push({
path:'/search'
})
}
(2)name命名路由跳转(适合path路径长的场景)
方法(){
this.$router.push({
name:'路由名'
})
}
routes:[{name:'search' path:'/sb/:参数名?',component:Sb
}],
路由传参
查询参数,动态路由传参(两种name和path传参方式都支持)
(1)通过路径跳转传参(query)
简洁写法,写的少
this.$router.push('/路径?参数名1=参数值1&参数名2=参数值2 ')
完整写法,写的多
this.$router.push({
path:'/路径'
query:{
参数名1:‘参数值1’
参数名2:‘参数值2’
}
})
使用
{{ $route.query.key }}
path路径跳转传参(动态路由传参)
this.$router.push('/路径/参数值 ')
this.$router.push({
path: '/路径/参数值 '
})
使用
{{ $route.params.路径 }}
- name和paraps传参
缓存组件p87
原因:路由跳转后,组件被销毁了,返回回来组件又被重建了,所以数据重新被加载了
3. keep-alive的三个属性
(1)include:组件名数组,只有匹配的组件会被缓存
(2)exclude:组件名数组,任何匹配的组件都不会被缓存
(3)max:最多可以缓存多少组件实例
组件名(如果没有配置name,才会找文件名作为组件)
组件缓存了,就不会执行组件的created,mounted,destroyed等钩子
所以提供了两个钩子
actived组件激活看到页面,进入页面触发
deactived组件失活看不见页面,离开页面触发
自定义创建项目p88
ESlint代码规范p89
赋值符号的左右一般要空格