一:通过watch
来监听数据变化,并通过打印显示
<template>
<div class="personal-center">
<input type="text" placeholder="请输入" v-model="inputVal"/>
<p>{{newVal}}</p>
</div>
</template>
<script>
export default {
name: 'demo',
data() {
return {
inputVal: '',
newVal:''
}
},
watch: {
inputVal(newVal, oldVal) {
this.newVal = newVal
console.log("inputVal = " + newVal + " , oldValue = " + oldVal)
}
}
}
</script>
效果图:
二:首次渲染开启监听
按上面的代码实现,网页首次渲染是不会启动监听的,如果我们需要第一次渲染变开启监听,这时只需要设置immediate: true,
watch: {
inputVal(newVal, oldVal) {
this.newVal = newVal
console.log("inputVal = " + newVal + " , oldValue = " + oldVal)
},
immediate: true,
}
三:深度监听
当我们监听的数据是对象或数组时,需要开启深度监听才行。这时也仅仅需要加一行代码:deep: true
watch: {
inputVal(newVal, oldVal) {
this.newVal = newVal
console.log("inputVal = " + newVal + " , oldValue = " + oldVal)
},
immediate: true,
deep: true
}