vue生态技术Router
# Vue-Router
单页面应用(SPA): 所有功能在一个html页面上实现 (Single Page Application)
yarn add vue-routerimport VueRouter from 'vue-roter'--main.jsVue.use(VueRoter)-- main.jsconst routes = [ { path:'/home', component:Home }, { path:'/my', component:My } ]1
2
3
4
5
6
7
8
9
10const router = new VueRouter({routes})--main.js挂载 Vue 实例 :
new Vue({router,render:h=>h(App)}).$mount('#app')App.vue 替换
<template> <router-view></router-view> </template>1
2
3
# 声明式导航
router-link提供了声明式导航高亮的功能(自带类名)
<router-link to="/find">发现音乐</router-link>
路由传参
{ path: "/part/:username", // 有:的路径代表要接收具体的值 component: Part }
<template>
<div>
<p>关注明星</p>
<p>发现精彩</p>
<p>寻找伙伴</p>
<p>加入我们</p>
<p>人名: {{ $route.query.name }} -- {{ $route.params.username }}</p>
</div>
</template>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
<router-link to="/part?name=小传&age=18">朋友-小传</router-link>
<router-link to="/part/小智">朋友-小智</router-link>
1
2
2
?key=value 用$route.query.key 取值
/值 提前在路由规则/path/:key 用$route.params.key 取值
路由嵌套
const routes = [
// ...省略其他
{
path: "/find",
name: "Find",
component: Find,
children: [
{
path: "recommend",
component: Recommend
},
{
path: "ranking",
component: Ranking
},
{
path: "songlist",
component: SongList
}
]
}
// ...省略其他
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
路由匹配
router-link自带的2个类名
- router-link-exact-active (精确匹配) url中hash值路径, 与href属性值完全相同, 设置此类名
- router-link-active (模糊匹配) url中hash值, 包含href属性值这个路径
# 路由重定向和模式
//main.js中增加
{
path: "/", // 默认hash值路径
redirect: "/find" // 重定向到/find
// 浏览器url中#后的路径被改变成/find-重新匹配数组规则
}
1
2
3
4
5
6
2
3
4
5
6
设置重定向
404
import NotFound from '@/views/NotFound'
const routes = [
// ...省略了其他配置
// 404在最后(规则是从前往后逐个比较path)
{
path: "*",
component: NotFound
}
]
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
模式
- hash
- history
# 编程式导航
JS 跳转
this.$router.push({
path: "路由路径", // 都去 router/index.js定义
name: "路由名"
})
1
2
3
4
2
3
4
传参
oneBtn(){
this.$router.push({
name: 'Part',// /part/小传
params: {
username: '小传'
}
})
},
twoBtn(){
this.$router.push({
name: 'Part', // /part?name=小智
query: {
name: '小智'
}
})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 路由守卫
路由跳转之前, 先执行一次前置守卫函数, 判断是否可以正常跳转
router.beforeEach(to,from,next)=>{}
// 目标: 路由守卫
// 场景: 当你要对路由权限判断时
// 语法: router.beforeEach((to, from, next)=>{//路由跳转"之前"先执行这里, 决定是否跳转})
// 参数1: 要跳转到的路由 (路由对象信息) 目标
// 参数2: 从哪里跳转的路由 (路由对象信息) 来源
// 参数3: 函数体 - next()才会让路由正常的跳转切换, next(false)在原地停留, next("强制修改到另一个路由路径上")
// 注意: 如果不调用next, 页面留在原地
// 例子: 判断用户是否登录, 是否决定去"我的音乐"/my
const isLogin = true; // 登录状态(未登录)
router.beforeEach((to, from, next) => {
if (to.path === "/my" && isLogin === false) {
alert("请登录")
next(false) // 阻止路由跳转
} else {
next() // 正常放行
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)
上次更新: 2023/02/07, 15:11:55