vue中计算属性computed与属性检测watch的区别

Vue中computed与watch的区别

计算属性computed属性检测watch
首次运行首次不运行
调用时需要在模板中渲染,修改计算所依赖元数据调用时只需修改元数据
默认深度依赖默认浅度观测
适合做筛选,不可异步适合做执行异步或开销较大的操作

计算属性

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="./vue.js"></script>
	</head>
	<body>
		<div id="app">
			<h3>计算属性</h3>
			<!-- 元属性 -->
			<div>{{str}}</div>
			<!-- 计算属性 -->
			<!-- <div>{{cptStr}}</div> 要放在模板中渲染才可以调用-->
			<div>{{cptStr}}</div>
		</div>
	</body>
	<script>
		let vm = new Vue({
			el:'#app',
			//元属性
			data:{
				str:'hello world',
			},
			computed:{
				// key(计算属性):value(fn)
				cptStr:function(){
					console.log('计算属性运行了')
					//计算业务
					// return '计算后的值'		//计算后的值
					return this.str			//hello world
				}
			}
		})
	</script>
</html>

属性检测

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="./vue.js"></script>
	</head>
	<body>
		<!-- data,commuted,watch都会被加到响应式系统中 -->
		<div id="app">
			{{str}}
			<!-- {{cptStr}} -->
		</div>
	</body>
	<script>
		let vm = new Vue({
			el:'#app',
			//元属性
			data:{
				str:'hello world',
				json:{a:1,b:2}
			},
			methods:{
				fn(current,prev){
					console.log('数据观测触发的方法',current,prev);
					// console.log('this默认全部指向vm',this);
				}
			},
			computed:{
				cptStr(){
					this.str;
					// this.json;
					// console.log('this默认全部指向vm',this)
					console.log('计算属性运行')
					// return this.json.a+this.str
					// return this.str+1;
					setTimeout(()=>this.str+=1,1000)
				}
			},
			watch:{
				str(current,prev){
					console.log('数据观测运行',current,prev);
					setTimeout(()=>this.str+=100,2000)
				}
				// str:"fn",
				// json:"fn",
				// str:{
				/* json:{
					handler(current,prev){
						console.log('数据观测运行',current,prev)
					},
					immediate:true,		//首次运行
					deep:true,		//深度观测
				} */
			}
		})
	</script>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值