Vue2学习第三天

Vue2 学习第三天

1. 计算属性 computed

  • 计算属性实现

    1. 定义:要用的属性不存在,要通过已有属性计算得来。

    2. 原理:底层借助了Objcet.defineproperty方法提供的gettersetter

    3. get函数什么时候执行?

      • 初次读取时会执行一次。
      • 当依赖的数据发生改变时会被再次调用。
    4. 优势:与 methods 实现相比,内部有缓存机制(复用),效率更高,调试方便。

js 复制代码
<template>
	<div>
		<div>count:{{ count }}</div>
		<div>num:{{ num }}</div>
		<div>computed:{{ doubleCount }}</div>
		<div>methods:{{ numDouble() }}</div>
		<button @click="num++">num++</button>
		<button @click="count++">count++</button>
	</div>
</template>

<script>
export default {
	/**
	 * 1.可以根据你data当中的值进行计算
	 * 2.可以实现数据缓存
	 * 3.计算属性必须依赖响应式数据
	 */
	name: "Computed",
	data() {
		return {
			count: 10,
			num: 12,
		};
	},
	computed: {
		// 只有依赖的数据发生变化,才执行
		doubleCount() {
			console.log("计算了");
			return this.count * 2;
		},
	},
	methods: {
		// num当中只要数据发生变化,methods就执行
		numDouble() {
			console.log("methods执行了");
			return this.num * 2;
		},
	},
};
</script>

<style scoped></style>
  • 计算属性总结

    1. 可以根据你 data 当中的值进行计算
    2. 可以实现数据缓存
    3. 计算属性必须依赖响应式数据
  • 计算属性最终会出现在 vm 上,直接读取使用即可。

  • 如果计算属性要被修改,那必须写set 函数 去响应修改,且set中要引起计算时依赖的数据发生改变。

2. 监视属性 watch

  • 监视属性

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

html 复制代码
<!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>今天天气很{{info}}</h2>
			<!-- 绑定事件的时候:@xxx="yyy" yyy可以写一些简单的语句 -->
			<!-- <button @click="isHot = !isHot">切换天气</button> -->
			<button @click="changeWeather">切换天气</button>
		</div>
	</body>

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

		const vm = new Vue({
			el: "#root",
			data: {
				isHot: true,
			},
			computed: {
				info() {
					return this.isHot ? "炎热" : "凉爽";
				},
			},
			methods: {
				changeWeather() {
					this.isHot = !this.isHot;
				},
			},
		});
	</script>
</html>
  • 深度监视
js 复制代码
<template>
	<div>
		<input type="text" v-model="value" />
		<button @click="changeObj">监听obj</button>
	</div>
</template>

<script>
export default {
	name: "Watch",
	data() {
		return {
			value: "",
			msg: {
				name: "123",
				obj: {
					name: "abc",
				},
			},
		};
	},
	// watch用于监听data中数据的变化,里面可以写任何逻辑
	watch: {
		value(newValue, oldValue) {
			console.log(newValue, oldValue);
		},
		msg: {
			handler(newValue, oldValue) {
				console.log(JSON.stringify(this.msg));
			},
		},
		// immediate立即监听
		immediate: true,
		// deep深度监听,对于嵌套层次深的对象,会一直监听到最下面
		deep: true,
	},
	methods: {
		changeObj() {
			this.msg = {
				name: "123",
				obj: {
					name: "abc",
					a: {
						b: "214",
					},
				},
			};
		},
	},
};
</script>

<style scoped></style>
  • 监视属性简写
html 复制代码
<!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>今天天气很{{info}}</h2>
			<button @click="changeWeather">切换天气</button>
		</div>
	</body>

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

		const vm = new Vue({
			el: "#root",
			data: {
				isHot: true,
			},
			computed: {
				info() {
					return this.isHot ? "炎热" : "凉爽";
				},
			},
			methods: {
				changeWeather() {
					this.isHot = !this.isHot;
				},
			},
			watch: {
				//正常写法
				/* isHot:{
					// immediate:true, //初始化时让handler调用一下
					// deep:true,//深度监视
					handler(newValue,oldValue){
						console.log('isHot被修改了',newValue,oldValue)
					}
				}, */
				//简写
				/* isHot(newValue,oldValue){
					console.log('isHot被修改了',newValue,oldValue,this)
				} */
			},
		});

		//正常写法
		/* vm.$watch('isHot',{
			immediate:true, //初始化时让handler调用一下
			deep:true,//深度监视
			handler(newValue,oldValue){
				console.log('isHot被修改了',newValue,oldValue)
			}
		}) */

		//简写
		/* vm.$watch('isHot',(newValue,oldValue)=>{
			console.log('isHot被修改了',newValue,oldValue,this)
		}) */
	</script>
</html>
  • watch 实现姓名案例

    • computedwatch 之间的区别:
      • computed 能完成的功能,watch 都可以完成。
  • watch 能完成的功能,computed 不一定能完成,例如:watch 可以进行异步操作

  • 两个重要的小原则:

    • 所被 Vue 管理的函数,最好写成普通函数,这样 this 的指向才是 vm 或 组件实例对象。

    • 所有不被 Vue 所管理的函数(定时器的回调函数、ajax 的回调函数等、Promise 的回调函数),最好写成箭头函数,这样 this 的指向才是 vm 或 组件实例对象。

html 复制代码
<!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(val) {
					setTimeout(() => {
						// console.log(this);
						this.fullName = val + "-" + this.lastName;
					}, 1000);
				},
				lastName(val) {
					this.fullName = this.firstName + "-" + val;
				},
			},
		});
	</script>
</html>
相关推荐
醉暮天22 分钟前
4.25学习——文件上传之00截断
学习
武昌库里写JAVA23 分钟前
39.剖析无处不在的数据结构
java·vue.js·spring boot·课程设计·宠物管理
blackA_4 小时前
数据库MySQL学习——day4(更多查询操作与更新数据)
数据库·学习·mysql
Freedom风间4 小时前
前端优秀编码技巧
前端·javascript·代码规范
萌萌哒草头将军5 小时前
🚀🚀🚀 Openapi:全栈开发神器,0代码写后端!
前端·javascript·next.js
萌萌哒草头将军5 小时前
🚀🚀🚀 Prisma 爱之初体验:一款非常棒的 ORM 工具库
前端·javascript·orm
拉不动的猪5 小时前
SDK与API简单对比
前端·javascript·面试
runnerdancer5 小时前
微信小程序蓝牙通信开发之分包传输通信协议开发
前端
梁下轻语的秋缘5 小时前
每日c/c++题 备战蓝桥杯(P1049 [NOIP 2001 普及组] 装箱问题)
c语言·c++·学习·蓝桥杯
山海上的风6 小时前
Vue里面elementUi-aside 和el-main不垂直排列
前端·vue.js·elementui