In Vue.js, I have a var app = new Vue({...});
and I have a ponent Vueponent('myponent', ...
where I can use such ponent without any issue by directly adding <myponent></myponent>
in html. What I wish to do is to dynamically add those ponent on demand maybe after a button click or when some other such event takes place. In raw JS, I'd use document.createElement...
when event fires and then do el.appendChild..
to add it into html. How would I do the same with Vue.js ?
I'm not doing anything fancy with node js. This is on a single html page with <script src=".js"></script>
in the <head>
.
In Vue.js, I have a var app = new Vue({...});
and I have a ponent Vue.ponent('myponent', ...
where I can use such ponent without any issue by directly adding <myponent></myponent>
in html. What I wish to do is to dynamically add those ponent on demand maybe after a button click or when some other such event takes place. In raw JS, I'd use document.createElement...
when event fires and then do el.appendChild..
to add it into html. How would I do the same with Vue.js ?
I'm not doing anything fancy with node js. This is on a single html page with <script src="https://cdn.jsdelivr/npm/vue/dist/vue.js"></script>
in the <head>
.
1 Answer
Reset to default 5To do this the "Vue way" usually involves the use of v-if
, v-for
or <ponent>
, depending on what you want to do:
- Use
v-if
to conditionally show a ponent/element based on a condition. - Use
v-for
to render a list of ponents/elements. - Use
<ponent>
to render a dynamic ponent/element.
So to achieve what you described in your question, you can declare a boolean data property visible
like this:
data() {
return {
visible: false
}
}
and use it with v-if
to control the visibility of a ponent in the template:
<myponent v-if="visible"></myponent>
This requires that <myponent>
exist in the template upfront. If you don't know what kind of ponent you want to show, then you can either include each possibility in the template and display the one you want based on some condition:
<p1 v-if="p1Visible"></p1>
<p2 v-if="p2Visible"></p2>
<p3 v-if="p3Visible"></p3>
or you can use <ponent>
together with another data property (p
) which you can set to the name of the ponent you want to display:
<ponent v-if="visible" :is="p"></ponent>
What you described (document.createElement
followed by el.appendChild
) does not exist in Vue. Vue has a strict rendering mechanism which you need to work with; it isn't possible to dynamically instantiate ponents and stick them into the DOM randomly. Technically you can do p = new Vue()
as an equivalent to document.createElement
and then el.appendChild(p.$el)
, but that probably isn't what you want to do because you would be creating an independent Vue instance that you would have to manage manually with no easy way of passing data around.