Reputation: 1827
I want to add one component inside other when user clicks a button. but how can we render the component in the virtual dom. I tried using v-html but its not working. Whats the best way to solve this issue?
export default {
data(){
return{
elements : {
hotel : '<hotel-form></hotel-form>'
},
}
},
methods:{
addHotel(){
console.log('add');
}
}
}
<template>
<div class="container" style="margin-top:300px;">
<div class="row" id="mainform">
<div v-for="item in elements">
<div v-html="item"></div>
</div>
</div>
<button @click="addHotel()">add hotel</button>
</div>
</template>
Upvotes: 1
Views: 375
Reputation: 55644
I would bind an array (hotels
) to a <hotel-form>
component tag via v-for
. This way, no hotel-form
components will be initially rendered, and then you can push an object (with any data to want bound to the hotel-form
component) to the hotels
array and the DOM will automatically render a new corresponding hotel-form
component.
Here's a simple example:
Vue.component('hotel-form', {
template: '#hotel-form',
props: { id: Number, name: String },
});
new Vue({
el: '#app',
data() {
return { hotels: [], count: 0 }
},
methods: {
addHotel() {
this.hotels.push({ name: 'foo', id: this.count++ })
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<div id="mainform">
<hotel-form v-for="hotel in hotels" :key="hotel.id" v-bind="hotel">
</hotel-form>
</div>
<button @click="addHotel">add hotel</button>
</div>
<template id="hotel-form">
<div>
<h4>Hotel Form #{{ id }}</h4>
<div>{{ name }}</div>
</div>
</template>
Upvotes: 1