这里我们先简单复习下watch的使用方法,具体使用可以参考官方文档 watch (opens new window)
watch
类型:{ [key: string]: string | Function | Object | Array }
一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch(),遍历 watch 对象的每一个 property。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>watch方法参数的处理</title>
</head>
<body>
<div id="app"></div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
age: 18
}
},
watch: {
// age(newValue, oldValue) {
// console.log(newValue, oldValue)
// },
// age: {
// handler(newValue, oldValue) {
// console.log(newValue, oldValue)
// },
// sync: true // 会出现两次
// }
// age: [
// function handler1(newValue, oldValue) {
// console.log(newValue, oldValue)
// },
// function handler2(newValue, oldValue) {
// console.log(newValue, oldValue)
// }
// ]
// age: 'handler'
age: [
'handler',
'handler1'
]
},
methods: {
handler(newValue, oldValue) {
console.log(newValue, oldValue)
},
handler1(newValue, oldValue) {
console.log(newValue, oldValue)
}
},
})
vm.age = 19
vm.age = 20
/*
1.如果监控的key对应的值是对象,是无法获取老状态的
2.watch一个属性可以注册多个监听器
3.可以写成handler的形式,监听method中的方法
*/
</script>
</body>
</html>
注意:不应该使用箭头函数来定义 watcher 函数。