watch侦听器
语法: watch:?{要侦听的属性名{handler (newVal,oldVal){}}} 注意:变量名对应的值改变侦听器里面的值也会自动触发更新* 注:如果只用于普通监听,可以使用简便写法 简便写法: watch:{ 属性名(newVal,oldVal){}}
<template>
<div>
{{ 1 }}
<button @click="add">点击+1</button>
</div>
</template>
<script>
export default {
data() {
return {
num: 1
};
},
methods: {
add() {
this.num++;
}
},
watch: {
num: {
handler(newVal, oldVal) {
console.log(newVal, oldVal);
}
}
}
};
</script>
<style scoped lang="less"></style>
每当我点击button 让num 的值加一发生改变时,都会被watch 侦听到,newVal 是改变后的值,可以理解为一个新的值,而oldVal 为改变前的值,也就是旧的值  
watch中的immediate
immediate:true/false 作用是,当设置为true 时,值没有发生改变,也会侦听一次,也就是页面加载开始,就会执行一次侦听 
watch中的deep
watch 只能侦听普通的数据,如果要侦听复杂的数据,包括嵌套类型的(多层的) 第一种写法 Vue中的watch默认监测对象内部的改变(一层):  第二种:设置deep:true 设置deep:true 表示开启了深度侦听模式,可以侦听复杂类型数据 
|