Watch 是一個可以監聽目標Data並在他發生改變時自動執行的方法,

在寫 Vue 的過程也算蠻常會使用到這個方法,必要時也會搭配 computed 一起使用。

一般寫起來會像這樣,搭配 computed 則是可以監聽物件中的值。

data () {
	return {
		targetData : 0,
		targetObj : { 
			ObjContentA:1,
			ObjContentB:2,
			ObjContentC:3,
		}
	}
},
computed:{
	targetObjA(){
		return this.ObjContentA
	}
},
watch: {
  targetData(newValue,oldValue) {
    console.log("改變後的值",newValue)
		console.log("改變前的值",oldValue)
  },
	targetObjA(newValue,oldValue) {
    console.log("改變後的值",newValue)
		console.log("改變前的值",oldValue)
  }
},

但是像我上次需要利用 Watch 在目標 data 改變時操作 $ref 綁定的元素,

就遇到一個問題了,因為Watch被建立時 $ref 是還沒有被渲染的,

所以一打開就能看到 console 有大片的紅色文字。😵

這時候就會用到另一個監聽的方法了 : $watch ( 實體上的函數 )

用這個函式來註冊監聽器,就能夠將他寫在 mounted階段 之中,

這時候才開始監聽,也就能夠取得到 $ref 不會報錯了。

<body>
	<div>
		<h1 class="blue" ref="H1">要被操作的元素</h1>
	</div>
</body>
data () {
	return {
		targetData : 0,
	}
},
mounted() {
	// this.$watch(expOrFn, callback, [options] )
	let vm = this 
	this.$watch(
    function () {
      return vm.targetData
    },
		(newValue)=>{
			if(newValue === 10){
				vm.$ref.H1.classList.value = ['red']
			}
		}
	)
}

大概就可以像這樣在目標Data的數值變成10 的時候將 H1 的顏色改成紅色。

如果有人遇到一樣的問題,也可以試試看這個方法。