watch computed 和 methods 之间的对比

//watch computed 和 methods 之间的对比
1.computed :属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算,主要是当属性使用,
2.methods :方法表示一个具体的操作,主要书写业务逻辑 (写方法)
3.watch : 一个对象,键是需要观察的表达式,值是对应回调函数,主要用来监听某些特定数据的变化,从而进行某些具体的业务逻辑操作;可以看做是computed 和methods的结合体

例子:
code html

<div id="app">
			<input type="text" v-model="input1" /> +
			<input type="text" v-model="input2" /> =
			<input type="text" v-model="input3" />
</div>

vue.js

//1.computed
new Vue({
	el:"#app",
	data:{
		input1:'',
		input2:'',
	},
	methods:{},
	computed:{
		//在computed 中,可以定义一些属性,这些属性叫做计算属性(本质是一个方法),只不过我们在使用这些计算属性的时候,
		//是把它们的名称直接当做属性来使用的,并不会把计算属性当做方法去调用
		
		//注意:	1.计算属性在引用的使用一定不要加()去调用,直接使用就行了
		//		2.只有计算属性这个function 内部,所用到的任何data中数据发送了变化,就会立即重新计算这个计算属性
		//		3.计算属性的求职结果被缓存起来,方便下次使用
		'input3':function(){
			console.log("执行几次???")
			return this.input1 + '--' + this.input2
		}
	}
})
			
//2.methods 
new Vue({
	el:"#app",
	data:{
		input1:'',
		input2:'',
		input3:''
	},
	methods:{
		getinput3(){
			this.input3 = this.input1 +"-" + this.input2
		}
	},
})

//3.watch
new Vue({
	el:"#app",
	data:{
		input1:'',
		input2:'',
		input3:''
	},
	methods:{},
	watch:{ //使用这个属性,可以监视data中的指定数据改变,然后触发
		'input1':function(newVal, oldVal){
			//方法1
			/* console.log("监视watch!!")
			this.input3 = this.input1 +"-" + this.input2 */	
								
			//方法2
			console.log(newVal+"---****---"+oldVal)
			this.input3 = newVal + '-' + this.input2						
		},
		'input2':function(newVal){					
			//方法2
			this.input3 = this.input1 + '-' + newVal						
		},
	}
})

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值