The difference between vue's computed and watch

First of all, computed and watch are both to observe the data changes of the page.

Here are their differences:

Computed attributes (one-to-many, one-to-one)

The calculated properties will be mixed into the Vue instance, and the this context of all getters and setters is automatically bound to the Vue instance.

1. Monitor custom variables. This variable cannot be repeated with the variables in data and props;
2. The attribute value of the computed attribute is the default get method of the function (must have a return value), and the attribute has a get and set method;
3. Support caching. Only when the dependent data changes will it be recalculated, otherwise the data in the cache will be fetched;
4. Asynchronous is not supported, and asynchronous operations in computed are invalid;

<templete>
	<div>{
    
    {
    
    message}}</div>
</templete>
<script>
data(){
    
    
	return {
    
    
		name:'muma',
		type:'man'
	}
},
computed:{
    
    
	//仅读取getter
	message:function(){
    
    
		return `${
    
    this.muma}是${
    
    this.man}孩子!!!`
	}// 读取getter和设置setter
	msg:{
    
    
	  get: function () {
    
    
        return `${
    
    this.muma}是${
    
    this.man}`
      },
      //在给msg重新赋值的时候会调用setter,例如this.msg = '你是谁'。
      set: function (newValue) {
    
    //newValue是msg新的值
      	let names = newValue.split('是');
        this.muma = names[0];
        this.man = names[1];
      }
	}
}
</script>

Monitor attribute watch (many to one)

1. Monitor the changes of data in data and props;
2. Cache is not supported, it will be recalculated every time;
3. Support asynchronous, the monitoring function receives two parameters, the first parameter is the latest value; the second parameter is Enter the previous value;

<templete>
	<div>{
    
    {
    
    message}}</div>
</templete>
<script>
data(){
    
    
	return {
    
    
		name:'muma',
		type:'boy',
		func:'1',
		obj:{
    
    
			label:'aa'
		}
	}
},
watch:{
    
    
	//name变了修改type	
	name:function(new, old){
    
    
		this.type = 'girl';
	},
	'func':'funcChange',
	'obj.label':{
    
    
		handler(new, old){
    
    
			this.type = 'boy';
		},
		immediate:true, //控制是否在第一次渲染是执行这个函数
		deep:true //控制是否要看这个对象里面的属性变化
	}
},
methods:{
    
    
	funcChange(){
    
    
		console.log('......')
	}
}
</script>

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/110876799