Vue 侦听属性(watch)的基本使用
使用方式一
<body>
<div id="app">
<!-- 侦听属性 -->
<h1>{{resByWatch}}</h1>
</div>
<script>
new Vue({
el: "#app",
// 数据
data: {
text: "数据",
resByWatch: ''
},
watch: {
/*
//完整版写法
text: {
//初始化时让handler调用一下
immediate:true,
//监视多级结构中所有属性的变化
deep:true,
handler(newValue, oldValue){
console.log("数据改变时做一些事")
this.resByWatch = newValue + '!!!(侦听属性结果)'
}
},
*/
//简写-相当于handler()
text(newValue, oldValue) {
console.log("数据改变时做一些事")
this.resByWatch = newValue + '!!!(侦听属性结果)'
}
}
})
使用方式二
<body>
<div id="app">
<!-- 侦听属性 -->
<h1>{{resByWatch}}</h1>
</div>
<script>
const vm = new Vue({
el: "#app",
// 数据
data: {
text: "数据",
resByWatch: ''
},
})
/*
//完整版写法
//return 取消观察的function
var unwatch = vm.$watch('text', {
//初始化时让handler调用一下
immediate: true,
//深度监视
deep: true,
handler(newValue, oldValue) {
console.log("数据改变时做一些事")
this.resByWatch = newValue + '!!!(侦听属性结果)'
}
})
*/
//简写
//return 取消观察的function
var unwatch = vm.$watch('text',(newValue,oldValue)=>{
console.log("数据改变时做一些事")
this.resByWatch = newValue + '!!!(侦听属性结果)'
})
//取消观察
unwatch()
</script>
</body>
浙公网安备 33010602011771号