Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性
当属性发生改变时,自动触发属性对应的侦听器。
当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。
当 msg 属性的值发生改变时,就会触发侦听器的执行
<div id="app">
<input type="text" v-model="msg">
</div>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: 'Hello'
},
watch: {
msg: function(){
console.log(this.msg)
}
}
})
</script>
<div id="app">
用户名: <input type="text" name="name" v-model.lazy="username">
<span :style="msgStyle">{{ msg }}</span>
<br>
密码: <input type="password" name="pass">
</div>
<script>
let vm = new Vue({
el: '#app',
data: {
msg: '',
username: '',
msgStyle: ''
},
watch: {
username: function(){
// 发送ajax请求 验证用户名
if (this.username == 'liang') {
this.msg = '该用户名已存在'
this.msgStyle = {
color: 'red',
fontWeight: 'bold'
}
} else {
this.msg = '用户名可以注册'
this.msgStyle = {
color: 'green',
fontWeight: 'bold',
}
}
}
}
})
</script>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有