watch可以用來監聽vue實例中data數據的變化,然后觸發觸發這個watch中的對應的function處理函數
eg:
watch: {
// 監聽data中firstname數據的變化
firstname(newVal, oldVal) {
// console.log("監聽到了firstname的變化")
// this.fulltname = this.firstname + "----" + this.lastname
// 函數還有兩個可用的參數,newVal和oldVal(newVal表示),newVal表示最新的值。oldVal表示舊值
// console.log(newVal + "---" + this.lastname)
this.fulltname = newVal + "--" + this.lastname
},
lastname(newVal) {
// console.log("監聽到了firstname的變化")
// this.fulltname = this.firstname + "----" + this.lastname
// 函數還有兩個可用的參數,newVal和oldVal(newVal表示)
// console.log(newVal + "---" + this.lastname)
this.fulltname = this.firstname + "---" + newVal
}
},
watch還可以用來監聽,一些費dom元素的操作。例如:路由的更換
eg:可以直接使用watch來監聽$route.path
watch: {
// watch可以監聽一些非dom操作
'$route.path'(newVal, oldVal) {
// console.log(newVal + "-----------" + oldVal)
if (newVal == "/logn") {
console.log("切換到了登陸組件")
}
else if (newVal == '/resgist') {
console.log("切換到了注冊組件")
}
}
},