> 文档中心 > Vue2.0笔记(B站天禹老师)

Vue2.0笔记(B站天禹老师)


第一章 Vue核心

一、认识Vue

<html><head><meta charset="UTF-8" /><title>初识Vue</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="demo"><h1>Hello,{{name.toUpperCase()}},{{address}}</h1></div><script type="text/javascript" >Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。//创建Vue实例new Vue({el:'#demo', //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。data:{ //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。name:'atguigu',address:'北京'}});</script></body></html>

二、Vue模板语法

<html><head><meta charset="UTF-8" /><title>模板语法</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h1>插值语法</h1><h3>你好,{{name}}</h3><hr/><h1>指令语法</h1><a v-bind:href="school.url.toUpperCase()" x="hello">点我去{{school.name}}学习1</a><a :href="school.url" x="hello">点我去{{school.name}}学习2</a></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'jack',school:{name:'尚硅谷',url:'http://www.atguigu.com',}}});</script></html>

三、数据绑定

<html><head><meta charset="UTF-8" /><title>数据绑定</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><!-- 单向数据绑定:
双向数据绑定:
-->
单向数据绑定:<input type="text" :value="name"><br/>双向数据绑定:<input type="text" v-model="name"><br/><!--

你好啊

-->
</div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷'}});</script></html>

四、el与data的两种写法

<html><head><meta charset="UTF-8" /><title>el与data的两种写法</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h1>你好,{{name}}</h1></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。//el的两种写法/* const v = new Vue({//el:'#root', //第一种写法data:{name:'尚硅谷'}})console.log(v)v.$mount('#root') //第二种写法 *///data的两种写法new Vue({el:'#root',//data的第一种写法:对象式/* data:{name:'尚硅谷'} *///data的第二种写法:函数式data(){console.log('@@@',this) //此处的this是Vue实例对象return{name:'尚硅谷'}}})</script></html>

五、MVVM模型

<html><head><meta charset="UTF-8" /><title>理解MVVM</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h1>学校名称:{{name}}</h1><h1>学校地址:{{address}}</h1><!-- 

测试一下1:{{1+1}}

测试一下2:{{$options}}

测试一下3:{{$emit}}

测试一下4:{{_c}}

-->
</div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',address:'北京',}})console.log(vm);</script></html>

六、数据代理

1.回顾Object.defineProperty方法

<html><head><meta charset="UTF-8" /><title>回顾Object.defineproperty方法</title></head><body><script type="text/javascript" >let number = 18let person = {name:'张三',sex:'男',}Object.defineProperty(person,'age',{// value:18,// enumerable:true, //控制属性是否可以枚举,默认值是false// writable:true, //控制属性是否可以被修改,默认值是false// configurable:true //控制属性是否可以被删除,默认值是false//当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值get(){console.log('有人读取age属性了')return number},//当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值set(value){console.log('有人修改了age属性,且值是',value)number = value}})// console.log(Object.keys(person))console.log(person);</script></body></html>

2.何为数据代理

<html><head><meta charset="UTF-8" /><title>何为数据代理</title></head><body><script type="text/javascript" >let obj = {x:100}let obj2 = {y:200}Object.defineProperty(obj2,'x',{get(){return obj.x},set(value){obj.x = value}});</script></body></html>

3.Vue中的数据代理

<html><head><meta charset="UTF-8" /><title>Vue中的数据代理</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',address:'宏福科技园'}});</script></html>

原理:利用Object.defineProperty
在这里插入图片描述

七、事件处理

1.事件的基本使用

<html><head><meta charset="UTF-8" /><title>事件的基本使用</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>欢迎来到{{name}}学习</h2><!--  --><button @click="showInfo1">点我提示信息1(不传参)</button><button @click="showInfo2($event,66)">点我提示信息2(传参)</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',},methods:{showInfo1(event){// console.log(event.target.innerText)// console.log(this) //此处的this是vmalert('同学你好!')},showInfo2(event,number){console.log(event,number)// console.log(event.target.innerText)// console.log(this) //此处的this是vmalert('同学你好!!')}}});</script></html>

2.事件修饰符

<html><head><meta charset="UTF-8" /><title>事件修饰符</title><script type="text/javascript" src="../js/vue.js"></script><style>*{margin-top: 20px;}.demo1{height: 50px;background-color: skyblue;}.box1{padding: 5px;background-color: skyblue;}.box2{padding: 5px;background-color: orange;}.list{width: 200px;height: 200px;background-color: peru;overflow: auto;}li{height: 100px;}</style></head><body><div id="root"><h2>欢迎来到{{name}}学习</h2><a href="http://www.atguigu.com" @click.prevent="showInfo">点我提示信息</a><div class="demo1" @click="showInfo"><button @click.stop="showInfo">点我提示信息</button><!-- 点我提示信息 --></div><button @click.once="showInfo">点我提示信息</button><div class="box1" @click.capture="showMsg(1)">div1<div class="box2" @click="showMsg(2)">div2</div></div><div class="demo1" @click.self="showInfo"><button @click="showInfo">点我提示信息</button></div><ul @wheel.passive="demo" class="list"><li>1</li><li>2</li><li>3</li><li>4</li></ul></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷'},methods:{showInfo(e){alert('同学你好!')// console.log(e.target)},showMsg(msg){console.log(msg)},demo(){for (let i = 0; i < 1000; i++) {console.log('#')}console.log('累坏了')}}});</script></html>

3.键盘事件

<html><head><meta charset="UTF-8" /><title>键盘事件</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>欢迎来到{{name}}学习</h2><input type="text" placeholder="按下回车提示输入" @keydown.huiche="showInfo"></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。Vue.config.keyCodes.huiche = 13 //定义了一个别名按键new Vue({el:'#root',data:{name:'尚硅谷'},methods: {showInfo(e){// console.log(e.key,e.keyCode)console.log(e.target.value)}},});</script></html>

八、computed计算属性

1.姓名案例_插值语法实现

<html><head><meta charset="UTF-8" /><title>姓名案例_插值语法实现</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{firstName}}-{{lastName}}</span></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{firstName:'张',lastName:'三'}});</script></html>

2.姓名案例_methods实现

<html><head><meta charset="UTF-8" /><title>姓名案例_methods实现</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{fullName()}}</span></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{firstName:'张',lastName:'三'},methods: {fullName(){console.log('@---fullName')return this.firstName + '-' + this.lastName}},});</script></html>

3.姓名案例_计算属性实现

<html><head><meta charset="UTF-8" /><title>姓名案例_计算属性实现</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>测试:<input type="text" v-model="x"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/><!-- 全名:{{fullName}} 

全名:{{fullName}}

全名:{{fullName}} -->
</div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',x:'你好'},methods: {demo(){}},computed:{fullName:{//get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值//get什么时候调用?1.初次读取fullName时。2.所依赖的数据发生变化时。get(){console.log('get被调用了')// console.log(this) //此处的this是vmreturn this.firstName + '-' + this.lastName},//set什么时候调用? 当fullName被修改时。set(value){console.log('set',value)const arr = value.split('-')this.firstName = arr[0]this.lastName = arr[1]}}}});</script></html>

4.姓名案例_计算属性简写

<html><head><meta charset="UTF-8" /><title>姓名案例_计算属性实现</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',},computed:{//完整写法/* fullName:{get(){console.log('get被调用了')return this.firstName + '-' + this.lastName},set(value){console.log('set',value)const arr = value.split('-')this.firstName = arr[0]this.lastName = arr[1]}} *///简写fullName(){console.log('get被调用了')return this.firstName + '-' + this.lastName}}});</script></html>

九、watch监视属性

1.天气案例_监视属性

<html><head><meta charset="UTF-8" /><title>天气案例_监视属性</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>今天天气很{{info}}</h2><button @click="changeWeather">切换天气</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{isHot:true,},computed:{info(){return this.isHot ? '炎热' : '凉爽'}},methods: {changeWeather(){this.isHot = !this.isHot}},watch:{isHot:{immediate:true, //初始化时让handler调用一下//handler什么时候调用?当isHot发生改变时。handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}}} });// vm.$watch('isHot',{// immediate:true, //初始化时让handler调用一下// //handler什么时候调用?当isHot发生改变时。// handler(newValue,oldValue){// console.log('isHot被修改了',newValue,oldValue)// }// });</script></html>

2.天气案例_深度监视

<html><head><meta charset="UTF-8" /><title>天气案例_深度监视</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>今天天气很{{info}}</h2><button @click="changeWeather">切换天气</button><hr/><h3>a的值是:{{numbers.a}}</h3><button @click="numbers.a++">点我让a+1</button><h3>b的值是:{{numbers.b}}</h3><button @click="numbers.b++">点我让b+1</button><button @click="numbers = {a:666,b:888}">彻底替换掉numbers</button>{{numbers.c.d.e}}</div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{isHot:true,numbers:{a:1,b:1,c:{d:{e:100}}}},computed:{info(){return this.isHot ? '炎热' : '凉爽'}},methods: {changeWeather(){this.isHot = !this.isHot}},watch:{isHot:{// immediate:true, //初始化时让handler调用一下//handler什么时候调用?当isHot发生改变时。handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}},//监视多级结构中某个属性的变化/* 'numbers.a':{handler(){console.log('a被改变了')}} *///监视多级结构中所有属性的变化numbers:{deep:true,handler(){console.log('numbers改变了')}}}});</script></html>

3.天气案例_监视属性_简写

<html><head><meta charset="UTF-8" /><title>天气案例_监视属性_简写</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>今天天气很{{info}}</h2><button @click="changeWeather">切换天气</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{isHot:true,},computed:{info(){return this.isHot ? '炎热' : '凉爽'}},methods: {changeWeather(){this.isHot = !this.isHot}},watch:{//正常写法/* isHot:{// immediate:true, //初始化时让handler调用一下// deep:true,//深度监视handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}}, *///简写isHot(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue);}}});//正常写法/* vm.$watch('isHot',{immediate:true, //初始化时让handler调用一下deep:true,//深度监视handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}}) *///简写/* vm.$watch('isHot',(newValue,oldValue)=>{console.log('isHot被修改了',newValue,oldValue,this)}) */</script></html>

4.姓名案例_watch实现

<html><head><meta charset="UTF-8" /><title>姓名案例_watch实现</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',fullName:'张-三'},watch:{firstName(val){setTimeout(()=>{console.log(this)this.fullName = val + '-' + this.lastName},1000);},lastName(val){this.fullName = this.firstName + '-' + val}}});</script></html>

十、绑定样式

<html><head><meta charset="UTF-8" /><title>绑定样式</title><style>.basic{width: 400px;height: 100px;border: 1px solid black;}.happy{border: 4px solid red;;background-color: rgba(255, 255, 0, 0.644);background: linear-gradient(30deg,yellow,pink,orange,yellow);}.sad{border: 4px dashed rgb(2, 197, 2);background-color: gray;}.normal{background-color: skyblue;}.atguigu1{background-color: yellowgreen;}.atguigu2{font-size: 30px;text-shadow:2px 2px 10px red;}.atguigu3{border-radius: 20px;}</style><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><div class="basic" :class="mood" @click="changeMood">{{name}}</div> <br/><br/><div class="basic" :class="classArr">{{name}}</div> <br/><br/><div class="basic" :class="classObj">{{name}}</div> <br/><br/><div class="basic" :style="styleObj">{{name}}</div> <br/><br/><div class="basic" :style="styleArr">{{name}}</div></div></body><script type="text/javascript">Vue.config.productionTip = falseconst vm = new Vue({el:'#root',data:{name:'尚硅谷',mood:'normal',classArr:['atguigu1','atguigu2','atguigu3'],classObj:{atguigu1:false,atguigu2:false,},styleObj:{fontSize: '40px',color:'red',},styleObj2:{backgroundColor:'orange'},styleArr:[{fontSize: '40px',color:'blue',},{backgroundColor:'gray'}]},methods: {changeMood(){const arr = ['happy','sad','normal']const index = Math.floor(Math.random()*3)this.mood = arr[index]}},});</script></html>

十一、条件渲染

<html><head><meta charset="UTF-8" /><title>条件渲染</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>当前的n值是:{{n}}</h2><button @click="n++">点我n+1</button><!-- 

欢迎来到{{name}}

-->
<!--

欢迎来到{{name}}

-->
<!--

欢迎来到{{name}}

-->
<!--

欢迎来到{{name}}

-->
<!--
Angular
React
Vue
哈哈
-->
<template v-if="n === 1"><h2>你好</h2><h2>尚硅谷</h2><h2>北京</h2></template></div></body><script type="text/javascript">Vue.config.productionTip = falseconst vm = new Vue({el:'#root',data:{name:'尚硅谷',n:0}});</script></html>

十二、列表渲染

1.基本列表

<html><head><meta charset="UTF-8" /><title>基本列表</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>人员列表(遍历数组)</h2><ul><li v-for="(p,index) of persons" :key="index">{{p.name}}-{{p.age}}</li></ul><h2>汽车信息(遍历对象)</h2><ul><li v-for="(value,k) of car" :key="k">{{k}}-{{value}}</li></ul><h2>测试遍历字符串(用得少)</h2><ul><li v-for="(char,index) of str" :key="index">{{char}}-{{index}}</li></ul><h2>测试遍历指定次数(用得少)</h2><ul><li v-for="(number,index) of 5" :key="index">{{index}}-{{number}}</li></ul></div><script type="text/javascript">Vue.config.productionTip = falsenew Vue({el:'#root',data:{persons:[{id:'001',name:'张三',age:18},{id:'002',name:'李四',age:19},{id:'003',name:'王五',age:20}],car:{name:'奥迪A8',price:'70万',color:'黑色'},str:'hello'}});</script></html>

2.key的原理

<html><head><meta charset="UTF-8" /><title>key的原理</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>人员列表(遍历数组)</h2><button @click.once="add">添加一个老刘</button><ul><li v-for="(p,index) of persons" :key="index">{{p.name}}-{{p.age}}<input type="text"></li></ul></div><script type="text/javascript">Vue.config.productionTip = falsenew Vue({el:'#root',data:{persons:[{id:'001',name:'张三',age:18},{id:'002',name:'李四',age:19},{id:'003',name:'王五',age:20}]},methods: {add(){const p = {id:'004',name:'老刘',age:40}this.persons.unshift(p)}},});</script></html>

用index作为key(可能会出现问题):
在这里插入图片描述
用id作为key:
在这里插入图片描述

3.列表渲染

<html><head><meta charset="UTF-8" /><title>列表过滤</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>人员列表</h2><input type="text" placeholder="请输入名字" v-model="keyWord"><ul><li v-for="(p,index) of filPerons" :key="index">{{p.name}}-{{p.age}}-{{p.sex}}</li></ul></div><script type="text/javascript">Vue.config.productionTip = false//用watch实现//#region /* new Vue({el:'#root',data:{keyWord:'',persons:[{id:'001',name:'马冬梅',age:19,sex:'女'},{id:'002',name:'周冬雨',age:20,sex:'女'},{id:'003',name:'周杰伦',age:21,sex:'男'},{id:'004',name:'温兆伦',age:22,sex:'男'}],filPerons:[]},watch:{keyWord:{immediate:true,handler(val){this.filPerons = this.persons.filter((p)=>{return p.name.indexOf(val) !== -1})}}}}) *///#endregion//用computed实现new Vue({el:'#root',data:{keyWord:'',persons:[{id:'001',name:'马冬梅',age:19,sex:'女'},{id:'002',name:'周冬雨',age:20,sex:'女'},{id:'003',name:'周杰伦',age:21,sex:'男'},{id:'004',name:'温兆伦',age:22,sex:'男'}]},computed:{filPerons(){return this.persons.filter((p)=>{return p.name.indexOf(this.keyWord) !== -1})}}}); </script></html>

4.列表排序

<html><head><meta charset="UTF-8" /><title>列表排序</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>人员列表</h2><input type="text" placeholder="请输入名字" v-model="keyWord"><button @click="sortType = 2">年龄升序</button><button @click="sortType = 1">年龄降序</button><button @click="sortType = 0">原顺序</button><ul><li v-for="(p,index) of filPerons" :key="p.id">{{p.name}}-{{p.age}}-{{p.sex}}<input type="text"></li></ul></div><script type="text/javascript">Vue.config.productionTip = falsenew Vue({el:'#root',data:{keyWord:'',sortType:0, //0原顺序 1降序 2升序persons:[{id:'001',name:'马冬梅',age:30,sex:'女'},{id:'002',name:'周冬雨',age:31,sex:'女'},{id:'003',name:'周杰伦',age:18,sex:'男'},{id:'004',name:'温兆伦',age:19,sex:'男'}]},computed:{filPerons(){const arr = this.persons.filter((p)=>{return p.name.indexOf(this.keyWord) !== -1})//判断一下是否需要排序if(this.sortType){arr.sort((p1,p2)=>{return this.sortType === 1 ? p2.age-p1.age : p1.age-p2.age})}return arr}}});</script></html>

5.更新时的一个问题

<html><head><meta charset="UTF-8" /><title>更新时的一个问题</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>人员列表</h2><button @click="updateMei">更新马冬梅的信息</button><ul><li v-for="(p,index) of persons" :key="p.id">{{p.name}}-{{p.age}}-{{p.sex}}</li></ul></div><script type="text/javascript">Vue.config.productionTip = falseconst vm = new Vue({el:'#root',data:{persons:[{id:'001',name:'马冬梅',age:30,sex:'女'},{id:'002',name:'周冬雨',age:31,sex:'女'},{id:'003',name:'周杰伦',age:18,sex:'男'},{id:'004',name:'温兆伦',age:19,sex:'男'}]},methods: {updateMei(){// this.persons[0].name = '马老师' //奏效// this.persons[0].age = 50 //奏效// this.persons[0].sex = '男' //奏效// this.persons[0] = {id:'001',name:'马老师',age:50,sex:'男'} //不奏效this.persons.splice(0,1,{id:'001',name:'马老师',age:50,sex:'男'})}}}); </script></html>

6.Vue监测数据改变的原理

<html><head><meta charset="UTF-8" /><title>Vue监测数据改变的原理</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',address:'北京',student:{name:'tom',age:{rAge:40,sAge:29,},friends:[{name:'jerry',age:35}]}}});</script></html>

7.模拟一个数据监测

<html><head><meta charset="UTF-8" /><title>Document</title></head><body><script type="text/javascript" >let data = {name:'尚硅谷',address:'北京',}//创建一个监视的实例对象,用于监视data中属性的变化const obs = new Observer(data)console.log(obs)//准备一个vm实例对象let vm = {}vm._data = data = obsfunction Observer(obj){//汇总对象中所有的属性形成一个数组const keys = Object.keys(obj)//遍历keys.forEach((k)=>{Object.defineProperty(this,k,{get(){return obj[k]},set(val){console.log(`${k}被改了,我要去解析模板,生成虚拟DOM.....我要开始忙了`)obj[k] = val}})})}</script></body></html>

8.Vue.set的使用

<html><head><meta charset="UTF-8" /><title>Vue监测数据改变的原理</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h1>学校信息</h1><h2>学校名称:{{school.name}}</h2><h2>学校地址:{{school.address}}</h2><h2>校长是:{{school.leader}}</h2><hr/><h1>学生信息</h1><button @click="addSex">添加一个性别属性,默认值是男</button><h2>姓名:{{student.name}}</h2><h2 v-if="student.sex">性别:{{student.sex}}</h2><h2>年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2><h2>朋友们</h2><ul><li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li></ul></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{school:{name:'尚硅谷',address:'北京',},student:{name:'tom',age:{rAge:40,sAge:29,},friends:[{name:'jerry',age:35},{name:'tony',age:36}]}},methods: {addSex(){// Vue.set(this.student,'sex','男')this.$set(this.student,'sex','男')}}});</script></html>

9.Vue监测数据改变的原理_数组

<html><head><meta charset="UTF-8" /><title>Vue监测数据改变的原理_数组</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h1>学校信息</h1><h2>学校名称:{{school.name}}</h2><h2>学校地址:{{school.address}}</h2><h2>校长是:{{school.leader}}</h2><hr/><h1>学生信息</h1><button @click="addSex">添加一个性别属性,默认值是男</button><h2>姓名:{{student.name}}</h2><h2 v-if="student.sex">性别:{{student.sex}}</h2><h2>年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2><h2>爱好</h2><ul><li v-for="(h,index) in student.hobby" :key="index">{{h}}</li></ul><h2>朋友们</h2><ul><li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li></ul></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{school:{name:'尚硅谷',address:'北京',},student:{name:'tom',age:{rAge:40,sAge:29,},hobby:['抽烟','喝酒','烫头'],friends:[{name:'jerry',age:35},{name:'tony',age:36}]}},methods: {addSex(){// Vue.set(this.student,'sex','男')this.$set(this.student,'sex','男')}}});</script></html>

在这里插入图片描述

10.总结Vue数据监测

<html><head><meta charset="UTF-8" /><title>总结数据监视</title><style>button{margin-top: 10px;}</style><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h1>学生信息</h1><button @click="student.age++">年龄+1岁</button> <br/><button @click="addSex">添加性别属性,默认值:男</button> <br/><button @click="student.sex = '未知' ">修改性别</button> <br/><button @click="addFriend">在列表首位添加一个朋友</button> <br/><button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button> <br/><button @click="addHobby">添加一个爱好</button> <br/><button @click="updateHobby">修改第一个爱好为:开车</button> <br/><button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br/><h3>姓名:{{student.name}}</h3><h3>年龄:{{student.age}}</h3><h3 v-if="student.sex">性别:{{student.sex}}</h3><h3>爱好:</h3><ul><li v-for="(h,index) in student.hobby" :key="index">{{h}}</li></ul><h3>朋友们:</h3><ul><li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li></ul></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{student:{name:'tom',age:18,hobby:['抽烟','喝酒','烫头'],friends:[{name:'jerry',age:35},{name:'tony',age:36}]}},methods: {addSex(){// Vue.set(this.student,'sex','男')this.$set(this.student,'sex','男')},addFriend(){this.student.friends.unshift({name:'jack',age:70})},updateFirstFriendName(){this.student.friends[0].name = '张三'},addHobby(){this.student.hobby.push('学习')},updateHobby(){// this.student.hobby.splice(0,1,'开车')// Vue.set(this.student.hobby,0,'开车')this.$set(this.student.hobby,0,'开车')},removeSmoke(){this.student.hobby = this.student.hobby.filter((h)=>{return h !== '抽烟'})}}});</script></html>

十三、收集表单数据

<html><head><meta charset="UTF-8" /><title>收集表单数据</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 收集表单数据:若:,则v-model收集的是value值,用户输入的就是value值。若:,则v-model收集的是value值,且要给标签配置value值。若:1.没有配置input的value属性,那么收集的就是checked(勾选 or 未勾选,是布尔值)2.配置input的value属性:(1)v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)(2)v-model的初始值是数组,那么收集的的就是value组成的数组备注:v-model的三个修饰符:lazy:失去焦点再收集数据number:输入字符串转为有效的数字trim:输入首尾空格过滤--><div id="root"><form @submit.prevent="demo">账号:<input type="text" v-model.trim="userInfo.account"> <br/><br/>密码:<input type="password" v-model="userInfo.password"> <br/><br/>年龄:<input type="number" v-model.number="userInfo.age"> <br/><br/>性别:男<input type="radio" name="sex" v-model="userInfo.sex" value="male"><input type="radio" name="sex" v-model="userInfo.sex" value="female"> <br/><br/>爱好:学习<input type="checkbox" v-model="userInfo.hobby" value="study">打游戏<input type="checkbox" v-model="userInfo.hobby" value="game">吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat"><br/><br/>所属校区<select v-model="userInfo.city"><option value="">请选择校区</option><option value="beijing">北京</option><option value="shanghai">上海</option><option value="shenzhen">深圳</option><option value="wuhan">武汉</option></select><br/><br/>其他信息:<textarea v-model.lazy="userInfo.other"></textarea> <br/><br/><input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="http://www.atguigu.com">《用户协议》</a><button>提交</button></form></div></body><script type="text/javascript">Vue.config.productionTip = falsenew Vue({el:'#root',data:{userInfo:{account:'',password:'',age:18,sex:'female',hobby:[],city:'beijing',other:'',agree:''}},methods: {demo(){console.log(JSON.stringify(this.userInfo))}}});</script></html>

十四、过滤器

<html><head><meta charset="UTF-8" /><title>过滤器</title><script type="text/javascript" src="../js/vue.js"></script><script type="text/javascript" src="../js/dayjs.min.js"></script></head><body><div id="root"><h2>显示格式化后的时间</h2><h3>现在是:{{fmtTime}}</h3><h3>现在是:{{getFmtTime()}}</h3><h3>现在是:{{time | timeFormater}}</h3><h3>现在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3><h3 :x="msg | mySlice">尚硅谷</h3></div><div id="root2"><h2>{{msg | mySlice}}</h2></div></body><script type="text/javascript">Vue.config.productionTip = false//全局过滤器Vue.filter('mySlice',function(value){return value.slice(0,4)})new Vue({el:'#root',data:{time:1621561377603, //时间戳msg:'你好,尚硅谷'},computed: {fmtTime(){return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')}},methods: {getFmtTime(){return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')}},//局部过滤器filters:{timeFormater(value,str='YYYY年MM月DD日 HH:mm:ss'){// console.log('@',value)return dayjs(value).format(str)}}})new Vue({el:'#root2',data:{msg:'hello,atguigu!'}});</script></html>

十五、Vue指令

在这里插入图片描述

1.v-text_指令

<html><head><meta charset="UTF-8" /><title>v-text指令</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><div>你好,{{name}}</div><div v-text="name"></div><div v-text="str"></div></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷',str:'

你好啊!

'
}})
</script></html>

2.v-html_指令

<html><head><meta charset="UTF-8" /><title>v-html指令</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><div>你好,{{name}}</div><div v-html="str"></div><div v-html="str2"></div></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷',str:'

你好啊!

'
,str2:'兄弟我找到你想要的资源了,快来!',}})
</script></html>

3.v-cloak_指令

<html><head><meta charset="UTF-8" /><title>v-cloak指令</title><style>[v-cloak]{display:none;}</style><!--  --></head><body><div id="root"><h2 v-cloak>{{name}}</h2></div><script type="text/javascript" src="http://localhost:8080/resource/5s/vue.js"></script></body><script type="text/javascript">console.log(1)Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷'}})</script></html>

4.v-once_指令

<html><head><meta charset="UTF-8" /><title>v-once指令</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2 v-once>初始化的n值是:{{n}}</h2><h2>当前的n值是:{{n}}</h2><button @click="n++">点我n+1</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{n:1}})</script></html>

5.v-pre_指令

<html><head><meta charset="UTF-8" /><title>v-pre指令</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2 v-pre>Vue其实很简单</h2><h2 >当前的n值是:{{n}}</h2><button @click="n++">点我n+1</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{n:1}})</script></html>

6.自定义指令

<html><head><meta charset="UTF-8" /><title>自定义指令</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2>{{name}}</h2><h2>当前的n值是:<span v-text="n"></span> </h2><!-- 

放大10倍后的n值是:

-->
<h2>放大10倍后的n值是:<span v-big="n"></span> </h2><button @click="n++">点我n+1</button><hr/><input type="text" v-fbind:value="n"></div></body><script type="text/javascript">Vue.config.productionTip = false//定义全局指令/* Vue.directive('fbind',{//指令与元素成功绑定时(一上来)bind(element,binding){element.value = binding.value},//指令所在元素被插入页面时inserted(element,binding){element.focus()},//指令所在的模板被重新解析时update(element,binding){element.value = binding.value}}) */new Vue({el:'#root',data:{name:'尚硅谷',n:1},directives:{//big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。/* 'big-number'(element,binding){// console.log('big')element.innerText = binding.value * 10}, */big(element,binding){console.log('big',this) //注意此处的this是window// console.log('big')element.innerText = binding.value * 10},fbind:{//指令与元素成功绑定时(一上来)bind(element,binding){element.value = binding.value},//指令所在元素被插入页面时inserted(element,binding){element.focus()},//指令所在的模板被重新解析时update(element,binding){element.value = binding.value}}}})</script></html>

十六、生命周期

1.引出生命周期

<html><head><meta charset="UTF-8" /><title>引出生命周期</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2 v-if="a">你好啊</h2><h2 :style="{opacity}">欢迎学习Vue</h2></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。 new Vue({el:'#root',data:{a:false,opacity:1},methods: {},//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mountedmounted(){console.log('mounted',this)setInterval(() => {this.opacity -= 0.01if(this.opacity <= 0) this.opacity = 1},16)},})//通过外部的定时器实现(不推荐)/* setInterval(() => {vm.opacity -= 0.01if(vm.opacity <= 0) vm.opacity = 1},16) */</script></html>

2.分析生命周期

<html><head><meta charset="UTF-8" /><title>分析生命周期</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root" :x="n"><h2 v-text="n"></h2><h2>当前的n值是:{{n}}</h2><button @click="add">点我n+1</button><button @click="bye">点我销毁vm</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',// template:`// 
//

当前的n值是:{{n}}

// //
// `,data:{n:1},methods: {add(){console.log('add')this.n++},bye(){console.log('bye')this.$destroy()}},watch:{n(){console.log('n变了')}},beforeCreate() {console.log('beforeCreate')},created() {console.log('created')},beforeMount() {console.log('beforeMount')},mounted() {console.log('mounted')},beforeUpdate() {console.log('beforeUpdate')},updated() {console.log('updated')},beforeDestroy() {console.log('beforeDestroy')},destroyed() {console.log('destroyed')},})
</script></html>

在这里插入图片描述
在这里插入图片描述

3.总结生命周期

<html><head><meta charset="UTF-8" /><title>引出生命周期</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><h2 :style="{opacity}">欢迎学习Vue</h2><button @click="opacity = 1">透明度设置为1</button><button @click="stop">点我停止变换</button></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。 new Vue({el:'#root',data:{opacity:1},methods: {stop(){this.$destroy()}},//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mountedmounted(){console.log('mounted',this)this.timer = setInterval(() => {console.log('setInterval')this.opacity -= 0.01if(this.opacity <= 0) this.opacity = 1},16)},beforeDestroy() {clearInterval(this.timer)console.log('vm即将驾鹤西游了')},})</script></html>

第二章 Vue组件化编程

一、 模块与组件、模块化与组件化

1.模块

  • 理解: 向外提供特定功能的js程序, 一般就是一个js文件
  • 为什么: js文件很多很复杂
  • 作用: 复用js, 简化js的编写, 提高js运行效率

2.组件

  • 理解: 用来实现局部(特定)功能效果的代码集合(html/css/js/image……)
  • 为什么: 一个界面的功能很复杂
  • 作用: 复用编码, 简化项目编码, 提高运行效率

3.模块化

当应用中的js都以模块来编写的, 那这个应用就是一个模块化的应用。

4.组件化

当应用中的功能都是多组件的方式来编写的, 那这个应用就是一个组件化的应用,。

二、非单文件组件

  1. 模板编写没有提示
  2. 没有构建过程, 无法将ES6转换成ES5
  3. 不支持组件的CSS
  4. 真正开发中几乎不用

1.基本使用

<html><head><meta charset="UTF-8" /><title>基本使用</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- Vue中使用组件的三大步骤:一、定义组件(创建组件)二、注册组件三、使用组件(写组件标签)一、如何定义一个组件?使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别;区别如下:1.el不要写,为什么? ——— 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。2.data必须写成函数,为什么? ———— 避免组件被复用时,数据存在引用关系。备注:使用template可以配置组件结构。二、如何注册组件?1.局部注册:靠new Vue的时候传入components选项2.全局注册:靠Vue.component('组件名',组件)三、编写组件标签:--><div id="root"><hello></hello><hr><h1>{{msg}}</h1><hr><school></school><hr><student></student></div><div id="root2"><hello></hello></div></body><script type="text/javascript">Vue.config.productionTip = false//第一步:创建school组件const school = Vue.extend({template:`

学校名称:{{schoolName}}

学校地址:{{address}}

`
,// el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。data(){return {schoolName:'尚硅谷',address:'北京昌平'}},methods: {showName(){alert(this.schoolName)}},})//第一步:创建student组件const student = Vue.extend({template:`

学生姓名:{{studentName}}

学生年龄:{{age}}

`
,data(){return {studentName:'张三',age:18}}})//第一步:创建hello组件const hello = Vue.extend({template:`

你好啊!{{name}}

`
,data(){return {name:'Tom'}}})//第二步:全局注册组件Vue.component('hello',hello)//创建vmnew Vue({el:'#root',data:{msg:'你好啊!'},//第二步:注册组件(局部注册)components:{school,student}})new Vue({el:'#root2',})
</script></html>

2.几个注意点

<html><head><meta charset="UTF-8" /><title>几个注意点</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 几个注意点:1.关于组件名:一个单词组成:第一种写法(首字母小写):school第二种写法(首字母大写):School多个单词组成:第一种写法(kebab-case命名):my-school第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)备注:(1).组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行。(2).可以使用name配置项指定组件在开发者工具中呈现的名字。2.关于组件标签:第一种写法:第二种写法:备注:不用使用脚手架时,会导致后续组件不能渲染。3.一个简写方式:const school = Vue.extend(options) 可简写为:const school = options--><div id="root"><h1>{{msg}}</h1><school></school></div></body><script type="text/javascript">Vue.config.productionTip = false//定义组件const s = Vue.extend({name:'atguigu',template:`

学校名称:{{name}}

学校地址:{{address}}

`
,data(){return {name:'尚硅谷',address:'北京'}}})new Vue({el:'#root',data:{msg:'欢迎学习Vue!'},components:{school:s}})
</script></html>

3.组件的嵌套

<html><head><meta charset="UTF-8" /><title>组件的嵌套</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。//定义student组件const student = Vue.extend({name:'student',template:`

学生姓名:{{name}}

学生年龄:{{age}}

`
,data(){return {name:'尚硅谷',age:18}}})//定义school组件const school = Vue.extend({name:'school',template:`

学校名称:{{name}}

学校地址:{{address}}

`
,data(){return {name:'尚硅谷',address:'北京'}},//注册组件(局部)components:{student}})//定义hello组件const hello = Vue.extend({template:`

{{msg}}

`
,data(){return {msg:'欢迎来到尚硅谷学习!'}}})//定义app组件const app = Vue.extend({template:`
`
,components:{school,hello}})//创建vmnew Vue({template:'',el:'#root',//注册组件(局部)components:{app}})
</script></html>

4.VueComponent

<html><head><meta charset="UTF-8" /><title>VueComponent</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 关于VueComponent:1.school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。2.我们只需要写或,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的:new VueComponent(options)。3.特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent!!!!4.关于this指向:(1).组件配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】。(2).new Vue(options)配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】。5.VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象)。Vue的实例对象,以后简称vm。--><div id="root"><school></school><hello></hello></div></body><script type="text/javascript">Vue.config.productionTip = false//定义school组件const school = Vue.extend({name:'school',template:`

学校名称:{{name}}

学校地址:{{address}}

`
,data(){return {name:'尚硅谷',address:'北京'}},methods: {showName(){console.log('showName',this)}},})const test = Vue.extend({template:`atguigu`})//定义hello组件const hello = Vue.extend({template:`

{{msg}}

`
,data(){return {msg:'你好啊!'}},components:{test}})// console.log('@',school)// console.log('#',hello)//创建vmconst vm = new Vue({el:'#root',components:{school,hello}})
</script></html>

5.一个重要的内置关系

<html><head><meta charset="UTF-8" /><title>一个重要的内置关系</title><script type="text/javascript" src="../js/vue.js"></script></head><body><div id="root"><school></school></div></body><script type="text/javascript">Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。Vue.prototype.x = 99//定义school组件const school = Vue.extend({name:'school',template:`

学校名称:{{name}}

学校地址:{{address}}

`
,data(){return {name:'尚硅谷',address:'北京'}},methods: {showX(){console.log(this.x)}},})//创建一个vmconst vm = new Vue({el:'#root',data:{msg:'你好'},components:{school}})//定义一个构造函数/* function Demo(){this.a = 1this.b = 2}//创建一个Demo的实例对象const d = new Demo()console.log(Demo.prototype) //显示原型属性console.log(d.__proto__) //隐式原型属性console.log(Demo.prototype === d.__proto__)//程序员通过显示原型属性操作原型对象,追加一个x属性,值为99Demo.prototype.x = 99console.log('@',d) */
</script></html>

三、单文件组件

1.一个.vue文件的组成(3个部分)

(1)模板页面

<template>页面模板</template>

(2)JS模块对象

<script>export default {data() {return {}},methods: {},computed: {},components: {}}</script>

(3)样式

<style>样式定义</style>

2.基本使用

  1. 引入组件
  2. 映射成标签
  3. 使用组件标签

School.vue:

<template><div class="demo"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2><button @click="showName">点我提示学校名</button></div></template><script> export default {name:'School',data(){return {name:'尚硅谷',address:'北京昌平'}},methods: {showName(){alert(this.name)}},}</script><style>.demo{background-color: orange;}</style>

App.vue:

<template><div><School></School></div></template><script>//引入组件import School from './School.vue'export default {name:'App',components:{School}}</script>

main.js:

import App from './App.vue'new Vue({el:'#root',template:``,components:{App},})

index.html:

<html><head><meta charset="UTF-8" /><title>练习一下单文件组件的语法</title></head><body><div id="root"></div><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script><script type="text/javascript" src="./main.js"></script></body></html>

第三章 Vue脚手架

3.1 初始化脚手架

3.1.1 说明

  1. Vue脚手架是Vue官方提供的标准化开发工具(开发平台)。
  2. 最新的版本是4.x。
  3. 文档: https://cli.vuejs.org/zh/。

3.1.2 具体步骤

  • 第一步(仅第一次执行):全局安装@vue/cli。
    npm install -g @vue/cli
  • 第二步:切换到你要创建项目的目录,然后使用命令创建项目
    vue create xxxx
  • 第三步:启动项目
    npm run serve

备注:

  1. 如出现下载缓慢请配置npm淘宝镜像:
    npm config set registry https://registry.npm.taobao.org
  2. Vue脚手架隐藏了所有webpack相关的配置,若想查看具体的webpakc配置, 请执行:
    vue inspect > output.js

3.1.3 模板项目的结构

在这里插入图片描述

3.1.4 关于不同版本的Vue

  1. vue.js与vue.runtime.xxx.js的区别:
    1. vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
    2. vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。
  2. 因为vue.runtime.xxx.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容。

3.1.5 vue.config.js配置文件

  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
  2. 使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh

3.2 ref与props

3.2.1 ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:

      .....

    2. 获取:this.$refs.xxx

App.vue

<template><div><h1 v-text="msg" ref="title"></h1><button ref="btn" @click="showDOM">点我输出上方的DOM元素</button><School ref="sch"/></div></template><script>//引入School组件import School from './components/School'export default {name:'App',components:{School},data() {return {msg:'欢迎学习Vue!'}},methods: {showDOM(){console.log(this.$refs.title) //真实DOM元素console.log(this.$refs.btn) //真实DOM元素console.log(this.$refs.sch) //School组件的实例对象(vc)}},}</script>

3.2.2 props配置项

  1. 作用:用于父组件给子组件传递数据

  2. 读取方式一: 只指定名称
    props: ['name', 'age', 'setName']

  3. 读取方式二: 指定名称和类型

props: {name: String,age: Number,setNmae: Function}
  1. 读取方式三: 指定名称/类型/必要性/默认值
props: {name: {type: String, required: true, default:xxx},}

备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

App.vue:

<template><div><Student name="李四" sex="" :age="18"/></div></template><script>import Student from './components/Student'export default {name:'App',components:{Student}}</script>

Student.vue:

<template><div><h1>{{msg}}</h1><h2>学生姓名:{{name}}</h2><h2>学生性别:{{sex}}</h2><h2>学生年龄:{{myAge+1}}</h2><button @click="updateAge">尝试修改收到的年龄</button></div></template><script>export default {name:'Student',data() {console.log(this)return {msg:'我是一个尚硅谷的学生',myAge:this.age}},methods: {updateAge(){this.myAge++}},//简单声明接收// props:['name','age','sex'] //接收的同时对数据进行类型限制/* props:{name:String,age:Number,sex:String} *///接收的同时对数据:进行类型限制+默认值的指定+必要性的限制props:{name:{type:String, //name的类型是字符串required:true, //name是必要的},age:{type:Number,default:99 //默认值},sex:{type:String,required:true}}}</script>

3.3 mixin(混入)

  1. 功能:可以把多个组件共用的配置提取成一个混入对象.

  2. 使用方式

    第一步定义混合:

    {    data(){....},    methods:{....}    ....}

    第二步使用混入:

    ​ 全局混入:Vue.mixin(xxx)
    ​ 局部混入:mixins:['xxx']

简单理解mixin:用来抽离组件公共的逻辑,代码维护更加方便。

3.4 插件

  1. 功能:用于增强Vue

  2. 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。

  3. 定义插件:

    对象.install = function (Vue, options) {    // 1. 添加全局过滤器    Vue.filter(....)    // 2. 添加全局指令    Vue.directive(....)    // 3. 配置全局混入(合)    Vue.mixin(....)    // 4. 添加实例方法    Vue.prototype.$myMethod = function () {...}    Vue.prototype.$myProperty = xxxx}
  4. 使用插件:Vue.use()

【扩展】:scoped样式

  • 作用:让样式在局部生效,防止冲突。
  • 写法:

3.5 浏览器存储webStorage

  1. 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)

  2. 浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。

  3. 相关API:

    1. xxxxxStorage.setItem('key', 'value');
      该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。

    2. xxxxxStorage.getItem('person');

      ​ 该方法接受一个键名作为参数,返回键名对应的值。

    3. xxxxxStorage.removeItem('key');

      ​ 该方法接受一个键名作为参数,并把该键名从存储中删除。

    4. xxxxxStorage.clear()

      ​ 该方法会清空存储中的所有数据。

  4. 备注:

    1. SessionStorage存储的内容会随着浏览器窗口关闭而消失。
    2. LocalStorage存储的内容,需要手动清除才会消失。
    3. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
    4. JSON.parse(null)的结果依然是null。

3.6 组件的自定义事件

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。

  3. 绑定自定义事件:

    1. 第一种方式,在父组件中:

    2. 第二种方式,在父组件中:

      <Demo ref="demo"/>......mounted(){   this.$refs.xxx.$on('atguigu',this.test)}
    3. 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。

  4. 触发自定义事件:this.$emit('atguigu',数据)

  5. 解绑自定义事件this.$off('atguigu')

  6. 组件上也可以绑定原生DOM事件,需要使用native修饰符。

  7. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!

App.vue:

<template><div class="app"><h1>{{msg}},学生姓名是:{{studentName}}</h1><School :getSchoolName="getSchoolName"/><!--  --><Student ref="student" @click.native="show"/></div></template><script>import Student from './components/Student'import School from './components/School'export default {name:'App',components:{School,Student},data() {return {msg:'你好啊!',studentName:''}},methods: {getSchoolName(name){console.log('App收到了学校名:',name)},getStudentName(name,...params){console.log('App收到了学生名:',name,params)this.studentName = name},m1(){console.log('demo事件被触发了!')},show(){alert(123)}},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>

Student.vue:

<template><div class="student"><h2>学生姓名:{{name}}</h2><h2>学生性别:{{sex}}</h2><h2>当前求和为:{{number}}</h2><button @click="add">点我number++</button><button @click="sendStudentlName">把学生名给App</button><button @click="unbind">解绑atguigu事件</button><button @click="death">销毁当前Student组件的实例(vc)</button></div></template><script>export default {name:'Student',data() {return {name:'张三',sex:'男',number:0}},methods: {add(){console.log('add回调被调用了')this.number++},sendStudentlName(){//触发Student组件实例身上的atguigu事件this.$emit('atguigu',this.name,666,888,900)// this.$emit('demo')// this.$emit('click')},unbind(){this.$off('atguigu') //解绑一个自定义事件// this.$off(['atguigu','demo']) //解绑多个自定义事件// this.$off() //解绑所有的自定义事件},death(){this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。}},}</script><style lang="less" scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}</style>

Schoole.vue:

<template><div class="school"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2><button @click="sendSchoolName">把学校名给App</button></div></template><script>export default {name:'School',props:['getSchoolName'],data() {return {name:'尚硅谷',address:'北京',}},methods: {sendSchoolName(){this.getSchoolName(this.name)}},}</script><style scoped>.school{background-color: skyblue;padding: 5px;}</style>

3.7 全局事件总线

  1. 一种组件间通信的方式,适用于任意组件间通信

  2. 安装全局事件总线:

    ......beforeCreate() {Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm},    ......    })     ```
  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){  demo(data){......}}......mounted() {  this.$bus.$on('xxxx',this.demo)}
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

main.js:

//引入Vueimport Vue from 'vue'//引入Appimport App from './App.vue'//关闭Vue的生产提示Vue.config.productionTip = false//创建vmnew Vue({    el: '#app',    render: h => h(App),    beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线    },})

App.vue:

<template><div class="app"><h1>{{msg}}</h1><School/><Student/></div></template><script>import Student from './components/Student'import School from './components/School'export default {name:'App',components:{School,Student},data() {return {msg:'你好啊!',}}}</script><style scoped>.app{background-color: gray;padding: 5px;}</style>

School.vue:

<template><div class="school"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></template><script>export default {name:'School',data() {return {name:'尚硅谷',address:'北京',}},mounted() {// console.log('School',this)this.$bus.$on('hello',(data)=>{console.log('我是School组件,收到了数据',)})},beforeDestroy() {this.$bus.$off('hello')},}</script><style scoped>.school{background-color: skyblue;padding: 5px;}</style>

Student.vue:

<template><div class="student"><h2>学生姓名:{{name}}</h2><h2>学生性别:{{sex}}</h2><button @click="sendStudentName">把学生名给School组件</button></div></template><script>export default {name:'Student',data() {return {name:'张三',sex:'男',}},mounted() {// console.log('Student',this.x)},methods: {sendStudentName(){this.$bus.$emit('hello',this.name)}},}</script><style lang="less" scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}</style>

【总结】--------重点:

  • School组件和Student中的this.$bus都是基于VueComponent.prototype.__proto__ === Vue.prototype;这个内置关系,最终找到Vue原型身上的$bus方法,而在main.js中提前定义了Vue.prototype.$bus = this; $bus方法存储的是this,this即为vm实例对象,而vm的所属类Vue原型上有$on、$off、$emit等事件可供使用。
    Vue2.0笔记(B站天禹老师)

3.8 消息订阅与发布(pubsub)

  1. 一种组件间通信的方式,适用于任意组件间通信。【思想与全局事件总线很相似,用的较少】

  2. 使用步骤:

    1. 安装pubsub:npm i pubsub-js

    2. 引入: import pubsub from 'pubsub-js'

    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

      methods(){  demo(data){......}}......mounted() {  this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息}
    4. 提供数据:pubsub.publish('xxx',数据)

    5. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅。

School.vue:

<template><div class="school"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></template><script>import pubsub from 'pubsub-js'export default {name:'School',data() {return {name:'尚硅谷',address:'北京',}},mounted() {// console.log('School',this)/* this.$bus.$on('hello',(data)=>{console.log('我是School组件,收到了数据',data)}) */this.pubId = pubsub.subscribe('hello',(msgName,data)=>{console.log(this)// console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)})},beforeDestroy() {// this.$bus.$off('hello')pubsub.unsubscribe(this.pubId)},}</script><style scoped>.school{background-color: skyblue;padding: 5px;}</style>

Student.vue:

<template><div class="student"><h2>学生姓名:{{name}}</h2><h2>学生性别:{{sex}}</h2><button @click="sendStudentName">把学生名给School组件</button></div></template><script>import pubsub from 'pubsub-js'export default {name:'Student',data() {return {name:'张三',sex:'男',}},mounted() {// console.log('Student',this.x)},methods: {sendStudentName(){// this.$bus.$emit('hello',this.name)pubsub.publish('hello',666)}},}</script><style lang="less" scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}</style>

3.9 nextTick

  1. 语法:this.$nextTick(回调函数)
  2. 作用:在下一次 DOM 更新结束后执行其指定的回调。
  3. 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。

4.0 过渡与动画

  1. 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

  2. 写法:

  1. 准备好样式:

    • 元素进入的样式:
      1. v-enter:进入的起点
      2. v-enter-active:进入过程中
      3. v-enter-to:进入的终点
    • 元素离开的样式:
      1. v-leave:离开的起点
      2. v-leave-active:离开过程中
      3. v-leave-to:离开的终点
  2. 使用包裹要过度的元素,并配置name属性:

    你好啊!

  3. 备注:若有多个元素需要过度,则需要使用:,且每个元素都要指定key值。

Test1.vue:

<template><div><button @click="isShow = !isShow">显示/隐藏</button><transition name="hello" appear><h1 v-show="isShow">你好啊!</h1></transition></div></template><script>export default {name:'Test',data() {return {isShow:true}},}</script><style scoped>h1{background-color: orange;}.hello-enter-active{animation: atguigu 0.5s linear;}.hello-leave-active{animation: atguigu 0.5s linear reverse;}@keyframes atguigu {from{transform: translateX(-100%);}to{transform: translateX(0px);}}</style>

Test2.vue:

<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;}/* 进入的起点、离开的终点 */.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>

第四章 Vue中的ajax

4.1 vue脚手架配置代理

4.11 方法一

​ 在vue.config.js中添加如下配置:

devServer:{  proxy:"http://localhost:5000"}

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

4.12 方法二

​ 编写vue.config.js配置具体代理规则:

module.exports = {devServer: {      proxy: {      '/api1': {// 匹配所有以 '/api1'开头的请求路径 target: 'http://localhost:5000',// 代理目标的基础路径 changeOrigin: true, pathRewrite: {'^/api1': ''}      },      '/api2': {// 匹配所有以 '/api2'开头的请求路径 target: 'http://localhost:5001',// 代理目标的基础路径 changeOrigin: true, pathRewrite: {'^/api2': ''}      }    }  }}/*   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080   changeOrigin默认值为true*/

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

以上两个方法的举例:
App.vue:

<template><div><button @click="getStudents">获取学生信息</button><button @click="getCars">获取汽车信息</button></div></template><script>import axios from 'axios'export default {name:'App',methods: {getStudents(){axios.get('http://localhost:8080/students').then(response => {console.log('请求成功了',response.data)},error => {console.log('请求失败了',error.message)})},getCars(){axios.get('http://localhost:8080/demo/cars').then(response => {console.log('请求成功了',response.data)},error => {console.log('请求失败了',error.message)})}},}</script>

vue.config.js:

module.exports = {  pages: {    index: {      //入口      entry: 'src/main.js',    },  },lintOnSave:false, //关闭语法检查//开启代理服务器(方式一)/* devServer: {    proxy: 'http://localhost:5000'  }, *///开启代理服务器(方式二)devServer: {    proxy: {      '/atguigu': { target: 'http://localhost:5000',pathRewrite:{'^/atguigu':''}, // ws: true, //用于支持websocket // changeOrigin: true //用于控制请求头中的host值      },      '/demo': { target: 'http://localhost:5001',pathRewrite:{'^/demo':''}, // ws: true, //用于支持websocket // changeOrigin: true //用于控制请求头中的host值      }    }  }}

4.2 插槽

  1. 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件

  2. 分类:默认插槽、具名插槽、作用域插槽

  3. 使用方式:

    1. 默认插槽:

      父组件中: <Category>    <div>html结构1</div> </Category>子组件中: <template>     <div>  <slot>插槽默认内容...</slot>     </div> </template>
    2. 具名插槽:

      父组件中: <Category>     <template slot="center"><div>html结构1</div>     </template>     <template v-slot:footer> <div>html结构2</div>     </template> </Category>子组件中: <template>     <div>  <slot name="center">插槽默认内容...</slot> <slot name="footer">插槽默认内容...</slot>     </div> </template>
    3. 作用域插槽:

      1. 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      2. 具体编码:

        父组件中:<Category><template scope="scopeData"><ul><li v-for="g in scopeData.games" :key="g">{{g}}</li></ul></template></Category><Category><template slot-scope="scopeData"><h4 v-for="g in scopeData.games" :key="g">{{g}}</h4></template></Category>子组件中: <template>     <div>  <slot :games="games"></slot>     </div> </template> <script>     export default {  name:'Category',  props:['title'],  //数据在子组件自身  data() {      return {   games:['红色警戒','穿越火线','劲舞团','超级玛丽']      }  },     } </script>

第五章 Vuex

1.概念

​ 在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

2.何时使用?

​ 多个组件需要共享数据时

3.vuex工作原理图

【注】:action、mutations、state都是统一交给store管理的,图中省略了store。
在这里插入图片描述

4.搭建vuex环境

  1. 创建文件:src/store/index.js

    //引入Vue核心库import Vue from 'vue'//引入Vueximport Vuex from 'vuex'//应用Vuex插件//【注意】:必须先引入vuex,才能使用storeVue.use(Vuex) //准备actions对象——响应组件中用户的动作const actions = {}//准备mutations对象——修改state中的数据const mutations = {}//准备state对象——保存具体的数据const state = {}//创建并暴露storeexport default new Vuex.Store({actions,mutations,state})
  2. main.js中创建vm时传入store配置项

    ......//引入storeimport store from './store'......//创建vmnew Vue({el:'#app',render: h => h(App),store})

5.基本使用

  1. 初始化数据、配置actions、配置mutations,操作文件store.js

    //引入Vue核心库import Vue from 'vue'//引入Vueximport Vuex from 'vuex'//引用VuexVue.use(Vuex)const actions = {    //响应组件中加的动作jia(context,value){// console.log('actions中的jia被调用了',miniStore,value)context.commit('JIA',value)},}const mutations = {    //执行加JIA(state,value){// console.log('mutations中的JIA被调用了',state,value)state.sum += value}}//初始化数据const state = {   sum:0}//创建并暴露storeexport default new Vuex.Store({actions,mutations,state,})
  2. 组件中读取vuex中的数据:$store.state.sum

  3. 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)$store.commit('mutations中的方法名',数据)

    备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

6.getters的使用

  1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工。

  2. store.js中追加getters配置

    ......const getters = {bigSum(state){return state.sum * 10}}//创建并暴露storeexport default new Vuex.Store({......getters})
  3. 组件中读取数据:$store.getters.bigSum

7.四个map方法的使用

  1. mapState方法:用于帮助我们映射state中的数据为计算属性

    computed: {    //借助mapState生成计算属性:sum、school、subject(对象写法)     ...mapState({sum:'sum',school:'school',subject:'subject'}),      //借助mapState生成计算属性:sum、school、subject(数组写法)    ...mapState(['sum','school','subject']),},
  2. mapGetters方法:用于帮助我们映射getters中的数据为计算属性

    computed: {    //借助mapGetters生成计算属性:bigSum(对象写法)    ...mapGetters({bigSum:'bigSum'}),    //借助mapGetters生成计算属性:bigSum(数组写法)    ...mapGetters(['bigSum'])},
  3. mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

    methods:{    //靠mapActions生成:incrementOdd、incrementWait(对象形式)    ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})    //靠mapActions生成:incrementOdd、incrementWait(数组形式)    ...mapActions(['jiaOdd','jiaWait'])}
  4. mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数

    methods:{    //靠mapActions生成:increment、decrement(对象形式)    ...mapMutations({increment:'JIA',decrement:'JIAN'}), //靠mapMutations生成:JIA、JIAN(对象形式)    ...mapMutations(['JIA','JIAN']),}

备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

8.模块化+命名空间

  1. 目的:让代码更好维护,让多种数据分类更加明确。

  2. 修改store.js

    const countAbout = {  namespaced:true,//开启命名空间  state:{x:1},  mutations: { ... },  actions: { ... },  getters: {    bigSum(state){return state.sum * 10    }  }}const personAbout = {  namespaced:true,//开启命名空间  state:{ ... },  mutations: { ... },  actions: { ... }}const store = new Vuex.Store({  modules: {    countAbout,    personAbout  }})
  3. 开启命名空间后,组件中读取state数据:

    //方式一:自己直接读取this.$store.state.personAbout.list//方式二:借助mapState读取:...mapState('countAbout',['sum','school','subject']),
  4. 开启命名空间后,组件中读取getters数据:

    //方式一:自己直接读取this.$store.getters['personAbout/firstPersonName']//方式二:借助mapGetters读取:...mapGetters('countAbout',['bigSum'])
  5. 开启命名空间后,组件中调用dispatch

    //方式一:自己直接dispatchthis.$store.dispatch('personAbout/addPersonWang',person)//方式二:借助mapActions:...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
  6. 开启命名空间后,组件中调用commit

    //方式一:自己直接committhis.$store.commit('personAbout/ADD_PERSON',person)//方式二:借助mapMutations:...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

第六章 Vue-router

6.1.1 vue-router的理解

  • vue的一个插件库,专门用来实现SPA应用

6.1.2 对SPA应用的理解

  1. 单页Web应用(single page web application,SPA)。
  2. 整个应用只有一个完整的页面。
  3. 点击页面中的导航链接不会刷新页面,只会做页面的局部更新。
  4. 数据需要通过ajax请求获取。

6.1.3 路由的理解

  1. 什么是路由?
  • 一个路由就是一组映射关系(key - value)
  • key为路径, value可能是function或component
  1. 路由分类
  1. 后端路由:

    1. 理解:value是function, 用于处理客户端提交的请求。
    2. 工作过程:服务器接收到一个请求时, 根据请求路径找到匹配的函数来处理请求, 返回响应数据。
  2. 前端路由:

    1. 理解:value是component,用于展示页面内容。
    2. 工作过程:当浏览器的路径改变时, 对应的组件就会显示。

6.1.4 基本使用

  1. 安装vue-router,命令:npm i vue-router

  2. 应用插件:Vue.use(VueRouter)

  3. 编写router配置项:

    //引入VueRouterimport 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}]})//暴露routerexport default router
  4. 实现切换(active-class可配置高亮样式)

    About
  5. 指定展示位置

6.1.5 几个注意点

  1. 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。
  2. 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
  3. 每个组件都有自己的$route属性,里面存储着自己的路由信息。
  4. 整个应用只有一个router,可以通过组件的$router属性获取到。

6.1.6 嵌套路由(多级路由)

  1. 配置路由规则,使用children配置项:

    routes:[{path:'/about',component:About,},{path:'/home',component:Home,children:[ //通过children配置子级路由{path:'news', //此处一定不要写:/newscomponent:News},{path:'message',//此处一定不要写:/messagecomponent:Message}]}]
  2. 跳转(要写完整路径):

    News

6.1.7 路由的query参数

  1. 传递参数

    <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link><router-link :to="{path:'/home/message/detail',query:{   id:666,     title:'你好'}}">跳转</router-link>
  2. 接收参数:

    $route.query.id$route.query.title

6.1.8 命名路由

  1. 作用:可以简化路由的跳转。

  2. 如何使用

    1. 给路由命名:

      {path:'/demo',component:Demo,children:[{path:'test',component:Test,children:[{ name:'hello' //给路由命名path:'welcome',component:Hello,}]}]}
    2. 简化跳转:

      跳转跳转跳转

6.1.9 路由的params参数

  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的对象写法,则不能使用path配置项,必须使用name配置!

  3. 接收参数:

    $route.params.id$route.params.title

6.2.0 路由的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.2.1 的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  3. 如何开启replace模式:News

6.2.2 编程式路由导航

  1. 作用:不借助实现路由跳转,让路由跳转更加灵活

  2. 具体编码:

    //$router的两个APIthis.$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() //可前进也可后退

6.2.3 缓存路由组件

  1. 作用:让不展示的路由组件保持挂载,不被销毁。

  2. 具体编码:

         

6.2.4 两个新的生命周期钩子

  1. 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
  2. 具体名字:
    1. activated路由组件被激活时触发。
    2. deactivated路由组件失活时触发。

6.2.5 路由守卫

  1. 作用:对路由进行权限控制

  2. 分类:全局守卫、独享守卫、组件内守卫

  3. 全局守卫:

    //全局前置守卫:初始化时执行、每次路由切换前执行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'}})
  4. 独享守卫:

    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()}}
  5. 组件内守卫:

    //进入守卫:通过路由规则,进入该组件时被调用beforeRouteEnter (to, from, next) {},//离开守卫:通过路由规则,离开该组件时被调用beforeRouteLeave (to, from, next) {}

6.2.6 路由器的两种工作模式

路由工作模式分为两类:hash模式、history模式。

  1. hash模式:
    1. 地址中永远带着**#**号。【#及其后面的内容就是hash值,hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
    2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    3. 兼容性较好。
  2. history模式:
    1. 地址干净,美观 。
    2. 兼容性和hash模式相比略差。
    3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题

第七章:Vue UI组件库

7.1 移动端常用UI组件库

  1. Vant https://youzan.github.io/vant
  2. Cube UI https://didi.github.io/cube-ui
  3. Mint UI http://mint-ui.github.io

7.2 PC端常用UI组件库

  1. Element UI https://element.eleme.cn
  2. IView UI https://www.iviewui.com