Home > Software engineering >  How to dynamically append template in Vue 3
How to dynamically append template in Vue 3

Time:11-19

I am attempting to set up a Vue 3 component that dynamically adds rows to a table. So far, I have the following:

 <template>
    <table>
        <tbody>
            <tr v-for="(item, index) in tableRows" :key="item.id">
                <td>D{{item.id}}</td>
                <td><input type="text" v-model="item.Filename"></td>
                <td><input type="text" v-model="item.ImageTitle"></td>
                <td><input type="text" v-model="item.Caption"></td>
            </tr>
        </tbody>
    </table>
   <button @click.stop="insert_Row">add row  </button>
   
   <div v-for="item in tableRows" :key="item.id">
     {{item}}
   </div>  
</template>
    
<script>
export default {
  data() {
    return {
    tableRows: [
      {
        "id": 1,
        "Filename": "test",
        "ImageTitle": "test",
        "Caption": "test"
      }
    ]
    }
  },
  methods: {
    insert_Row() {
      this.tableRows.push(
        {
        "id": this.tableRows.length 1,
        "Filename": "",
        "ImageTitle": "",
        "Caption": ""
      }
      )
    }
  }
}
</script>

However, the above is configured to include an initial row by default, before clicking the add button. I want to set this up so that the first row is also dynamically added when the clicking the button. How can I go about doing this?

CodePudding user response:

Perhaps I'm over-simplifying things, but if you want no table rows to display until the button has been pressed, then why not simply remove the row of dummy data that you have in your tableRows array?

Change this:

data() {
    return {
        tableRows: [
            {
               "id": 1,
               "Filename": "test",
               "ImageTitle": "test",
               "Caption": "test"
             }
        ]
    }
},

to this:

data() {
    return {
        tableRows: []
    }
},
  • Related