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
count
with the initial value of 1.
- Use
v-for
to generate components
- In our
template
tag, We loop through the component withv-for="index in count"
. - With the
v-for
shorthands,vue
will generate fromcount
times of the component. In this case,count
act 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
Add
button that executeaddComponent
on click. TheaddComponent
method is fairly straightforward, just increase thecount
by 1. - When the user click the
Add
button, thecount
will be increased by 1, thus causeVue.js
to 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