D29.Vue
F10.组件编码流程 + 组件自定义事件 + 全局事件总线(K64-K66)
1.组件编码流程
A.组件编码流程:
1)拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突
2)实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件用:
a. 一个组件在用:放在组件自身即可
b. 一些组件在用:放在他们共同的父组件上(状态提升)
3)实现交互:从绑定事件开始
B.props适用于:
1)父组件 ==> 子组件 通信
2)子组件 ==> 父组件 通信(要求父先给子一个函数)
C.使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!
D.props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做
2.组件自定义事件
组件自定义事件是一种组件间通信的方式,适用于:子组件 ===> 父组件
使用场景:
A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)
A.绑定自定义事件
第一种方式,在父组件中:<Demo @atguigu="test"/>
或 <Demo v-on:atguigu="test"/>
具体代码
1)App.vue
<template>
<div class="app">
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
<Student @atguigu="getStudentName"/>
</div>
</template>
<script>
import Student from './components/Student'
export default {
name:'App',
components:{Student},
data() {
return {
msg:'你好啊!',
studentName:''
}
},
methods: {
getStudentName(name,...params){
console.log('App收到了学生名:',name,params)
this.studentName = name
}
}
}
</script>
<style scoped>
.app{
background-color: gray;
padding: 5px;
}
</style>
2)Student.vue
<template>
<div class="student">
<button @click="sendStudentlName">把学生名给App</button>
</div>
</template>
<script>
export default {
name:'Student',
data() {
return {
name:'张三',
}
},
methods: {
sendStudentlName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
第二种方式,在父组件中:
使用 this.$ refs.xxx.$on() 这样写起来更灵活,比如可以加定时器啥的
具体代码
3)App.vue
<template>
<div class="app">
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
<Student ref="student"/>
</div>
</template>
<script>
import Student from './components/Student'
export default {
name:'App',
components:{Student},
data() {
return {
studentName:''
}
},
methods: {
getStudentName(name,...params){
console.log('App收到了学生名:',name,params)
this.studentName = name
},
},
mounted() {
this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
},
}
</script>
<style scoped>
.app{
background-color: gray;
padding: 5px;
}
</style>
4)Student.vue
<template>
<div class="student">
<button @click="sendStudentlName">把学生名给App</button>
</div>
</template>
<script>
export default {
name:'Student',
data() {
return {
name:'张三',
}
},
methods: {
sendStudentlName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
若想让自定义事件只能触发一次,可以使用once
修饰符,或$once
方法
触发自定义事件:this. $emit('atguigu',数据)
使用 this.$emit()
就可以子组件向父组件传数据
注:通过this. $ refs.xxx.$on('atguigu',回调)
绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
B.解绑自定义事件
this.$off('atguigu')
1)代码
this.$off('atguigu') //解绑一个自定义事件
// this.$off(['atguigu','demo']) //解绑多个自定义事件
// this.$off() //解绑所有的自定义事件
C.组件使用原生事件
组件上也可以绑定原生DOM事件,需要使用native修饰符
如果不用.native修饰符就会被当成自定义事件
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
<Event1 @click.native="handler1"></Event1>
a. 原生DOM—button可以绑定系统事件----click单击事件等等
b. 组件标签— event1可以绑定系统事件(不起作用,因为属于自定义事件)----native(可以把自定义事件变为原生DOM事件)
利用native触发—原理是事件委派
在views/Communication/EventTest/Event1.vue
中:
他的结构是这样的,但是我们在页面中,不管是点击Event1组件,还是其他内容,都可以触发打印,那是因为当前原生DOMclick事件,其实是给子组件的根节点div绑定了点击事件----利用事件委派,所以里面的h2和span也是可以触发打印的
注:给原生DOM绑定自定义事件没有任何意义的,因为没有办法触发$emit函数
一般是给组件绑定自定义事件在结合 $on, $emit使用
D.自定义组件中的 $event
1)一般子组件传给父组件的值在methods对象中的函数接收,然而有时想从当前组件传些数据,但是这样就无法接收子组件传来的数据了
这时可以使用 $event
子组件 传值
export default {
methods: {
customEvent() {
this.$emit( custom-event , value )
}
}
}
父组件
接收自定义事件
<template>
<div>
<my-item v-for="(item, index) in list" @custom-event="customEvent(index, $event)">
</my-list>
</div>
</template>
接收$event
export default {
methods: {
//e就是接收过来的$event 现在他就是子组件传过来的值 不再是 对象事件
customEvent(index, e) {
console.log(e) // some value
}
}
}
3.全局事件总线
一种可以在任意组件间通信的方式,本质上就是一个对象,它必须满足以下条件
a. 所有的组件对象都必须能看见他
b. 这个对象必须能够使用 $ on$ emit$off方法去绑定、触发和解绑事件
A.
1)使用步骤
a.一种组件间通信的方式,适用于任意组件间通信
b.安装全局事件总线:
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
},
......
})
c.使用事件总线:
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
methods(){
demo(data){......}
}
......
mounted() {
this.$bus.$on('xxxx',this.demo)
}
提供数据:this. $bus. $emit(‘xxxx’,数据)
d.最好在beforeDestroy钩子中,用 $ off去解绑当前组件所用到的事件
因为销毁的时候只会把组件销毁,不会把 $bus上的销毁,下车要把东西带走
F11.CLI 初始化脚手架(K67-68)
1.Vue CLI 初始化脚手架
A.具体步骤
1)如果下载缓慢请配置npm淘宝镜像npm config set registry http://registry.npm.taobao
2)全局安装 @vue/cli npm install -g @vue/cli
3)切换到创建项目的目录,使用命令创建项目vue create xxx
4)选择使用vue的版本
5)启动项目npm run serve
6)打包项目npm run build
7)暂停项目 Ctrl+C
Vue脚手架隐藏了所有webpack相关的配置,若想查看具体的webpack配置,请执行vue inspect > output.js
B.脚手架文件结构
.文件目录
├── node_modules
├── public
│ ├── favicon.ico: 页签图标
│ └── index.html: 主页面
├── src
│ ├── assets: 存放静态资源
│ │ └── logo.png
│ │── component: 存放组件
│ │ └── HelloWorld.vue
│ │── App.vue: 汇总所有组件
│ └── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件
├── README.md: 应用描述文件
└── package-lock.json: 包版本控制文件
1)脚手架demo
components
就直接把单文件组件的 School.vue 和 Student.vue 两个文件直接拿来用,不需要修改
2)App.vue
引入这两个组件,注册一下这两个组件,再使用
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<Student></Student>
<School></School>
</div>
</template>
<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components: {
School,
Student
}
}
</script>
3)main.js:
入口文件
// 该文件是整个项目的入口文件
import Vue from 'vue' // 引入Vue
import App from './App.vue' // 引入App组件,它是所有组件的父组件
Vue.config.productionTip = false
new Vue({
el:'#app',
render: h => h(App), // render函数完成了这个功能:将App组件放入容器中
})// .$mount('#app')
4)index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<!-- 针对IE浏览器的特殊配置,含义是让IE浏览器以最高渲染级别渲染页面 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 开启移动端的理想端口 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 配置页签图标 <%= BASE_URL %>是public所在路径,使用绝对路径 -->
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- 配置网页标题 -->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 当浏览器不支持js时,noscript中的元素就会被渲染 -->
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<!-- 容器 -->
<div id="app"></div>
</body>
</html>
F12.组件通信(K69-K74)
1.props
适用于的场景:父子组件通信
1)注:
如果父组件给子组件传递数据(函数):本质其实是子组件给父组件传递数据
如果父组件给子组件传递数据(非函数):本质就是父组件给子组件传递数据
2)书写方式:3种
[‘todos’],{type:Array},{type:Array,default:[]}
特殊情况:路由传递props 1:布尔值类型,把路由中params参数映射为组件props数据 2:对象,静态数据,很少用 3:函数,可以把路由中params|query参数映射为组件props数据
2.自定义事件
1)使用于场景:子组件给父组件传递数据
$ on与$emit
- $emit绑定一个自定义事件event,当这个这个语句被执行到时,就会将参数arg传递给父组件,父组件通过@event监听并接收参数
3.全局事件总线 $bus
1)使用于场景:万能
2)组件实例的原型的原型指向的Vue.prototype
Vue.prototype. $bus = this;
a. 对于比较小型的项目,没有必要引入 vuex 的情况下,可以使用 eventBus
b. 它的实现思想也很好理解,在要相互通信的两个组件中,都引入同一个新的vue实例,然后在两个组件中通过分别调用这个实例的事件触发和监听来实现通信
4.pubsub-js
1)适用于场景:万能
2)vue当中几乎不用(因为vue中有全局事件总线和这个第三方提供的库功能重复)
3)在React框架中使用比较多(发布与订阅)
5.Vuex
1)适用于场景:万能
2)数据非持久化
3)核心概念: State:保存所有组件的共享状态 Getters:类似状态值的计算属性 Mutations:修改 State中状态值的唯一方法,里面包含状态变化监听器和记录器 Actions:用于异步处理 State中状态值,异步函数结束后调用Mutations Modules:当一个 State 对象比较庞大时,可以将 State 分割成多个Modules 模块
6.插槽
1)适用于场景:父子组件通信 — (结构)
默认插槽 具名插槽 作用域插槽:子组件的数据来源于父组件,但是子组件的自己的结构有父亲决定
插槽就是子组件中的提供给父组件使用的一个占位符,用< slot>< /slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的< slot>< /slot>标签
7.小总结
1)可以实现任意组件的通信的方法有两个:事件总线 和 Vuex,事件总线难维护数据但轻量,Vux维护数据方便但比较重量
2)可以实现父与子孙跨越层级通信的方法也有两个:$attrs/ $listeners
和provide/inject
,$attrs/ $listeners
具有响应性且可以双向通信,provide/inject
无响应性且只能单向通信(父传子)
3)只能实现父与子组件通信的方法有一个:props/emit
,方法比较基础,适合只有父子组件通信的方法,若想跨层级通信需要中间组件做转发,比较麻烦
8.v-model
1)CustomInput.vue<template> <div style="background: #ccc; height: 50px;"> <h2>input包装组件</h2> <!-- :value 动态数据v-bind @input 给原生DOM绑定原生DOM事件 --> <input type="text" :value="value" @input="$emit('input',$event.target.value)"> </div> </template> <script type="text/ecmascript-6"> export default { name: 'CustomInput', props:['value'] } </script>
2)ModelTest.vue
<template> <div> <!-- 深入学习v-model:实现父子组件数据同步(实现父子组件通信) --> <hr /> <!-- 组件身上的:value是props,父子组件通信 这里的@input是 非原生DOM的input事件 ,属于自定义事件 --> <CustomInput :value="msg" @input="msg = $event" /> <!--上面那种写法可以简化为下面这种写法,可以实现父子组件数据同步, v-model不仅可以在表单元素身上使用,还可以在非表单元素身上使用, 后台管理系统中经常在非表单元素身上,或者已经封装好的身上v-model--> <CustomInput v-model="msg" /> <span>{{ msg }}</span> </div> </template> <script type="text/ecmascript-6"> import CustomInput from './CustomInput.vue' export default { name: 'ModelTest', components: { CustomInput }, data() { return { msg: '我爱你中国' } }, } </script>
F13.nextTick 过渡与动画(K75-K78)
1.nextTick
这是一个生命周期钩子
1)语法:this.$nextTick(回调函数)
2)作用:在下一次 DOM 更新结束后执行其指定的回调
3)什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行
比如编辑按钮使文本变成表单且自动获取焦点
点击表单时会用一个布尔值配合v-show使表单显示,可是改变布尔值的时候,后面的focus方法会跟着执行,然后再渲染模板<template> <li> <label> <input type="checkbox" :checked="todo.done" > <span v-show="!todo.isEdit">{{ todo.title }}</span> <input type="text" v-show="todo.isEdit" :value="todo.title"ref="inputTitle"/> </label> <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)"> 编辑 </button> </li> </template> <script> export default { name: "MyItem", props: ["todo"], // 声明接收todo methods: { handleEdit(todo) { // 编辑 if (todo.hasOwnProperty("isEdit")) { todo.isEdit = true; } else { this.$set(todo, "isEdit", true); } this.$nextTick(function () { this.$refs.inputTitle.focus(); }); }, }, }; </script>
2.过渡与动画
A.基本介绍
1)Vue 在插入、更新或者移除 DOM 时,提供多种不同方式的应用过渡效果。 包括以下工具: 1、在 CSS 过渡和动画中自动应用 class; 2、配合使用第三方 CSS 动画库,如 Animate.css; 3、在过渡钩子函数中使用 JavaScript 直接操作 DOM; 4、配合使用第三方 JavaScript 动画库,如 Velocity.js
2)作用:Vue封装的在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名
3)写法:
a. 准备好样式:
元素进入的样式:v-enter:进入的起点
v-enter:进入的起点
v-enter-to:进入的终点
元素离开的样式:v-leave:离开的起点
v-leave-active:离开过程中
v-leave-to:离开的终点
b. 使用< transition>包裹要过度的元素,并配置name属性,此时需要将上面样式名的v换为name<transition name="hello"> <h1 v-show="isShow">你好啊!</h1> </transition>
c. 要让页面一开始就显示动画,需要添加appear
d. 备注:若有多个元素需要过度,则需要使用:< transition-group>,且每个元素都要指定key值<transition-group name="hello" appear> <h1 v-show="!isShow" key="1">你好啊!</h1> <h1 v-show="isShow" key="2">尚硅谷!</h1> </transition-group>
e. 第三方动画库Animate.css
<template> <div> <button @click="isShow = !isShow">显示/隐藏</button> <transition-group appear name="animate__animated animate__bounce" enter-active-class="animate__swing" leave-active-class="animate__backOutUp" > <h1 v-show="!isShow" key="1">你好啊!</h1> <h1 v-show="isShow" key="2">尚硅谷!</h1> </transition-group> </div> </template> <script> import 'animate.css' export default { name:'Test', data() { return { isShow:true } }, } </script>
B.过渡的使用
<template> <div> <button @click="isShow = !isShow">显示/隐藏</button> <transition-group name="hello" appear> <h1 v-show="!isShow" key="1">你好啊!</h1> <h1 v-show="isShow" key="2">尚硅谷!</h1> </transition-group> </div> </template> <script> export default { name:'Test', data() {return {isShow:true}}, } </script> <style scoped> h1 { background-color: orange; /* transition: 0.5s linear; */ } /* 进入的起点、离开的终点 */ .hello-enter,.hello-leave-to { transform: translateX(-100%); } .hello-enter-active,.hello-leave-active{ transition: 0.5s linear; } /* 进入的终点、离开的起点 */ .hello-enter-to,.hello-leave { transform: translateX(0); } </style>
F14.Vue-Router(K79-K83)
1.相关理解
A.vue-router 的理解
1)vue的一个插件库,专门用来实现SPA应用
B.对SPA应用的理解
1)单页Web应用(single page web application,SPA)
2)整个应用只有一个完整的页面
3)点击页面中的导航链接不会刷新页面,只会做页面的局部更新
4)数据需要通过ajax请求获取
C.路由的理解
1)一个路由就是一组映射关系(key - value)key
为路径,value
可能是function
或component
2)路由分类 后端路由 理解:value是function,用于处理客户端提交的请求 工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据 前端路由 理解:value是component,用于展示页面内容 工作过程:当浏览器的路径改变时,对应的组件就会显示
a. 用户点击了页面上的路由链接(本质是a链接)
b. 导致了 URL 地址栏中的 Hash 值发生了变化
c. 前端路由监听了到 Hash 地址的变化
d. 前端路由把当前 Hash 地址对应的组件渲染都浏览器中
结论:前端路由,指的是 Hash 地址与组件之间的对应关系!
2.基本路由
A.基本使用
1)安装vue-router,命令:npm i vue-router@3
2)应用插件:Vue.use(VueRouter)
3)编写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
4)实现切换
< router-link>< /router-link>
浏览器会被替换为a标签active-class
设置 链接激活时使用的 CSS 类名实现切换 <router-link></router-link>浏览器会被替换为a标签 active-class设置 链接激活时使用的 CSS 类名
5)指定展示位置
<router-view></router-view>
切换的时候会把路由销毁,触发销毁生命周期函数
B.实际使用
1)src/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 } ] })
2)src/main.js
import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' // 引入VueRouter import router from './router' // 引入路由器 Vue.config.productionTip = false Vue.use(VueRouter) // 应用插件 new Vue({ el:'#app', render: h => h(App), router:router })
3)src/App.vue
<template> <div> <!-- 原始html中我们使用a标签实现页面的跳转 --> <!-- <a class="list-group-item active" href="./about.html">About</a> --> <!-- <a class="list-group-item" 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> <!-- 指定组件的呈现位置 --> <router-view></router-view> </div> </template> <script> export default { name:'App' } </script>
4)src/components/Home.vue
<template> <h2>我是Home的内容</h2> </template> <script> export default { name:'Home' } </script>
5)src/components/About.vue
<template> <h2>我是About的内容</h2> </template> <script> export default { name:'About' } </script>
3.几个注意点
1)路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹
2)通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载
3)每个组件都有自己的$route(路由)属性,里面存储着自己的路由信息
4)整个应用只有一个router,可以通过组件的 $router(路由器)属性获取到
4.多级路由
1)配置路由规则,使用children配置项:routes:[ { path:'/about', component:About, }, { path:'/home', component:Home, children:[ //通过children配置子级路由 { path:'news', //此处一定不要写:/news component:News }, { path:'message',//此处一定不要写:/message component:Message } ] } ]
2)跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
3)指定展示位置
<router-view></router-view>
a. src/pages/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', } </script>
b. src/pages/Message.vue
<template> <ul> <li> <a href="/message1">message001</a> </li> <li> <a href="/message2">message002</a> </li> <li> <a href="/message/3">message003</a> </li> </ul> </template> <script> export default { name:'News' } </script>
c. src/router/index.js
//该文件专门用于创建整个应用的路由器 import VueRouter from "vue-router"; //引入组件 import Home from '../pages/Home' import About from '../pages/About' import News from '../pages/News' import Message from '../pages/Message' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home, children:[ { path:'news', component:News }, { path:'message', component:Message } ] } ] })
5.vue中路由重定向redirect
A.重定向到平级的路径上去
第一个对象里是配置路由path:’/'
为项目的根目录,redirect重定向为渲染的路径redirect:'/index'
(这里我是指向了第二个对象里的path),所以就要写第二个对象方便 redirect 找到它
重定向的地址不需要接收参数,把"/“重定向到”/index"
B.重定向到子路由路径上面去
父路由(path:‘/’)重定向到相应的子路由路径上去了 redirect:‘/index’
6.命名路由
1)作用:可以简化路由的跳转
2)如何使用
a. 给路由命名:{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //给路由命名 path:'welcome', component:Hello, } ] } ] }
b. 简化跳转:
<!--简化前,需要写完整的路径 --> <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>
7.路由的query参数
1)传递参数<!-- 跳转并携带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>
2)接收参数:
$route.query.id $route.query.title
8.路由的params参数
A.基本使用
1)配置路由,声明接收params参数{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }
2)传递参数
<!-- 跳转并携带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配置!
3)接收参数:$route.params.id $route.params.title
B.params传参问题
1)如何指定params参数可传可不传
如果路由path要求传递params参数,但是没有传递,会发现地址栏URL有问题,详情如下:Search路由项的path已经指定要传一个keyword的params参数,如下所示: path: "/search/:keyword", 执行下面进行路由跳转的代码: this.$router.push({name:"Search",query:{keyword:this.keyword}}) 当前跳转代码没有传递params参数 地址栏信息:http://localhost:8080/#/?keyword=asd 此时的地址信息少了/search 正常的地址栏信息: http://localhost:8080/#/search?keyword=asd
解决方法
可以通过改变path来指定params参数可传可不传 path: “/search/:keyword?”,?表示该参数可传可不传
2)由(1)可知params可传可不传,但是如果传递的是空串,如何解决this.$router.push({name:"Search",query:{keyword:this.keyword},params:{keyword:''}}) 出现的问题和1中的问题相同,地址信息少了/search
解决方法
加入||undefined
,当我们传递的参数为空串时地址栏url也可以保持正常this.$router.push({name:"Search",params:{keyword:this.keyword||undefined}})
9.路由的props配置
1)作用:让路由组件更方便的收到参数{ 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({query:{id,title}}){ return { id,title }, props({params:{id,title}}){ return { id,title } } }
2)src/pages/Detail.vue
<template> <ul> <li>消息编号:{{ id }}</li> <li>消息标题:{{ title }}</li> </ul> </template> <script> export default { name:'Detail', props:['id','title'] } </script>
10.replace
1)作用:控制路由跳转时操作浏览器历史记录的模式
2)浏览器的历史记录有两种写入方式:分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
3)如何开启replace模式:< router-link replace .......>News< /router-link>
总结:浏览记录本质是一个栈,默认push,点开新页面就会在栈顶追加一个地址,后退,栈顶指针向下移动,改为replace就是不追加,而将栈顶地址替换
src/pages/Home.vue<template> <div> <h2>Home组件内容</h2> <div> <ul class="nav nav-tabs"> <li> <router-link replace class="list-group-item" active-class="active" to="/home/news">News</router-link> </li> <li> <router-link replace 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' } </script>
11.编程式路由导航
A.基本使用
1)作用:不借助< router-link>
实现路由跳转,让路由跳转更加灵活this. $ router.push({})
内传的对象与<router-link>
中的to相同,跳转到指定 hash 地址,并增加一条历史记录this. $ router.replace({})
跳转到指定的 hash 地址,并替换掉当前的历史记录this. $ router.forward()
前进this. $ router.back()
后退this.$router.go(n)
可前进也可后退,n为正数前进n,为负数后退
src/pages/Message.vue<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <button @click="showPush(m)">push查看</button> <button @click="showReplace(m)">replace查看</button> </li> </ul> <hr/> <router-view></router-view> </div> </template> <script> export default { name:'News', data(){ return{ messageList:[ {id:'001',title:'消息001'}, {id:'002',title:'消息002'}, {id:'003',title:'消息003'} ] } }, methods:{ showPush(m){ this.$router.push({ name:'xiangqing', query:{ id:m.id, title:m.title } }) }, showReplace(m){ this.$router.replace({ name:'xiangqing', query:{ id:m.id, title:m.title } }) } } } </script>
src/components/Banner.vue
<template> <div class="col-xs-offset-2 col-xs-8"> <div class="page-header"> <h2>Vue Router Demo</h2> <button @click="back">后退</button> <button @click="forward">前进</button> <button @click="test">测试一下go</button> </div> </div> </template> <script> export default { name:'Banner', methods:{ back(){ this.$router.back() }, forward(){ this.$router.forward() }, test(){ this.$router.go(3) } }, } </script>
简化写法
<button @click="$router.forward">前进</button> <button @click="$router.back">后退</button>
B.多次执行相同的push问题
1)多次执行相同的push问题,控制台会出现警告
例如:使用this. $ router.push({name:'Search',params:{keyword:".."||undefined}})
时,如果多次执行相同的push,控制台会出现警告let result = this.$router.push({name:"Search",query:{keyword:this.keyword}}) console.log(result)
执行一次上面代码:
多次执行出现警告:
原因:push是一个promise,promise需要传递成功和失败两个参数,我们的push中没有传递
方法:this. $ router.push({name:'Search',params:{keyword:".."||undefined}},()=>{},()=>{})
后面两项分别代表执行成功和失败的回调函数
这种写法治标不治本,将来在别的组件中push|replace,编程式导航还是会有类似错误
push是VueRouter.prototype的一个方法,在router中的index重写该方法即可(看不懂也没关系,这是前端面试题)//1、先把VueRouter原型对象的push,保存一份 let originPush = VueRouter.prototype.push; //2、重写push|replace //第一个参数:告诉原来的push,跳转的目标位置和传递了哪些参数 VueRouter.prototype.push = function (location,resolve,reject){ if(resolve && reject){ //因为函数是被window调用,这里函数内部的this得是vuerouter实例 originPush.call(this,location,resolve,reject) }else{ originPush.call(this,location,() => {},() => {}) } }
12.缓存路由组件
1)作用:让不展示的路由组件保持挂载,不被销毁
2)具体编码:
这个 include 指的是组件名// 缓存一个路由组件 <keep-alive include="News"> // include中写想要缓存的组件名,不写表示全部缓存 <router-view></router-view> </keep-alive> // 缓存多个路由组件 <keep-alive :include="['News','Message']"> <router-view></router-view> </keep-alive>
src/pages/News.vue
<template> <ul> <li>news001 <input type="text"></li> <li>news002 <input type="text"></li> <li>news003 <input type="text"></li> </ul> </template> <script> export default { name:'News' } </script>
13.两个新的生命周期钩子
1)作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态
2)具体名字:
a. activated路由组件被激活时触发
b. deactivated路由组件失活时触发
因为这个路由使用keep-alive,所以切换不会清除定时器
src/pages/News.vue<template> <ul> <li :style="{opacity}">欢迎学习vue</li> <li>news001 <input type="text"></li> <li>news002 <input type="text"></li> <li>news003 <input type="text"></li> </ul> </template> <script> export default { name:'News', data(){ return{ opacity:1 } }, activated(){ console.log('News组件被激活了') this.timer = setInterval(() => { this.opacity -= 0.01 if(this.opacity <= 0) this.opacity = 1 },16) }, deactivated(){ console.log('News组件失活了') clearInterval(this.timer) } } </script>
14.路由守卫
1)作用:对路由进行权限控制
2)作用:对路由进行权限控制
路由守卫总共有7个
全局路由守卫:
a. beforeEach 前置守卫
b. affterEach 后置守卫
c. affterEach 后置守卫
路由的守卫
d. beforeRouterEnter 进入组件之前触发,在Created前面
e. beforeRouterUpdated 路由更新但是内容不会改变
f. beforeRouterUpdated 路由更新但是内容不会改变
路由独享守卫
g. beforeEnter 读取路由的信息
A.全局路由守卫
1)每次发生路由的导航跳转时,都会触发全局前置守卫。因此,在全局前置守卫中,程序员可以对每个路由进行访问权限的控制:
你可以使用 router.beforeEach 注册一个全局前置守卫://创建路由的实例对象 const router = new VueRouter({...}) //为router实例对象,声明全局前置导航守卫 //只要发生了路由的跳转,必然会触发beforeEach指定的function回调函数 router.beforeEach((to, from, next)=>{ //to是将要访问的路由的信息对象 //from是将要离开的路由的信息对象 //next是一个函数,调用next()表示放行,允许这次路由导航 next(); //next函数表示放行的意思 }) export default router
每个守卫方法接收三个参数:
to: Route: 即将要进入的目标路由对象
from: Route: 当前导航正要离开的路由
next: Function: 钩子函数,里面定义参数,确认下一步路由要做什么
next(’/’)
或者next({ path: ‘/’ }):
跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,next({name: ‘home’})
2)next 函数的 3 种调用方式
当前用户拥有后台主页的访问权限,直接放行:next()
当前用户没有后台主页的访问权限,强制其跳转到登录页面:next(‘/login’)
当前用户没有后台主页的访问权限,不允许跳转到后台主页:next(false)
当前用户没有后台主页的访问权限,不允许跳转到后台主页:next(false)router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' }) else next() })
例
//该文件专门用于创建整个应用的路由器 import VueRouter from "vue-router"; //引入组件 import Home from '../pages/Home' import About from '../pages/About' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建一个路由器 const router = new VueRouter({ routes:[ { name:'guanyv', path:'/about', component:About, meta:{title:'关于'} }, { name:'zhuye', path:'/home', component:Home, meta:{title:'主页'}, children:[ { name:'xinwen', path:'news', component:News, meta:{isAuth:true,title:'新闻'} }, { name:'xiaoxi', path:'message', component:Message, meta:{isAuth:true,title:'消息'}, children:[ { name:'xiangqing', path:'detail', component:Detail, meta:{isAuth:true,title:'详情'}, props($route){ return { id:$route.query.id, title:$route.query.title, } } } ] } ] } ] }) // 全局前置路由守卫————初始化的时候、每次路由切换之前被调用 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)=>{ console.log('后置路由守卫',to,from) document.title = to.meta.title || '硅谷系统' }) // 导出路由器 export default router
B.独享路由守卫
1)你可以在路由配置上直接定义 beforeEnter 守卫:const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
这些守卫与全局前置守卫的方法参数是一样的
例//该文件专门用于创建整个应用的路由器 import VueRouter from "vue-router"; //引入组件 //创建一个路由器 const router = new VueRouter({ routes:[ { name:'zhuye', path:'/home', component:Home, meta:{title:'主页'}, children:[ { name:'xinwen', path:'news', component:News, meta:{title:'新闻'}, // 独享守卫,特定路由切换之后被调用 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() } } }, ] } ] }) //全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用 router.afterEach((to,from)=>{ console.log('后置路由守卫',to,from) document.title = to.meta.title || '硅谷系统' }) //导出路由器 export default router
C.组件内路由守卫
1)可以在路由组件内直接定义以下路由导航守卫:
进组组件前的守卫 beforeRouteEnter 路由更新时的守卫 beforeRouteUpdate (2.2 新增) 离开组件时的守卫 beforeRouteLeavebeforeRouteEnter(to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 this // 因为当守卫执行前,组件实例还没被创建 }, beforeRouteUpdate(to, from, next) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 this }, beforeRouteLeave(to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 this }
beforeRouteEnter
守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建
不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数beforeRouteEnter (to, from, next) { next(vc => { vc.$store.state.token // 通过 `vc` 访问组件实例 }) }
注意 beforeRouteEnter 是支持给 next传递回调的唯一守卫。对于 beforeRouteUpdate和beforeRouteLeave 来说,this 已经可用了,所以不支持传递回调,因为没有必要了
beforeRouteUpdate (to, from, next) { this.name = to.params.name next() }
这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消
beforeRouteLeave (to, from, next) { const answer = window.confirm('你真的要离开吗?你还没有保存!') if (answer) { next() } else { next(false) } }
D.总结
1)完整的导航解析流程 导航被触发。 在失活的组件里调用beforeRouteLeave
守卫。 调用全局的 beforeEach 守卫。 在重用的组件里调用beforeRouteUpdate守卫 (2.2+)
。 在路由配置里调用beforeEnter
。 解析异步路由组件。 在被激活的组件里调用beforeRouteEnter
。 调用全局的beforeResolve 守卫 (2.5+)
。 导航被确认。 调用全局的afterEach
钩子。 触发 DOM 更新。 调用beforeRouteEnter
守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入
15.路由懒加载
1)当打包构建应用时,JavaScript 包会变得非常大,影响页面加载。如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了{ path: '/center', component: () => import('@/views/Center'), redirect: '/center/myOrder' }
新的导入方式,这样导入在加载时只会按需加载
16.路由器的两种工作模式
1)对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值
2)hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器
3)hash模式:
a. 地址中永远带着#号,不美观
b. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法
c. 兼容性较好
4)history模式:
a. 地址干净,美观
b. 兼容性和hash模式相比略差
c. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题
17.监听路由
1)复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch(监测变化) $ route 对象:
最佳方法:我们每次进行新的搜索时,我们的query和params参数中的部分内容肯定会改变,而且这两个参数是路由的属性。我们可以通过监听路由信息的变化来动态发起搜索请求
如下图所示,$route是组件的属性,所以watch是可以监听的(watch可以监听组件data中所有的属性) 注意:组件中data的属性包括:自己定义的、系统自带的(如 $route)、父组件向子组件传递的等等
watch:{ $route(newValue,oldValue){ // 对路由变化作出响应... Object.assign(this.searchParams,this.$route.query,this.$route.params) this.searchInfo() //如果下一次搜索时只有params参数,拷贝后会发现searchParams会保留上一次的query参数 //所以每次请求结束后将相应参数制空 this.searchParams.category1Id = ''; this.searchParams.category2Id = ''; this.searchParams.category3Id = ''; this.$route.params.keyword = ''; } },
18.滚动行为
A.
1)使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router 能做到,而且更好,它让你可以自定义路由切换时页面如何滚动
注意: 这个功能只在支持 history.pushState 的浏览器中可用
当创建一个 Router 实例,你可以提供一个 scrollBehavior 方法:const router = createRouter({ history: createWebHashHistory(), routes: [...], //设置滚动条的位置 scrollBehavior (to, from, savedPosition) { //滚动行为这个函数,需要有返回值,返回值为一个对象。 //经常可以设置滚动条x|y位置 [x|y数值的设置一般最小是零] return { top: 0 }; } })
scrollBehavior
函数接收to
和from
路由对象,如Navigation Guards
。第三个参数savedPosition
,只有当这是一个 popstate 导航时才可用(由浏览器的后退/前进按钮触发)
更多推荐
D29 Vue2 + Vue3 K64-K83
发布评论