Vue2路由案例实战
1、 基本使用
<!-- 1、路由标签 -->
<router-link to="/foo">foo</router-link>
<!-- 2、路由出口 -->
<router-view></router-view>
<!-- 3、配置路由 -->
const router = new VueRouter({
routes:[
{
path:'/foo',
component:Foo
}
]
})
<!-- 4、vue实例对象中书写路由 -->
let vm = new Vue({
el:"#app",
data:{
},
router
})
2、 高亮 “active” 与 精确匹配 “exact”
a、linkActiveClass:'active'
详细:router-link 切换时的类; 可以理解为:点谁谁自动变为这个类
b、<router-link tag="li" to="/" exact>
<a>首页</a>
</router-link>
详细:tag="li" 将 <router-link> 渲染为 li; exact 开启精确匹配(路径完全一致才能匹配)
3、 嵌套路由
a、配置路由规则,使用children配置项
routes: [
{
path: '/news',
component: news,
// 二级路由 配置 children
children: [
{
// 写法一:路径写全
path: '/news/ty',
component:Ty
},
{
// 写法二:简写 不写‘/’
path: 'kj',
component:Kj
},
]
}
]
b、跳转(要写完整路径):
<router-link tag='li' to='/news/ty'>
<a>体育</a>
</router-link>
4、 路由重定向 redirect
routes: [
{
// 重定向
redirect: '/news/ty',
path: '/news',
component: news
}
]
5、 路由缓存组件 keep-alive
作用: 让不展示的路由组件保持挂载,不被销毁。
<!-- 在切换路由时 会记录当前状态 -->
<keep-alive>
<router-view></router-view>
</keep-alive>
6、 路由传参 params
a、配置路由:声明接收params参数
routes: [
{
redirect: '/news/ty',
path: '/news',
component: news,
// 二级路由 配置 children
children: [
{
path: '/news/ty',
component: Ty,
children: [
{
path: '/news/ty/data/:id', // 使用占位符声明接收params参数
component: TyList,
// props 配置项
props:true
}
]
}
]
}
]
b、传递参数
<router-link :to='"/news/ty/data/"+item.id'>{{item.title}}</router-link>
c、接收参数:
$route.params.id
$route.params.title
7、 路由配置 的 props配置项
作用:让路由组件更方便的收到参数
a、配置
routes: [
{
redirect: '/news/ty',
path: '/news',
component: news,
children: [
{
path: '/news/ty',
component: Ty,
children: [
{
path: '/news/ty/data/:id',
component: TyList,
props:true // props 配置项
}
]
}
]
}
]
b、使用
id
title
8、 编程式路由导航
作用:不借助<router-link>
实现路由跳转,让路由跳转更加灵活
a、$router的两个API
this.$router.push('/news/kj/kjlist') // push 保存浏览器记录
this.$router.replace('/news/kj/kjlist') // replace 不会保存
b、动作
this.$router.forward() // 前进
this.$router.back() // 后退
this.$router.go() // 可前进可后退 根据的是里面的值 1-1