Home > Software engineering >  Remove an array from computed reverse method Vuejs
Remove an array from computed reverse method Vuejs

Time:05-11

Good day, how to remove an array from a reverse method?

Here's my code

const app = Vue.createApp({
    data() {
        return {
            app_title: 'Simple Checklist App',
            entered_task_value: '',
            list_of_tasks: [],
            is_priority: false,
        }
    },
    computed: {
        reverseItems() {
            return [...this.list_of_tasks].reverse();
        }
    },
    methods: {
        add_item() {
            this.list_of_tasks.push(
                {
                    id: this.list_of_tasks.length   1,
                    data: this.entered_task_value,
                    priority: this.is_priority,
                }
            );
            this.entered_task_value = '';
            this.is_priority = '';
        },
        total_tasks() {
           return this.list_of_tasks.length;
        },
        remove_item(task_index) {
            return this.reverseItems.splice(task_index, 1);
        }
    },
});


app.mount('#app');

The remove_item method is not working and I am not sure how to properly call the property inside the computed

remove_item(task_index) {
            return this.reverseItems.splice(task_index, 1);
        }

This is the HTML

            <ul>
            <li
                v-for="(task, task_index) in reverseItems"
                
                :key="task.id"
                :
            >
            {{task.id}}
            {{task.data}}
             <button v-on:click="remove_item(task_index)">Remove</button>
            </li>
        </ul>

Thank you in Advance!

CodePudding user response:

You should update the list_of_tasks of task array instead of the computed array.

The computed values are calculated from the real data and updated each time the data changes.

Here is the documentation about computed properties in vue.js


Here is a small example

new Vue({
  el: '#app',
  data: () => {
    return {
      myArr: [1,2,3,4,5]
    }
  },
  
  computed: {
    myArrReversed(){
      return [...this.myArr].reverse()
    }
  },
  
  methods : {
    addItem(){
      this.myArr.push(this.myArr.length  1)
    },
    removeItem(){
      this.myArr.splice(this.myArr.length - 1, 1)
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="item of myArrReversed" :key='item'>
      {{item }}
    </li>
  </ul>
  
  <button @click="addItem">Add item</button>
  <button @click="removeItem">Remove item</button>

</div>

  • Related