路由创建
npm install vue-router@4
引入
import VueRouter from 'vue-router'
创建路由对象
const router = new VueRouter()
注入vue实例中
new Vue({render:h=>h(App),router
})
路由出口router-view
<router-view></router-view>
router-link
- 必须配置to属性,本质上是
a
标签 - 能高亮,默认就会提供高亮类名,可以直接设置高亮样式
router-link-active–模糊匹配
to=‘/my’ 可以匹配 /my /my/a /my/b
router-link-exact-active–精确匹配
to='.my’仅可以匹配/myconst router = new VueRouter({routes:[],linkActiveClass:'active-link'linkExactActiveClass: 'exact-active' });
修改高亮yanse
#header a.router-link-exact-active{color:rgb(139, 12, 18) }//注意这里的a标签,就是router-link
路由跳转传参-接收参数
查询参数传参
- 语法
to='/path?参数名=值
- 对应页面组件接受传过来的值
$route.query.参数名
<p>搜索关键字: {{ $route.query.key }} </p> created () { // 在created中,获取路由参数 // this.$route.query.参数名 获取 console.log(this.$route.query.key); }
动态路由传参
- 配置动态路由–
必须传参,如果不传参就不显示
------但可以添加 ? 可选符----这样无论是否传参,都可以显示
- 配置动态路由
const router = new VueRouter({routes: [{ path: '/home', component: Home },// 必须传参数,如果不传参数,亦希望匹配,可以加 个可选符?{ path: '/search/:words?', component: Search }// { path: '/search', component: Search }] })
- 配置导航链接
to="/path/参数值"
- 对应页面组件接受传递过来的值
$route.params.参数名
- 配置动态路由–
路由重定向
使得一个路由地址A与另一个路由地址B联系起来,执行A的时候会跳转执行B。
var router = new VueRouter({routes:[// {path:'/', redirect:'跳转到的路由地址'}{path:'/', redirect:'/home'},{path:'/home', component:Home}]
})
执行/根目录路由地址时,就跳转执行/home路由地址 ,进而把对应的组件给显示出来。
编程时导航–路由跳转
两种语法
- path路径跳转-------适合短路径
- name命名路由跳转------适合长路径
- router大的路由实例对象----
$route
里的$
是一个约定俗成的前缀,用于标识它是 Vue 实例的属性或方法 path路径跳转
this.$router.push('路由路径’)
this.$router.oush({path:'路由路径'
})
name命名路由跳转
this.$router.push({name:路由名‘
})
{name: '路由名’,path: '/path/xxx' , component:xxx}
编程式导航–路由传参
path路径–查询参数传参
this.$router.push('/路径?参数名1=参数值1&参数名2=参数值2')
this.$router.push({path:'/路径',query:{参数名1:‘参数值1’,参数名2:‘参数值2’}
})
接收: $route.query.参数名
path路径-动态路由传参
this.$router.push('/路径/参数值1&参数值2')
this.$router.push({path:'/路径/参数值'
})
接收: $route.params.参数名
name命名–query传参
this.$router.push({name:'路由名字',query: {参数名1:’参数值1‘}
})
接收: $route.query.参数名
name命名–动态路由传参
this.$router.push({name:'路由名字',params: {参数名1:’参数值1‘}
})
接收: $route.params.参数名
组件缓存 keep-alive
可以详细查看该文档
https://blog.csdn.net/wanghaoyingand/article/details/119847949
- include :组件名数组,只有匹配的组件才会缓存
- exclude:组件名数组,任何匹配的组件都不会被缓存
- max:最多可以缓存多少组件实例