VUE 监听对象中某一个属性的变化
第一种直接监听对象的属性,写法如下<!DOCTYPE html><html><head><meta charset="UTF-8"><!-- import CSS --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.cs
·
第一种
直接监听对象的属性,写法如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<h1>{{ obj.num }}</h1>
<button @click="click">点击</button>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
obj: {
num: 1,
name: 'testeg'
}
},
watch: {
'obj.num'(val) {
console.log('watch' + val)
}
},
methods: {
click() {
this.obj.num++
}
}
})
</script>
</html>
第二种
监听整个对象,配置 deep: true 属性实现深度监测
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
<h1>{{ obj.num }}</h1>
<button @click="click">点击</button>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
obj: {
num: 1,
name: 'testeg'
}
},
watch: {
obj: {
handler: function (obj) {
console.log('watch' + obj.num)
},
deep: true
}
},
methods: {
click() {
this.obj.num++
}
}
})
</script>
</html>
更多推荐
已为社区贡献10条内容
所有评论(0)