vue2
vue2中的watch监听数据的方式有两种:
<script>
export default {
data() {
return {
msg: 'hello'
}
},
watch: {
// 简单监听
msg(newVal, oldVal) {
console.log(newVal, oldVal)
},
// 深度监听
msg: {
deep: true,
immediate: true,
handler(newVal, oldVal) {
console.log(newVal, oldVal)
}
}
},
created() {
// 函数式监听
const watcher = this.$watch('msg', (newVal, oldVal) => {
console.log(newVal, oldVal)
}, {
deep: true,
immediate: true
})
// 取消监听
watcher()
}
}
</script>
小于 1 分钟