vue watch的三種用法
var app = new Vue({
data: {
a: 1,
b: 2,
c: 3
},
watch: {
// watch的第一種形式
a: function (val, oldVal) { // 在監聽$route時,第一個參數表示to, 第二個參數表示from
console.log()
},
// watch的第二種形式,注意當引用函數名時,必須用單引號
b: 'going',
// watch的第三種形式
c: {
handler: function (val, oldVal) {
console.log(val)
},
deep: true, // 是否深度監聽
immediate: true // 是否立即執行handler函數
}
},
methods: {
going () {
console.log(123)
}
}
})
在後臺登錄系統的登陸界面見過這幾行代碼:
data () {
return {
redirect: undefined
}
}
watch: {
$route: {
handler: function (route) {
this.redirect = route.query && route.query.redirect
},
immediate: true
}
},
上述代碼的意義是什麼呢?
因爲有immediate: true 說明加載登錄頁面時就會執行handler函數,handler的第一個參數表示to,
所以上述代碼的意義就是,加載登錄頁後,直接獲取,登錄頁地址欄的的redirect參數,賦值給this.redirect