vue计算属性computed
下面是一个简单的computed 的使用,在项目中常用
selectAll,进入页面,selectAll 先通过get 获取值,当页面刷新时,则通过其他的checbox 的元素的isSelect来计算值
<template>
<div class="demo">
<div class="example">
<div class="item">
<input type="checkbox" id="seleceall" v-model="selectAll"/>
<label for="seleceall" >全选</label>
</div>
<div class="item" v-for="(item,index) in arr" :key="index">
<input type="checkbox" :id="item.id" v-model="item.isSelect"/>
<label :for="item.id">{{item.name}}</label>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
arr:[{isSelect:false,name:"羽毛球",id:"item1"},{isSelect:false,name:'踢毽子',id:"item5"},{isSelect:false,name:"游泳",id:"item4"},{isSelect:false,name:"马拉松",id:"item3"},{isSelect:false,name:"乒乓球",id:"item2"},]
};
},
computed:{
selectAll:{
get(){
return this.arr.every(p=>p.isSelect);
},
set(val){
return this.arr.forEach(p=>p.isSelect=val);
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201013232008855.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NoaXhpYW94aWFvMTA2,size_16,color_FFFFFF,t_70#pic_center)
};
注意:computed 默认调用的是get 方法 必须有return 但是computed 不支持异步,但是支持缓存