Vue2 侦听器 watch【初识】

我心飞翔 分类:vue
Vue2 侦听器 watch【初识】

1. 侦听器 watch


Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性

当属性发生改变时,自动触发属性对应的侦听器。

当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。

2. 基础用法


当 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>

3. 应用场景:用户注册时,验证用户名是否存在


<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>

回复

我来回复
  • 暂无回复内容