6.路由
0.简介
vue-router的理解
vue的一个组件库,专门用来实现spa应用
对spa应用的理解:
单页面web应用
整个应用只有一个完整的页面
点击页面中导航链接不会刷新页面,只会做页面的局部更新
数据需要通过ajax获取请求
什么是路由:
1.一个路由就是一组映射关系(key-value)
2.key为路径,value 可能是function或component
路由分类:
前端路由:
1.value是component,用于展示页面内容
2.工作过程:服务器接受到一个请求时,更具请求路径找到匹配的函数来处理请求,处理响应数据
后端路由:
1.理解:value是function,用于处理客户端提交的请求
2.工作过程:当浏览器的路径改变时,对应的组件就会显示
1.路由的基本使用
安装 npm i vue-router@3
应用插件:Vue.use(VueRouter)
编写router配置项:
import VueRouter from "vue-router"; import Home from '../components/Home' import About from '../components/About' export default new VueRouter({ routes:[ { path:'/about', component:About },{ path:"/home", component:Home }, ] })<template> <div id="app"> <!-- <HelloWorld msg="Welcome to Your Vue.js App"/> --> //实现切换(active-class可以配置高亮) <router-link active-class="active" to="/About">About</router-link> <router-link active-class="active" to="/Home">Home</router-link> <div> //展示内容位置 <router-view></router-view> </div> </div> </template>
2.几个注意点
-
路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹
-
通常切换"隐藏"了路由租金啊,默认是被销毁的,需要的时候再去挂载
-
每个组件都有自己的$route属性,里面存储着自己的路由信息
-
整个应用只有一个router,可以通过组件的$router属性获取到
3.多级路由(嵌套路由)
1.配置路由规则,使用childern配置项
import VueRouter from "vue-router"; import Home from '../pages/Home' import About from '../pages/About' import Message from '../pages/Message' import News from '../pages/News' export default new VueRouter({ routes:[ { path:'/about', component:About },{ path:"/home", component:Home, children:[ { path:'message', //此处一定不要写/message component:Message, }, { path:'news', component:News }, ] }, ] })
2.跳转(要写完全路径)
<template> <div> <h2> Home组件内容 </h2> <div> <ul> <li> <router-link to="/home/news">News</router-link> </li> <li> <router-link to="/home/message">Message</router-link> </li> </ul> <router-view></router-view> </div> </div> </template>
4.路由的参数
传递参数:
<!-- 跳转路由并携带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>
2.接受参数:
<li> 消息ID:{{ $route.query.id}} </li> <li> 消息名称:{{ $route.query.title }} </li>
5.命名路由
1.作用:可以简化路由的跳转
2.如何使用
1.给路由命名:
routes:[ { name:'guanyu', //配置的路由名称 path:'/about', component:About },{ path:"/home", component:Home, children:[ { path:'message', //此处一定不要写/message component:Message, children:[{ name:'xiangqing', //配置的路由名称 path:'detail', component:Detail }] }, { path:'news', component:News }, ] }, ]
2.简化跳转:
//简化前:需要写完整的路径 <router-link :to="{path:'/home/message/detail', }">{{ m.title }}</router-link> //简化后:直接通过名字跳转 <router-link :to="{name:'xiangqing', }">{{ m.title }}</router-link> //简化写法配合传递参数 <router-link :to="{ //path:'/home/message/detail', name:'xiangqing', query:{ id:m.id, title:m.title } }">{{ m.title }}</router-link>
6.路由的params参数
1.配置路由,生命接受params参数
routes:[ { name:'guanyu', path:'/about', component:About },{ path:"/home", component:Home, children:[ { path:'message', //此处一定不要写/message component:Message, children:[{ name:'xiangqing', // path:'detail', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail }] }, { path:'news', component:News }, ] }, ]
2.传递参数
<!-- 跳转路由并携带params参数,to的字符串写法 --> <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{ m.title }} </router-link> <!-- 跳转路由并携带params参数,to的对象写法 --> <router-link :to="{ //path:'/home/message/detail', name:'xiangqing', params:{ id:m.id, title:m.title }, }">{{ m.title }} </router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置
3.接收参数:
$route.$params.id $route.$params.title
7.路由的props配置
作用:让路由组件更方便的接收参数
children:[{ name:'xiangqing', // path:'detail', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail, // 第一种写法:props为对象,该对象中的所有key-value都会通过props传给detial // props:{ // a:900, // b:'hello' // }, // 第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传递给detail组件 props:true, // 第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给detail // props(route){ // return{ // id:route.params.id, // title:route.params.title // } // } }]
8.<router-link>的replace属性
1.作用:控制路由跳转时操作浏览器历史记录的模式
2.浏览器历史记录有两种写入方式:分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认开启push
3.如何开启replace模式:<router-link replace....>news</router-link>
9.编程式路由导航
1.作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活
2.具体编码:
methods:{ //router的两个api pushHandle(m){ this.$router.push({ name:'xiangqing', params:{ id:m.id, title:m.title } }) }, replaceHandle(m){ this.$router.replace({ name:'xiangqing', params:{ id:m.id, title:m.title } }) }, }, methods:{ back(){ this.$router.back()//后退 }, forward(){ this.$router.forward() //前进 }, test(){ this.$router.go(参数) //可以后退前进 }, }
10.缓存路由组件
1.作用:让不展示的路由组件保持挂载,不被销毁
2.具体编码:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
11.两个新的生命周期钩子
1.作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态
2.具体名字:
-
activated路由组件被激活时触发
-
deactivated路由失活时触发
activated() { console.log('news组件被激活了') this.timer=setInterval(() => { console.log('@') this.opacity -=0.01 if(this.opacity<=0)this.opacity=1 },200); }, deactivated() { console.log('news组件失活了') clearInterval(this.timer) }
12.路由守卫
1.作用:对路由进行权限控制
2.分类:全局守卫、独享守卫、组件守卫
3.全局守卫:
// 全局路由守卫--初始化的时候被调用、每次路由切换之前被调用 router.beforeEach((to,from,next)=>{ console.log('前置路由守卫',to,from) if(to.meta.isAuth){ if(localStorage.getItem('school')==='atguigu'){ next() }else{ alert('学校名称不对,无权限查看!') } }else{ next() } }) // 全局后置路由守卫--初始化的时候被调用、每次路由切换中后被调用 router.afterEach((to,from)=>{ document.title=to.meta.title || 'demo系统' console.log('后置路由守卫',to,from) })
4:独享路由守卫:
某个页面单独享用的路由守卫
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ if(localStorage.getItem('school')==='atguigu'){ next() }else{ alert('学校名称不对,无权限查看!') } }else{ next() } }
5.组件内守卫:
// 进入守卫,通过路由规则,进入该组件时被调用 beforeRouteEnter(to,from,next){ console.log('beforeRouteEnter',to,from) if(to.meta.isAuth){ // 判断是否需要鉴权 if(localStorage.getItem('school')==='atguigu'){ next() }else{ alert('学校名称不对,无权查看!') } }else{ next() } }, // 进入守卫,通过路由规则,离开该组件时被调用 beforeRouteLeave(to,from,next){ console.log('beforeRouteLeave',to,from) next() }, beforeRouteEnter(to,from,next){}; beforeRouteLeave(to,from,next){};
13.路由的两种工作模式
-
对于一个url来说什么是hash值?——#及其后面的内容就是hash值
-
hash值不会包含在http请求中,即:hash值不会带给服务器
-
hash模式:
-
地址中永远带着#号,不美观
-
若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记不合法
-
兼容性较好
-
-
history模式:
-
地址干净、美观
-
兼容性和hash模式相比较差
-
应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题
-
14.配置node+express来部署线上页面
-
创建一个空文件
-
npm init
-
npm i express 安装express
-
创建一个server.js文件,配置
-
const express =require('express') //引入express //const history=require('connect-history-api-fallback') const app=express() //app.use(history()) 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('服务器已启动!') })
-
为了能够浏览history模式
-
npm i connect-history-api-fallback 安装写好的库
-
const history=require('connect-history-api-fallback') //引用文件 app.use(history()) //使用
-
node server 启动服务