watch和computed的区别
监视
watch可以对单个变量继续监视,也可以深度监视对象
如果需求是对10个变量进行监视?
计算属性computed可以监视多个值,并且指定返回数据,并且可以显示在页面
export default{
data(){
return{
text:[];
person:[{
name:'Jack'
},{
name:'rose'
}]
}
}
methods:{
changeValue(){
this.text='abc';
this.person[0].name='mick';
}
},
watch:{
text:function(newV,oldV){
console.log('值改变了,很开心');
},
<!--
person:function(newV,oldV){
console.log('Person改变了');
}-->
深度监视
person:{
handler:function(val,oldVal){
console.log('person改变了');
}
deep:true
}
}
}
总结:遇到数组或对象的属性,就需要遇到深度监视
computed计算属性
<div>
单价:<input type="text" name="",v-model="price">
件数:<input type="text" name="",v-model="num">
折扣:<input type="text" name="",v-model="rate">
{{sum.name}}:{{sum.price}}
</div>
created(){},
methods:{},
computed:{
sum(){
console.log('触发了');
//如果当函数内涉及到的this,相关属性发生改变之后触发,并且返回一个值,可以是对象
return this.price*this.num*(this.rate/100);
return{
name:'古龙水',
price:this.price*this.num*(this.rate/100)
}
}
}