1. 程式人生 > >vue-computed 計算屬性

vue-computed 計算屬性

<!DOCTYPE html>
<html>
<head>
    <title>123</title>
</head>
<body>
   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <div>
   <div>
      全選
      <input type="checkbox"  v-model
='ischeckAll' name=""> </div> <ul> <li v-for="item in objects"> <span>{{item.name}}</span> <input type="checkbox" v-model="item.checked" name=""> </li> </ul> <div> <b>選中成員:{{total}}</
b> <b>選中數量:{{totalCount}}</b> </div> </div> </div> <script type="text/javascript"> let obj=[ { name:"崔1", num:1, checked:true }, { name:"崔2
" , num:1, checked:true }, { name:"崔3" , num:1, checked:true }, { name:"崔1" , num:1, checked:true }, { name:"崔2" , num:1, checked:true }, { name:"崔2" , num:1, checked:true }, { num:1, name:"崔2", checked:true }, { name:"崔2", num:1, checked:true }, { name:"崔2", num:1, checked:true }, { name:"崔2", num:1, checked:true }, { name:"崔4", num:1, checked:true }, { name:"崔3", num:1, checked:true }, ] var app = new Vue({ el: '#app', data: { message: 'Hello Vue!', objects:obj, ischeck:false }, computed:{ total(){ return this.removeDuplicatedItem(this.objects.filter(item=>item.checked)).length }, totalCount(){ let totalArr=this.objects.filter(item=>item.checked) let num =0 totalArr.map(item=>{ num +=item.num }) return num }, ischeckAll:{ get(){ return this.objects.every(item=>item.checked) }, set(nweValue){ this.objects.forEach(item=>{ item.checked=nweValue }) } } }, methods:{ removeDuplicatedItem(option){ let json={} let arr=[] for(let i=0;i<option.length;i++){ let item = option[i] if(!json[item.name]){ json[item.name]=true arr.push(item) } } return arr } } }) </script> </body> </html>