Home > front end >  Change Vue.js array's elements to opposite with splice
Change Vue.js array's elements to opposite with splice

Time:01-27

<template>
        <div>
            <div
                v-for="(a, i) in arr"
                :key="i"
                :checked="a"
                @click="toggleItem(i)"
                
            >
        </div>
        <div >{{ arr }}</div>
    </template>

    <script>
    export default {
        data() {
            return {
              arr: [true, false, true, false, true, true, true],
            };
        },
        methods: {
            toggleItem(index) {
                this.arr.splice(this.arr[index], 1, !this.arr[index]);
            },
        };
    </script>

How can I change each element in the array arr from true to false and from false to true by clicking the checkbox button using splice method ?

CodePudding user response:

You can use the splice() method to change each element in the array arr from true to false and vice versa by clicking the checkbox button. Here's an example of how you can do it:

methods: {
    toggleItem(index) {
        this.arr.splice(index, 1, !this.arr[index]);
    },
};

CodePudding user response:

If I understood you correctly maybe without splice:

const app = Vue.createApp({
  data() {
    return {
      arr: [true, false, true, false, true, true, true],
    };
  },
  methods: {
    toggleItem(i) {
      this.arr[i] = !this.arr[i]
    },
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div>
    <div
      v-for="(a, i) in arr"
      :key="i"
      :checked="a"
      @click="toggleItem(i)"
      
    >
    {{ a }}
  </div>
  <div >{{ arr }}</div>
</div>

  • Related