- <template>
- <div id="app">
- <button v-for="(item, index) in list" @click="checkFn(item)" :class="isActiveFn(item)?'active':''">{{ item.value }}</button>
- <button @click="selectAll">全选</button>
- <button @click="reverseSelect">反选</button>
- </div>
- </template>
-
- <script>
- export default {
- name: "app",
- data:function () {
- return {
- list: [
- {
- id: 0,
- value: "1"
- },
- {
- id: 1,
- value: "2"
- },
- {
- id: 2,
- value: "3"
- },
- {
- id: 3,
- value: "4"
- },
- ],
- checkedList: []
- }
- },
- methods: {
- isActiveFn:function (item) {
- let index = this.checkedList.findIndex(el => {
- return item.value === el.value;
- })
- if (index !== -1) {
- return true
- } else {
- return false
- }
- },
- checkFn:function (item) {
- let index = this.checkedList.findIndex(el => {
- return el.value === item.value
- })
- if (index === -1) {
- this.checkedList.push(item)
- } else {
- this.checkedList.splice(index, 1)
- }
- },
- selectAll:function () {
- // 这里使用深拷贝 , 切忌使用 this.checkedList = this.list , 这样会发生引用的问题
- this.checkedList = JSON.parse(JSON.stringify(this.list))
- },
- reverseSelect:function () {
- let parseChecked = []
- this.list.forEach(item => {
- let index = this.checkedList.findIndex(el => {
- return el.value === item.value
- })
- if (index === -1) {
- parseChecked.push(item)
- }
- })
- this.checkedList = parseChecked
- }
- }
- }
- </script>
-
- <style lang="less" scoped>
- button {
- margin: 10px;
- }
- .active {
- background-color: chartreuse;
- }
- </style>