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>
- Declare a counter
- We first declare a data
countwith the initial value of 1.
- Use
v-forto generate components
- In our
templatetag, We loop through the component withv-for="index in count". - With the
v-forshorthands,vuewill generate fromcounttimes of the component. In this case,countact like range. For more detailed explanation, refer to the official documetation: v-for with a Range{:target="_blank"}).
- Button to increase
count
- Then we create a
Addbutton that executeaddComponenton click. TheaddComponentmethod is fairly straightforward, just increase thecountby 1. - When the user click the
Addbutton, thecountwill be increased by 1, thus causeVue.jsto render additional component in our view.
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