侦听属性
侦听属性,可以帮助我们侦听data某个数据的变化,从而做相应的自定义操作。
侦听属性是一个对象,它的键是要监听的对象或者变量,值一般是函数,当侦听的data数据发生变化时,会自定执行的对应函数,这个函数在被调用时,vue会传入两个形参,第一个是变化前的数据值,第二个是变化后的数据值。
案例1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.min.js"></script>
<script>
window.onload = function(){
var vm = new Vue({
el:"#app",
data:{
num:20
},
watch:{
num:function(newval,oldval){
//num发生变化的时候,要执行的代码
console.log("num已经发生了变化!");
}
}
})
}
</script>
</head>
<body>
<div id="app">
<p>{{ num }}</p>
<button @click="num++">按钮</button>
</div>
</body>
</html>
案例2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
<style>
input[type=password]{
outline-color: red;
}
input.is_pass{
outline-color: blue;
}
input.is_fail{
outline-color: red;
}
</style>
</head>
<body>
<div id="app">
<button @click="num--">-</button>
<input type="text" size="1" v-model="num">
<button @click="num++">+</button>
<p>
<input type="password" :class="pwd_tips" v-model="password">
</p>
</div>
<script>
const vm = new Vue({
el:"#app",
data(){
return {
num: 0,
password: "",
pwd_tips: "is_fail",
}
},
// 侦听属性,往往开发中用于验证用户的操作和输入内容,当然也可以在用户输入合法结果时,自动完成对应的操作
// 例如:http提交数据,提示。
watch:{
num(){
if(this.num < 0){
this.num = 0;
}
},
password(){
if(this.password.length>6 && this.password.length<16){
this.pwd_tips = "is_pass"
}else{
this.pwd_tips = "is_fail";
}
}
},
methods:{
}
})
</script>
</body>
</html>

浙公网安备 33010602011771号