Oct 17, 2017

Vue.js: Add component on click

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


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.

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

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


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