Home > other >  V-for remove element
V-for remove element

Time:11-11

I'm working on a Vue/Quasar app and what I want to do is show the following layout only once when the page is loaded:

<template>
  <div v-for="(section, index) in sections" :key="index">
    <div >
      <q-input v-model="sectionName" bottom-slots dense :label="labelText">
        <template v-slot:append>
          <q-btn flat dense icon="add" color="grey " @click="addNew" />
          <q-btn flat dense icon="delete" color="grey " @click="removeSection" />
        </template>
      </q-input>
    </div>
  </div>
</template>

Here is the code snippet from the script section:

    setup() {
    const sections = ref(1);
    const addNew = () => {
      sections.value  
    };
    const removeSection = () => {
     //...
    };
    return{
     //...}

The addNew function works well: new sections will be added to the screen. But how could I remove a particular (which was clicked) section? What should I change?

CodePudding user response:

You can send a parameter to your removeSection function (ex: index) after that once you clicked on delete button you will know which index should be deleted. You will be able to find the item in your sections that you wanted to delete.

CodePudding user response:

You can define sections like array of objects with id and value:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const sections = ref([{id: new Date(), sectionName: ''}]);
    const addNew = (i) => {
      sections.value = [...sections.value, {id: new Date(), sectionName: ''}]
    };
    const removeSection = (i) => {
      sections.value.length > 1 && sections.value.splice(sections.value[i], 1)
    };
    return{ sections, addNew, removeSection }
   }
})

app.use(Quasar)
app.mount('#q-app')
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material Icons" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/quasar.prod.css" rel="stylesheet" type="text/css">
<div id="q-app">
  <div v-for="(section, index) in sections" :key="index">
    <div >
      <q-input v-model="section.sectionName" bottom-slots dense :label="labelText">
        <template v-slot:append>
          <q-btn flat dense icon="add" color="grey " @click.prevent="addNew" />
          <q-btn flat dense icon="delete" color="grey " @click.prevent="removeSection(index)" />
        </template>
      </q-input>
    </div>
  </div>
  {{sections}}
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/quasar.umd.prod.js"></script>

  • Related