How to add or remove DOM elements dynamically with Vue.js?

Sometimes, we want to add or remove DOM elements dynamically with Vue.js.

In this article, we’ll look at how to add or remove DOM elements dynamically with Vue.js.

How to add or remove DOM elements dynamically with Vue.js?

To add or remove DOM elements dynamically with Vue.js, we can manipulate values of reactive properties and then use directives to render the data based on the reactive property values.

For instance, we write

<template>
  <div>
    <ul>
      <li v-for="(input, index) in inputs" :key="input.id">
        <input type="text" v-model="input.one" /> - {{ input.one }}
        <input type="text" v-model="input.two" /> - {{ input.two }}
        <button @click="deleteRow(index)">Delete</button>
      </li>
    </ul>

    <button @click="addRow">Add row</button>
  </div>
</template>

<script>
//...
export default {
  //...
  data() {
    return {
      inputs: [],
    };
  },

  methods: {
    addRow() {
      this.inputs.push({
        id: uuidv4(),
        one: "",
        two: "",
      });
    },
    deleteRow(index) {
      this.inputs.splice(index, 1);
    },
  },
  //...
};
</script>

to render the inputs array items with v-for.

We render 2 inputs based on the items,

And then we render the Delete button.

And when we click Add row, the addRow method is done which calls this.inputs.push to append a new entry.

After that, v-for will re-render the inputs array to include the new entry.

Likewise, when deleteRow is called, the item at the given index will be removed and v-for will re-render the new list.

Conclusion

To add or remove DOM elements dynamically with Vue.js, we can manipulate values of reactive properties and then use directives to render the data based on the reactive property values.