vue2 computed
计算属性:
有点监听的属性,只要响应式数据变化,他就会做计算,不变化就不做计算。
换句话说:计算属性是基于它们的响应式依赖进行缓存的。响应式数据变化了它们会重新计算,但是没变,会把原来的数据保存好,不会再次执行函数
vue2
<tempalte>
<div>
{{ name }}: {{ filmInstantPice() }} 亿
</div>
</template>
...
data(){
return {
name: '哪吒2',
filmPrice: '100'
}
},
computed: {
filmInstantPice: ()=>{
return this.filmPrice
}
}
computed vs watch
大多数情况下会滥用watch属性,因为开发时候只想着实时监听数据的变化,但却忽略了是否全部需要监听。若是几个数据最终关联到一起,最终要展示关联后的实时数据,不会用computed,自然就用watch代替了。这个就很浪费了。比如
<tempalte>
<div>
{{ topic }}: 参与人:{{ participants }}
</div>
</template>
...
data(){
return{
topic: '动漫',
host: '撒贝宁',
director: '饺子'
participants: ''
}
},
watch(){
host:(val)=>{
this.participants = val + this.director
},
director: (val)=>{
this.participants = val + this.host
}
}
...
上面看上去就很繁琐,要监听两个数据,代码量也增大了,很让人抓狂。若是用computed ,那就神清气爽了
<tempalte>
<div>
{{ topic }}: 参与人:{{ participants()}}
</div>
</template>
...
data(){
return{
topic: '动漫',
host: '撒贝宁',
director: '饺子'
}
},
computed: {
participants: ()=>{
return this.host + '' + this.director
}
}
...
侦听器 watch
当然不滥用watch,但是也不能不用。如果数据变化时,执行异步或者,开销很大的操作,那就要用它了。