文章目录
vue-router
6.1 路由的简介
6.1.1 vue-router 的理解
vue 的一个插件库,专门用来实现 SPA 应用
插件库就要:1.npm i vue-router
2. Vue.use()
- 区分路由器和路由:(生活中的)
- 编程中的路由:为了实现SPA应用(单页面应用)
6.1.2 对 SPA 应用的理解
- 单页 Web 应用(single page web application,SPA)。
- 整个应用只有一个完整的页面。(index.html)
- 点击页面中的导航链接不会刷新页面,只会做页面的局部更新。
- 数据需要通过 ajax 请求获取。
之前写过多页面时,存在页面的各种跳转,现在要是写成单页面?
多页面不好:开了一个页签,要到别的页签,点击跳转,就会各种条,交互中各种抖动,麻烦
那么用单页面? — 实现切换
左边时导航区,右边展示区,根据左边内容进行不同内容的呈现。页面只是局部更新,不会跳转到别的区域
例如美团的页面:
所以:
单页面也可以丰富多彩,用户体验感更好
6.1.3 路由的理解
-
什么是路由?
- 一个路由就是一组映射关系(key - value)
- key 为路径, value 可能是 function 或 component
-
路由分类
-
后端路由:(服务器)
- 理解:value 是 function, 用于处理客户端提交的请求。
- 工作过程:服务器接收到一个请求时, 根据请求路径找到匹配的函数
来处理请求, 返回响应数据。
-
前端路由:
- 理解:value 是 component,用于展示页面内容。
- 工作过程:当浏览器的路径改变时, 对应的组件就会显示。
-
前端路由工作流程(你是什么路径,我就展示什么组件)
后端路由工作流程(你是什么路径,我就调用指定函数去响应你的请求)
(可以参考之前nodejs写的服务器)
神奇的路由理解:路由,路径由我(路由器)决定区展示那个组件
要实现上面的导航区和展示区的切换前提是:展示区不同的内容要变成不同的组件
6.2 路由基本使用
6.2.1 基本应用
-
安装vue-router,命令:
npm i vue-router
-
应用插件:
Vue.use(VueRouter)
-
编写router配置项:
//引入VueRouter import VueRouter from 'vue-router' //引入Luyou 组件 import About from '../components/About' import Home from '../components/Home' //创建router实例对象,去管理一组一组的路由规则 const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //暴露router export default router
-
实现切换(active-class可配置高亮样式)
<router-link active-class="active" to="/about">About</router-link>
-
指定展示位置
<router-view></router-view>
6.2.2 导航切换案例分析
案例分析:
- 引入 import 使用 use (在src/main.js)
- 创建一个router文件夹,里面建一个index.js 专门写路由
- App.vue引入路由器
- 路由器已经就位,我们需要去找到导航,实现导航区点击之后切换路径 使用标签
router-link
- 选择哪个背景高亮 使用active-class
- 现在页面已经知道药去 Home 或 About,我们要去告诉他在哪 使用
router-view
没有交互的效果
样式使用的bootstrap
代码
router/index.js
// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router"
// 引入组件
import About from '../components/About'
import Home from '../components/Home'
// 创建并且暴露一个路由器
export default new VueRouter({
routes:[
{
path: '/about',
component: About
},
{
path: '/home',
component: Home
}
]
})
App.vue
<template>
<div>
<div class="row">
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header"><h2>Vue Router Demo</h2></div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!-- 原始html中我们使用a标签实现页面的跳转 -->
<!-- <a class="list-group-item" href="./about.html">About</a>
<a class="list-group-item active" href="./home.html">Home</a> -->
<!--vue中借助router-link标签实现路由的切换 -->
<router-link class="list-group-item" active-class="active" to="/about">About</router-link>
<router-link class="list-group-item" active-class="active" to="/home">Home</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!-- 此处到底展示什么组件,得看用户点击的是哪个导航项 -->
<!-- 指定组件的呈现位置 -->
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "App",
};
</script>
About.vue
<template>
<h2>我是About的内容</h2>
</template>
<script>
export default {
name: 'About'
}
</script>
Home.vue
<template>
<h2>我是Home的内容</h2>
</template>
<script>
export default {
name: 'Home'
}
</script>
效果显示
几个注意点
- 路由组件通常存放在
pages
文件夹,一般组件通常存放在components
文件夹。 - 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
- 每个组件都有自己的
$route
属性,里面存储着自己的路由信息。 - 整个应用只有一个router,可以通过组件的
$router
属性获取到。
总结: 编写使用路由的3步
- 定义路由组件
- 注册路由
- 使用路由
6.3 嵌套(多级)路由
案例静态效果:
代码:(在之前的代码基础上修改添加)
Home.vue
<template>
<div>
<h2>Home组件内容</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
</li>
<li>
<router-link class="list-group-item" active-class="active" to="/home/message">Message</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
name:'Home',
/* beforeDestroy() {
console.log('Home组件即将被销毁了')
}, */
/* mounted() {
console.log('Home组件挂载完毕了',this)
window.homeRoute = this.$route
window.homeRouter = this.$router
}, */
}
</script>
News.vue
<template>
<ul>
<li>news001</li>
<li>news002</li>
<li>news003</li>
</ul>
</template>
<script>
export default {
name:'News'
}
</script>
Message.vue
<template>
<div>
<ul>
<li>
<a href="/message1">message001</a>
</li>
<li>
<a href="/message2">message002</a>
</li>
<li>
<a href="/message/3">message003</a>
</li>
</ul>
</div>
</template>
<script>
export default {
name:'Message'
}
</script>
效果显示
6.4 路由传参
6.4.1 路由的query参数
-
传递参数
<!-- 跳转并携带query参数,to的字符串写法 --> <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link> <!-- 跳转并携带query参数,to的对象写法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'你好' } }" >跳转</router-link>
-
接收参数:
$route.query.id $route.query.title
6.4.2 三级路由案例分析
在上面案例中,再套一次娃,三级路由
注意:之前的办法是创建多个vue,比如Detrail1.vue,Detrail2.vue…。但是现在我们不使用之前的办法,麻烦,不好用,我们现在值创建一个Detail.vue文件
静态效果:
部分代码:
Message.vue
<template>
<div>
<ul>
<li v-for="m in messageList" :key="m.id">
<!-- 跳转路由并携带query参数,to的字符串写法 -->
<!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link> -->
<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
path:'/home/message/detail',
query:{
id:m.id,
title:m.title
}
}">
{{m.title}}
</router-link>
</li>
</ul>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:'Message',
data() {
return {
messageList:[
{id:'001',title:'消息001'},
{id:'002',title:'消息002'},
{id:'003',title:'消息003'}
]
}
},
}
</script>
Detail.vue
<template>
<ul>
<li>消息编号:{{$route.query.id}}</li>
<li>消息标题:{{$route.query.title}}</li>
</ul>
</template>
<script>
export default {
name:'Detail',
mounted() {
console.log(this.$route)
},
}
</script>
6.5 命名路由
6.5.1 命名路由的作用
作用:可以简化路由的跳转。
6.5.2 命名路由如何使用
-
给路由命名:
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //给路由命名 path:'welcome', component:Hello, } ] } ] }
-
简化跳转:
<!--简化前,需要写完整的路径 --> <router-link to="/demo/test/welcome">跳转</router-link> <!--简化后,直接通过名字跳转 --> <router-link :to="{name:'hello'}">跳转</router-link> <!--简化写法配合传递参数 --> <router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }" >跳转</router-link>
6.6 路由的params参数
-
配置路由,声明接收params参数
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }
-
传递参数
<!-- 跳转并携带params参数,to的字符串写法 --> <router-link :to="/home/message/detail/666/你好">跳转</router-link> <!-- 跳转并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
-
接收参数:
$route.params.id $route.params.title
6.7 路由的props配置
作用:让路由组件更方便的收到参数
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
// props:{a:900}
//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
// props:true
//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
props(route){
return {
id:route.query.id,
title:route.query.title
}
}
}
代码分析:
第一种写法(用的少)
第二种写法
第三种写法(最强大)
6.8 <router-link>
的replace属性
- 作用:控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入方式:分别为
push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push
- 如何开启
replace
模式:<router-link replace .......>News</router-link>
举例:
浏览器是怎么保存这个历史记录的呢?
默认的router-link
是push模式
如果是replace模式:(替换当前的记录)
6.9 编程式路由导航
引入
不写router-link能实现跳转吗?
这个router-link最终会转成 a, 但是我们并不是总是用 a, 有时用button img 等等
编程式路由导航
-
作用:不借助
<router-link>
实现路由跳转,让路由跳转更加灵活 -
具体编码:
//$router的两个API this.$router.push({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.replace({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.forward() //前进 this.$router.back() //后退 this.$router.go() //可前进也可后退
相关 API
控制前进后退 灵活的控制往哪个路由跳转 并且可以携带参数
- this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
- this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
- this.$router.back(): 请求(返回)上一个记录路由
- this.$router.go(-1): 请求(返回)上一个记录路由
- this.$router.go(1): 请求下一个记录路由
6.10 缓存路由组件
-
作用:让不展示的路由组件保持挂载,不被销毁。
-
具体编码:
<keep-alive include="News"> // 组件名:News <router-view></router-view> </keep-alive>
6.11 两个新的生命周期钩子
- 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
- 具体名字:
activated
路由组件被激活时触发。deactivated
路由组件失活时触发。
6.12 路由守卫
-
作用:对路由进行权限控制(保护路由的安全)
-
分类:全局守卫、独享守卫、组件内守卫
-
全局守卫:
//全局前置守卫:初始化时执行、每次路由切换前执行 router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则 next() //放行 }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() //放行 } }) //全局后置守卫:初始化时执行、每次路由切换后执行 router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改网页的title }else{ document.title = 'vue_test' } })
-
独享守卫:
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ next() }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() } }
-
组件内守卫:
//进入守卫:通过路由规则,进入该组件时被调用 beforeRouteEnter (to, from, next) { }, //离开守卫:通过路由规则,离开该组件时被调用 beforeRouteLeave (to, from, next) { }
6.13 路由器的两种工作模式
- 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
- hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
- 开始浏览器默认是hash,通过
mode: 'history'
转成history模式 - hash模式:
- 地址中永远带着#号,不美观 。
- 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
- 兼容性较好。
- history模式:
- 地址干净,美观 。
- 兼容性和hash模式相比略差。
- 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。
6.14 项目上线
6.14.1 项目基本上线流程
把写的东西打包,最终给后端的文件都要转成html,css,js文件
-
终端使用命令
npm run build
-
会生成一个dist(dist: 打包)文件
-
打包出来的文件必须放在服务器上进行部署
-
没有服务器,可以自己写一个用nodejs + express框架 搭建一个微型服务器
-
新建一个文件夹demo,安装这个包
npm init
-
取名:atguigu_test_server(随便)
-
一路回车
-
安装express:
npm i express
-
创建一个server.js文件开始写
server.js
const express = require('express') const app = express() app.use(express.static(__dirname+'/static')) app.get('person',(req,res)=>{ res.send({ name:'tom', age: 18 }) }) app.listen(5005,(err)=>{ if(!err) console.log('服务器启动成功啦!'); })
-
终端启动服务
node server
,这时服务器差不多准备好了 -
新建一个文件夹static,把刚刚脚手架打包的dist里面的文件放进去
-
重新启动一下服务器,部署好了
-
6.14.2 404问题
中途会出现问题:
上面的问题我们用hash就可以解决404问题,不用history
如果非要使用history呢?(毕竟不适用#更美观)
需要后端工程师配合
推荐一个nodejs里面的中间件去解决这个history里面404问题
connect-history-api-fallback
此时再次启动服务器,打开浏览器,刷新也不会有404了