Home > OS >  Deleting row list in Vue.js 3
Deleting row list in Vue.js 3

Time:12-10

I am trying to remove item from my list , i am using js delete operator but it can't , here is the code

HTML :

    <ol v-if="status">
      <li v-for="(item, key) in items" :key="item.title">
        {{ item.title }} - Type - {{ item.type }}
        <input v-model="item.type" type="text" value="{{ item.type }}" style="margin-left: 2%;" />
        <button @click="delete items[key]">Remove Items</button>
      </li>
    </ol>

JS :

    const sample = {
    data() {
    return {
      newItem: [
        {title: "", type: ""}
      ],
      subject: 'Vue.js',
      items: [
        { title: 'Javascript', type: 'Native'},
        { title: 'Vue', type: 'Framework'},
        { title: 'React', type: 'Framework'},
        { title: 'Angular', type: 'Framework'},
      ],
      item: 'Javascript',
      status: 1
    }
  },
}

Vue.createApp(sample).mount('#app')

CodePudding user response:

you need to declare a proper method for your @click event:

 <button @click="deleteItem(key)">Remove Items</button>

then, in your vue, methods section, declare this function:

methods:{
    deleteItem(key){
     this.items.splice(key, 1)
    },
},

your complete vue code will be this :

const sample = {
    data() {
    return {
      newItem: [
        {title: "", type: ""}
      ],
      subject: 'Vue.js',
      items: [
        { title: 'Javascript', type: 'Native'},
        { title: 'Vue', type: 'Framework'},
        { title: 'React', type: 'Framework'},
        { title: 'Angular', type: 'Framework'},
      ],
      item: 'Javascript',
      status: 1
    }
  },

   methods:{
        deleteItem(key){
         this.items.splice(key, 1)
        },
    },

}

Vue.createApp(sample).mount('#app')

CodePudding user response:

Hi In your @onclick u dont use correctly ur function u most to do something like this :

   <ol v-if="status">
  <li v-for="(item, key) in items" :key="item.title">
    {{ item.title }} - Type - {{ item.type }}
    <input v-model="item.type" type="text" value="{{ item.type }}" style="margin-left: 2%;" />
    <button @click="delete(item)">Remove Items</button>
  </li>
</ol>

And here, delete is a function for delete ur item in items like this function

delete(item){
 this.items.splice(item.title, 1)
},
  • Related