用Vue.js實現全選與全不選刪除功能
阿新 • • 發佈:2019-01-06
這是實現全選與全不選邏輯的程式碼,大家只要給相應的控制元件再加上刪除邏輯就完成了全選與選不選、單選等刪除功能了;這段程式碼經過我很多次強暴,是可以用的。
<template>
<div id="hello"><ol>
<li>
<span><input type="checkbox" v-model="selectAll"></th></span>
<span align="left">全選</span>
</li>
<li v-for="answer in answers">
<span>
<!--:value === v-bind:value=""-->
<input type="checkbox" v-model="selected" :value="answer.id" >
</span>
<span>{{ answer.name }}</span>
</li>
</ol>
</div>
</template>
<script>
import Vue from 'vue'
export default {
name: 'hello',
data:function() {
return{
answers: [
{ "id": 1, "name": "A" },
{ "id": 2, "name": "B" },
{ "id": 3, "name": "C" },
{ "id": 4, "name": "D" }
],
selected : []
} },
computed: {
selectAll: {
get: function () {//因為在set方法中改變了全域性變數selected,所以get方法會被呼叫
console.log("getgetget");
console.log("this.answers ? ...="+this.answers ? this.selected.length == this.answers.length : false);
console.log("this.answers="+this.answers);
console.log("this.selected.length == this.answers.length:"+this.selected.length == this.answers.length);
return this.answers ? this.selected.length == this.answers.length : false
},
set: function (value) {//點選checkbox會自動呼叫set方法
console.log("setsetset");
var selected = [];
console.log("value="+value);
if (value) {
this.answers.forEach(function (user) {
console.log("user="+user);
console.log("user.value="+user.value);
console.log("user.id"+user.id);
selected.push(user.id);
});
}
this.selected = selected;
}
},
selectAll2:{
get:function(){
console.log("get");
},
set:function(value){
console.log("value"+value);
}
}
}
}
</script>
<style>
</style>