vue2.0 computed、methods和watch比較

目錄

computed、methods、watch理解

簡單地理解

加載順序

computed&&method比較

computed&&watch比較


computed、methods、watch理解

computed:計算屬性將被混入到Vue實例中,所有getter和setter的this上線自動綁定到Vue中
methods:methods將被混入到Vue實例中,可以直接通過vm實例訪問這些方法,或者指令表達式中使用。方法中的this自動綁定爲Vue實例。
watch:是一種通用的觀察和響應Vue實例上的數據變動。適用於異步操作。

簡單地理解

  computed在HTML&DOM加載後馬上執行,如賦值
  methods則必須要有一定的觸發條件纔會執行,如點擊事件
  watch用於觀察Vue實例上數據的變動。一個對象。鍵是觀察的表達式,值是對應的回調。值也可以是方法名,或者對象。

加載順序

 默認加載的時候先執行Computed-->watch,不執行method。當觸發某一事件後,method-->watch、

computed&&method比較

<div id="app">
	computed<br/>
	{{fullName}}<br/>
	{{fullName}}<br/>
	
	Method<br/>
	{{getfullName()}}<br/>
	{{getfullName()}}<br/>
</div>
<script>
	var app=new Vue({
		el:"#app",
		data:{
			firstName:"wu",
			lastName:"man",
			fullName:""
		},
		computed:{
			fullName:function(){
				console.log("computed")
				return this.firstName+" "+this.lastName;
			}
		},
		method:{
			console.log("method")
			getfullName:function(){
				return this.firstName+" "+this.lastName;
			}
		}
		
		
	})
</script>

控制檯輸出:
computed
method
method

總結:多個{{}}使用了computed,computed內的function也只執行一次。僅當function內涉及到Vue實例綁定的data的值的改變,function纔會重新執行,並修改DOM上的內容。methods則會多次調用。

computed&&watch比較:

<div id="app">
	watch<br/>
	{{fullName}}<br/>
	{{fullName}}<br/>
</div>
<script>
	var app=new Vue({
		el:"#app",
		data:{
			firstName:"wu",
			lastName:"man",
			fullName:""
		},
		watch:{
			firstName:function(val){
				return this.fullName=val+" "+this.lastName ;
			},
			lastName:function(val){
				return this.fullName=val+" "+this.firstName;
			}
		}
		
		
	})
</script>

<div id="app">
	computed<br/>
	{{fullName}}<br/>
	{{fullName}}<br/>
</div>
<script>
	var app=new Vue({
		el:"#app",
		data:{
			firstName:"wu",
			lastName:"man",
		},
		computed:{
			fullName:function(){
				console.log("computed")
				return this.firstName+" "+this.lastName;
			}
		
	})
</script>

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章