什么是Vue?
箭头函数没有this,往上层找,找到的第一个就是该this
可以自底向上逐层的应用
简单应用:只需一个轻量小巧的核心库
复杂应用:可以引入各式各样的Vue插件
特点:
hello,{{name}}
注意区分:js表达式 和 js代码(语句)
你好,{{name}}
单向数据绑定:
双向数据绑定:
注:
你好啊
//el的两种写法
const v =new Vue({
el:'#root', //第一种写法
data:{
name:'world'
}
})
console.log(v)
v.$mount('#root')//第二种写法
setTimeout(()=>{
v.$mount('#root')
},1000)//利用定时器
//data的两种写法
new Vue({
el: '#root',
// data:{ //第一种写法:对象式
// name:'world'
// }
//data的第二种写法:函数式
data: function () {//或者写成data()
console.log('@@@', this) //此处的this是Vue实例对象
return {
name: 'world'
}
}
})
M:模型(Model):对应data中的数据
V:视图(View):模板
VM:视图模型(ViewModel):Vue实例对象
观察发现:
1. data中所有的属性,最后都出现在了vm身上。
2. vm身上所有的属性 及 Vue原型上的所有属性,在Vue模板中都可以直接使用。
姓名:{{name}}
地址:{{address}}
测试一下1:{{$emit}}
测试一下2:{{$options}}
const vm = new Vue({
el:'#root',
data:{
name:'小华',
address:'上海'
}
})
console.log(vm)
验证getter和setter图解
欢迎{{name}},你好
1.Vue中常用的按键别名:
2.Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebad-case(短横线命名)
3.系统修饰键(用法特殊):ctrl、alt、shift、meta
4.也可以使用keyCode去指定具体的按键(不推荐)
5.Vue.config.keyCodes.自定义键名 = 键码, 可以去定制按键别名
欢迎{{name}},你好
姓:
名:
全名:{{firstName.slice(0,3)}}-{{lastName}}
姓:
名:
全名:{{fullName()}}
姓:
名:
全名:{{fullName}}
当计算属性 computed 只有get()时
//简写,只考虑读取,不考虑修改时才可用
fullName(){
console.log('get被调用了')
return this.firstName + "-" + this.lastName
}
今天天气很{{info}}
a的值:{{numbers.a}}
b的值:{{numbers.b}}
深度监视简写:当watch属性里只有handler时
watch:{
//正常写法
isHot:{
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}
//简写
isHot(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
}
//正常写法
vm.$watch('isHot',{
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
}
})
//简写
vm.$watch('isHot',function(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue)
})
区别:
两个重要的小原则:
{{name}}
{{name}}
{{name}}
{{name}}
{{name}}
data:{
isHot:true,
name:'xiaoha',
mood:'normal',
classArr:['at1','at2','at3'],
classObj:{
at1:false,
at2:false
},
styleObj:{
fontSize:'40px'
},
styleArr:[
{
fontSize:'40px',
color:'blue'
},
{
backgroundColor:'gray'
}
]
}
你好
小华
上海
<%--遍历数组--%>
人员列表(遍历数组)-用的最多
<%-- -
{{p.name}}-{{p.age}}
--%>
-
{{p.name}}-{{p.age}}
<%--遍历对象--%>
汽车信息(遍历对象)
-
{{key}}-{{value}}
<%--遍历字符串--%>
测试遍历字符串(用的少)
-
{{index}}-{{char}}
<%--遍历指定次数--%>
测试遍历字符串(用的少)
-
{{index}}-{{number}}
面试题:react、vue中的key有什么作用?(key的内部原理)
人员列表
-
{{p.name}}-{{p.age}}-{{p.sex}}
注意:@click里是赋值语句,sort排序函数,降序为后数-前数,反之为前数-后数
人员列表
-
{{p.name}}-{{p.age}}-{{p.sex}}
Vue监视数据的原理:
学校信息
学校名称:{{school.name}}
学校地址:{{school.address}}
校长是:{{school.leader}}
学生信息
姓名:{{student.name}}
性别:{{student.sex}}
年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}
爱好
-
{{h}}
朋友们
-
{{f.name}}---{{f.age}}
显示格式化后的时间
现在是:{{fmtTime}}
现在是:{{time | timeFormater}}
现在是:{{time | timeFormater('YYYY年MM月DD日') | mySlice}}
name:'小华
'
初始化的n值是:{{n}}
当前的n值是:{{n}}
Vue其实很简单
//跳过该条语句的编译
姓名:{{name}}
一、定义语法:
二、配置对象中常用的3个回调:
三、备注
当前的n值是:
放大10倍后的n值是:
欢迎学习Vue
当应用中的js都以模块来编写的,那这个应用就是一个模块化的应用。
当应用中的功能都是多组件的方式来编写的,那这个应用就是一个组件化的应用。
一个文件中包含有n个组件
一、定义组件(创建组件)
二、注册组件
三、使用组件(写组件标签)
<body>
<div id="root">
div>
body>
<script type="text/javascript">
Vue.config.productionTip = false
//创建student组件
const student = Vue.extend({
template:`
姓名:{{name}}
年龄:{{age}}
`,
data(){
return{
name:"张三",
age:18
}
}
})
//创建school组件
const school = Vue.extend({
template:`
学校名称:{{name}}
学校地址:{{address}}
`,
data(){
return{
name:"尚硅谷",
address:"北京"
}
},
components:{
student
}
})
//创建hello组件
const hello = Vue.extend({
template:`
你好啊,{{name}}
`,
data(){
return{
name:"Tom"
}
}
})
//创建app组件
const app = Vue.extend({
template:`
`,
components:{
school,
hello
}
})
new Vue({
template:` `,
el:'#root',
//注册组件(局部注册)
components: {
app
}
})
script>
School.vue
学校名称:{{name}}
学校地址:{{address}}
Student.vue
姓名:{{name}}
年龄:{{age}}
App.vue
main.js
import App from './App.vue'
new Vue({
template:` `,
el:'#root',
components: {
App
}
})
index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>练习一个单文件组件的语法title>
head>
<body>
<div id="root">
div>
<script type="text/javascript" src="../js/vue.js">script>
<script type="text/javascript" src="./main.js">script>
body>
html>
CLI:command line interface
1.下载一个node.js
2.(仅第一次执行):全局安装@vue/cli
npm install -g @vue/cli
3.切换到你要创建项目的目录,然后使用命令创建项目
cd 具体的项目地址
vue create xxxx(脚手架名称)
4.启动项目
npm run serve
备注: 1.如出现下载缓慢请配置npm淘宝镜像: npm config set registry https://registry.npm.taobao.org
2.Vue 脚手架隐藏了所有webpack相关的配置,若想查看具体的webpack配置,请执行:vue inspect > output.js ——>打开vue.config.js,查看脚手架的默认配置
vue.js与vue.runtime.xxx.js的区别:
vue.js是完整版的Vue,包含:核心功能+模板解析器
vue.runtime.xxx.js是运行版的Vue,只包含:核心功能,没有模板解析器
因为vue.runtime.xxx.js没有模板解析器,所有不能使用template配置项,需要使用render函数接收到的createElement函数去指定具体内容
**vue.config.js **
使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh/
pages:{
index:{
entry:'src/main.js' //项目入口
}
}
lintOnSave:false //关闭语法检查
├── 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:包版本控制文件
功能:让组件接收外部传过来的数据
传递数据:
接收数据:
第一种方式(只接收):
props:['name']
第二种方式(限制类型):
props:{
name:String
}
第三种方式(限制类型、限制必要性、指定默认值):
props:{
name:{
type:String,//类型
required:true//必要性
},
age:{
type:int, //类型
default:19 //默认值
}
}
备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
注:在一个属性中required 和 default 一般不会同时使用
功能:可以把多个组件共用的配置提取成一个混入对象(类似于公共类)
使用方式:
{
data(){
......
},
methods:{
......
},
......
}
功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
定义插件:
export default{
install(Vue,options){
//1.添加全局过滤器
Vue.filter(....)
//2.添加全局指令
Vue.directive(....)
//3.配置全局混入(合)
Vue.mixin(....)
//4.添加实例方法
Vue.prototype.$myMethod = function() {...}
Vue.prototype.$myProperty = xxx
}
}
//或 对象.install = function (Vue, options){ }
使用插件: Vue.use(xxx)
功能:让样式在局部生效,防止冲突。
写法:
xxxxxStorage.getItem(xxx)
如果xxx对应的value获取不到,那么getItem的返回值是null
JSON.parse(null)
的结果依然是null
一种组件间通信的方式,适用于:子组件===>父组件
使用场景:A是父组件,B是子组件,B向给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)
绑定自定义事件:
第一种方式:在父组件中:
或
第二种方式:在父组件中:
methods:{
getStudentName(name){
alert(name)
}
},
mounted(){
setTimeout(()=>{
this.$refs.student.$on('getName',this.getStudentName)
},1000)
// this.$refs.student.$once('getName',this.getStudentName) //一次性
}
若向让自定义事件只能触发一次,可以使用once
修饰符,或$once
方法
触发自定义事件:this.$emit('getName',数据)
解绑自定义事件:this.$off('getName')
组件上也可以绑定原生DOM事件,需要使用native
修饰符
注意:通过this.$refs.xxx.$on('getName',回调)
绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!!!
一种组件间通信的方式,适用于任意组件间通信。
安装全局事件总线:
new Vue({
......
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
}
})
使用事件总线:
1.接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){
demo(data){......}
}
......
mounted(){
this.$bus.$on('xxxx',this.demo)
}
2.提供数据:this.$bug.$emit('xxxx',数据)
最好在beforeDestory钩子中,用$off去解绑当前组件所用到的事件。
一种组件间通信的方式,适用于任意组件间通信
使用步骤:
安装pubsub:npm i pubsub-js
引入:import pubsub form 'pubsub-js
接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
methods(){
//demo(msgName,data){......}
demo(_,data){......} //第一个参数不需要的时候,用_占位
}
......
mounted(){
this.pubId = pubsub.subscribe('xxx',this.demo)//订阅消息
}
提供数据:pubsub.publish('xxx',数据)
最好在beforeDestory钩子中,用pubsub.unsubscribe(this.pubId)
去取消订阅
this.$nextTick(回调函数)
作用:在插入、更新或移除DOM元素时,在合适的时候给元素添加样式类名
写法:
准备好样式:
使用
包裹要过度的元素,并配置name属性:
你好啊!
备注:若有多个元素需要过度,则需要使用:
,且每个元素都要指定key
值
方法一
devServer:{
proxy:"http://localhost:5000"
}
方法二
module.exports = {
devServer:{
proxy:{
'/api1':{//匹配所有以 '/api1' 开头的请求路径
target:'http://localhost:5000', //代理目标的基础路径
changeOrigin:true, //用于控制请求头中的host值
ws:true, // 用于支持websocket
pathRewrite:{'^/api1':''}
},
'/api2':{//匹配所有以 '/api2' 开头的请求路径
target:'http://localhost:5001', //代理目标的基础路径
changeOrigin:true,//用于控制请求头中的host值
ws:true, // 用于支持websocket
pathRewrite:{'^/api2':''}
}
}
}
}
/*
changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
changeOrigin默认值为true,ws默认值也为true
*/
import axios from 'axios'
axios.get("URL").then(
response => {
console.log('请求成功了',response.data)
},
error =>{
console.log('请求失败了',error.message)
}
)
main.js
//引入插件
import vueResource from 'vue-resource'
//使用插件
Vue.use(vueResource)
.vue
this.$http.get("URL").then(
response => {
console.log('请求成功了',response.data),
error =>{
console.log('请求失败了',error.message)
)
作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件
分类:默认插槽、具名插槽、作用域插槽
使用方式:
默认插槽:
html结构
我是一个插槽,当使用者没有传递具体结构时,我会出现
具名插槽:
html结构1
html结构2
我是一个插槽1,当使用者没有传递具体结构时,我会出现
我是一个插槽2,当使用者没有传递具体结构时,我会出现
作用域插槽:
理解:数组在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(films数据在Category组件中,但使用数据所遍历出来的结构由APP组件决定)
具体编码:
- {{f}}
- {{f}}
{{f}}
我是一个插槽1,当使用者没有传递具体结构时,我会出现
概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。
全局事件总线实现
Vuex实现
什么时候使用Vuex?
State,Actions,Mutations都是一个对象,三者要经过store
创建文件:src/store/index.js
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
//准备actions对象——响应组件中用户的动作
const actions ={}
//准备mutations对象——修改state中的数据
const mutations = {}
//准备state对象——保存具体的数据
const state = {}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
在main.js
中创建vm时传入store
配置项
//引入store, 可以简写成import Store from './store'
import store from './store/index'
......
//创建vm
new Vue({
el:'#app',
render: h =>h(App),
store
})
初始化数据、配置actions
、配置mutations
、操作文件store.js
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
const actions = {
incrementOdd(context,value){
console.log(context,value);
if(context.state.sum % 2){
context.commit('INCREMENT',value)
}
},
incrementWait(context,value){
setTimeout(()=>{
context.commit('INCREMENT',value)
},500)
}
}
const mutations = {
INCREMENT(state,value){
state.sum += value
},
DECREMENT(state,value){
state.sum -= value
}
}
//初始化数据
const state = {
sum:0 //当前的和
}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
组件中读取vuex中的数据:$store.state.sum
组件中修改vuex中的数据:this.$store.dispatch('actions中的方法名',数据)
或this.$store.commit('mutations中的方法名',数据)
备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch
,直接编写commit
概念:当state中的数据需要经过加工后再使用时,可以使用getters加工
在store.js
中追加getters
配置
//准备getters——用于将state中的数据进行加工,注意返回值
const getters = {
bigSum(state){
return state.sum *10
}
}
//创建并暴露store
export default new Vuex.Store({
......,
getters
})
组件中读取数据:$store.getters.bigSum
mapState方法:用于帮助我们映射state
中的数据为计算属性
computed:{
//借助mapState生成计算属性:sum、school、subject(对象写法)
...mapState({sum:'sum',school:'school',subject:'subject'}),
//借助mapState生成计算属性:sum、school、subject(数组写法)
...mapState(['sum','school','subject']),
}
mapGetters方法:用于帮助我们映射getters
中的数据为计算属性
computed:{
//借助mapGetters生成计算属性:bigSum(对象写法)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性:bigSum(数组写法)
...mapGetters(['bigSum'])
}
mapActions方法:用于帮助我们生成与actions
对话的方法,即包含$store.dispatch(xxx)
的函数
methods:{
//借助mapActions生成计算属性:incrementOdd、incrementWait(对象写法)
...mapActions({incrementOdd:'incrementOdd',incrementWait:'incrementWait'}),
//借助mapActions生成计算属性:incrementOdd、incrementWait(数组写法)
...mapActions(['incrementOdd','incrementWait'])
}
mapMutations方法:用于帮助我们生成与mutations
对话的方法,即包含$store.commit(xxx)
的函数
methods:{
//借助mapMutations生成计算属性:INCREMENT、DECREMENT(对象写法)
...mapMutations({INCREMENT:'INCREMENT',DECREMENT:'DECREMENT'}),
//借助mapMutations生成计算属性:INCREMENT、DECREMENT(数组写法)
...mapMutations(['INCREMENT','DECREMENT']),
}
备注:mapActions与mapMutations使用时,若需要传递参数:需要在模板中绑定事件时传递好参数,否则参数是事件对象。
目的:让代码更好维护,让多种数据分类更加明确。
创建count.js
export default {
namespaced: true,//开启命名空间
actions:{
incrementOdd(context,value){
console.log(context,value);
if(context.state.sum % 2){
context.commit('INCREMENT',value)
}
},
incrementWait(context,value){
setTimeout(()=>{
context.commit('INCREMENT',value)
},500)
}
},
mutations:{
INCREMENT(state,value){
state.sum += value
},
DECREMENT(state,value){
state.sum -= value
}
},
state:{
sum:0, //当前的和
school:'尚硅谷',
subject:'Vue'
},
getters:{
bigSum(state){
return state.sum *10
}
}
}
创建person.js
import axios from 'axios'
import { nanoid } from 'nanoid'
export default {
namespaced:true,
actions:{
addPersonWang(context,value){
if(value.name.indexOf('王')===0){
context.commit('ADD_PERSON',value)
}else{
alert('添加的人必须为王')
}
},
addPersonServer(context){
axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
response => {
context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
},
error =>{
alert(error.message)
}
)
}
},
mutations:{
ADD_PERSON(state,value){
state.personList.unshift(value)
}
},
state:{
personList:[
{id:'001',name:'张三'}
]
},
getters:{
firstPersonName(state){
return state.personList[0].name
}
}
}
修改store.js
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
import countAbout from './count'
import personAbout from './person'
//应用Vuex插件
Vue.use(Vuex)
//创建并暴露store
export default new Vuex.Store({
modules:{
countAbout,
personAbout
}
})
开启命名空间后,组件中读取state数据:
//方式一:自己直接读取
this.$store.state.personAbout.list
//方式二:借助mapState读取
...mapState('countAbout',['sum','school','subject'])
开启命名空间后,组件中读取getters数据:
//方式一:自己直接读取
this.$store.getters['personAbout/firstPersonName']
//方式二:借助mapGetters读取
...mapGetters('countAbout',['bigSum'])
开启命名空间后,组件中调用dispatch:
//方式一:自己直接dispatch
this.$store.dispatch('personAbout/addPersonWang',person)
//方式二:借助mapActions
...mapActions('countAbout',{incrementOdd:'incrementOdd',incrementWait:'incrementWait'})
开启命名空间后,组件中调用commit:
//方式一:自己直接commit
this.$store.commit('personAbout/ADD_PERSON',person)
//方式二:借助mapMutations
...mapMutations('countAbout',['increment','decrement'])
vue的一个插件库,专门用来实现SPA应用
什么是路由?
路由分类
安装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 class="list-group-item" active-class="active" to="/about">About</router-link>
指定展示位置
<router-view></router-view>
pages
文件夹,一般组件通常存放components
文件夹$route
属性,里面存储着自己的路由信息$router
属性获取到配置路由规则,使用children配置项:
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[//通过children配置子级路由
{
path:'news',//此处一定不要写:/news
component:News
},
{
path:'message',//此处一定不要写:/message
component:Message
}
]
}
]
跳转(要写完整路径):
<router-link to="/home/news">Newsrouter-link>
传递参数
<router-link :to="{
path:'/home/message/detail',
query:{
id:m.id,
title:m.title
}
}">
跳转
router-link>
接收参数
<li>消息id:{{$route.query.id}}li>
<li>消息标题:{{$route.query.title}}li>
作用:可以简化路由的跳转
如何使用
给路由命名:
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message,
children:[
{
name:'xiangqing',//给路由命名
path:'detail',
component:Detail
}
]
}
]
}
简化跳转:
<router-link :to="/home/message/detail">跳转router-link>
<router-link :to="{name:'xiangqing'}">跳转router-link>
<router-link :to="{
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
}">跳转router-link>
配置路由,声明接收params参数
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
path:'message',
component:Message,
children:[
{
name:'xiangqing',//给路由命名
path:'detail/:id/:title',//使用占位符声明接收params参数
component:Detail
}
]
}
]
}
传递参数
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">跳转router-link>
<router-link :to="{
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
}">
跳转
router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置
接收参数
<li>消息id:{{$route.params.id}}li>
<li>消息标题:{{$route.params.title}}li>
作用:让路由组件更方便的收到参数
// 第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
// props:{a:900}
// 第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
// props:true
// 第三种写法:props值为函数
props($route){
return{
id:$route.query.id,
title:$route.query.title
}
}
props({query}){
return{
id:query.id,
title:query.title
}
}
接收参数
<li>消息id:{{id}}</li>
<li>消息标题:{{title}}</li>
<script>
export default {
......
props:['id','title']
}
</script>
的replace属性push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push
replace
模式:News
作用:不借助
实现路由跳转,让路由跳转更加灵活
具体编码
this.$router.push({
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
}),
this.$router.replace({
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
})
this.$router.back() //前进
this.$router.forward() //后退
this.$router.go(2) //也可前进也可后退
作用:让不展示的路由组件保持挂载,不被销毁
具体编码
activated
路由组件被激活时触发deactivated
路由组件失活时触发作用:对路由进行权限控制
分类:全局守卫、独享守卫、组件内守卫
全局守卫:
//全局前置路由守卫——初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
console.log('前置路由守卫',to,from)
if(to.meta.isAuth){//判断是否需要判断权限
if(localStorage.getItem('name')==='admin'){
next()
}else{
alert('无权限查看!')
}
}else{
next()
}
})
//全局后置路由守卫——初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
console.log('后置路由守卫',to,from)
document.title = to.meta.title || '管理系统'
})
独享守卫:(只有beforeEnter,没有afterEnter)
//独享路由守卫
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){//判断是否需要判断权限
if(localStorage.getItem('name')==='admin'){
next()
}else{
alert('无权限查看!')
}
}else{
next()
}
}
组件内守卫:
//通过路由规则,进入该组件时被调用
beforeRouteEnter(to, from, next){
},
//通过路由规则,离开该组件时被调用
beforeRouteLeave(to, from, next){
}