Vue.js: Add component on click

Oct 17, 2017

Estimated Reading Time: 2 minutes (306 words)

I have been working on a project which uses Vue.js for front end. I came across a scenario where we need to allow user to add more entry in their form.

Initial Approach

The first thought that come to my mind will be get the div#id of the element and append it dynamically through javascript

var parent = document.getElementById("parent");
var component = createComponent(); // Assuming this return an Node element

parent.appendChild(component);

However, since we are using Vue.js, it doesn’t feel natural to approach it this way.

With Vue.js

Instead, we can utilize the functionality of Vue.js, by using v-for and v-on:click.

<template>
  <div>
    <p v-for="index in count" :key="index">
      {% raw %}{{ index }}{% endraw %}
    </p>
    <button v-on:click="addComponent">Add</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        count: 1
      };
    },
    methods: {
      addComponent() {
        this.count += 1;
      }
    }
  };
</script>
  1. Declare a counter
  1. Use v-for to generate components
  1. Button to increase count

Conclusion

With the combination of, count act as counter. v-for to generate the components, and addComponent method to increase the count, we are able to render new component into our view when the user click the button.

P.S. The solution is inspired by this forum post{:target=”_blank”}