vue2.0中监听watch的三种写法
watch:观测Vue实例上的数据变动,对应一个对象。
键:就是需要监测的那个东西,
值:
1.可以是当键变化时执行的函数,有两个参数,第一个是变化后的值,第二个是变化前的值。
2.可以是函数名,得用单引号包裹。
3.可以是一个对象,这个对象有三个选项:
(1)handler :一个回调函数,监听到变化时应该执行的函数。
(2)deep :boolean值,是否深度监听。(一般监听时是不能监听到对象属性值的变化的,数组的变化可以听到)
(3)immediate :boolean值,是否立即执行handler函数。
watch的三种情况:
1、普通的watch:
el:'#app',
data:{
meter:1000,
kilameter:1
},
watch:{
meter:function(val){
this.kilameter = val * 0.1;
},
kilameter:function(val){
this.meter = val *1000;
}
}
})
2、数组的watch:
el:'#app',
data:{
arr:[1,2,3]
},
watch:{
arr:function(newV,oldV){
console.log(newV);
console.log(oldV);
}
}
})
3、对象的watch:
写法一:
el:'#app',
data:{
obj : {
a:111,
b:222
}
},
watch:{
obj:{
handler:function(newV,oldV){
console.log(oldV);
},
deep:true
}
}
)
写法二
<el-input :disabled="true" type="textarea" v-model="form.price"></el-input>
显示价格:{{$store.state.editTask.rowData.price}}
<el-input type="text" v-model="newPrice"></el-input>
<script>
data(){
return{
newPrice: "",
timer: null,
form{
id:'',
price:''
}
}
},
created() {
// this.$store.state.editTask.rowData = row
this.form = this.$store.state.editTask.rowData // 当前行数据
},
watch: {
// 对象的监听写法
'form.price': function (val) {
// newPrice(val){
this.showReason = val!== 1
},
newPrice(val){
clearTimeout(this.timer); //防抖
this.timer = setTimeout(() => {
/**
*小数点不好控制,把控不了用户输入后是否继续输入,
*所以如果输入后1秒内没有再输入则小数点就会被清掉
*/
let reg = /^(0|[1-9]\d*)(\.\d{1,2})?/; //只允许输入小数点后2位
let price = val.match(reg);
this.newPrice = price ? price[0] : '';
}, 1000);
}
},
</script>
store定义数据
src/store/modules/editTask.js
const state = {
rowData:{},//当前行数据
}