Vue.js 监听属性
Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化。
watch中可以使用异步代码。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model="inputVal">
<span>{{msg}}</span>
</div>
<script src="node_modules/vue/dist/vue.min.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
inputVal: '',
msg: ''
},
//watch中可以使用异步代码
watch: {
//newVal为当前值,oldVal为上一次值。
inputVal(newVal, oldVal) {
setTimeout(()=> {
if(newVal.length < 2) {
this.msg = "密码太短了"
}else if(newVal.length > 10) {
this.msg = "密码太长了"
}else {
this.msg = "密码长度合适"
}
}, 0)
// console.log(newVal,oldVal)
}
}
})
</script>
</body>
</html>