Asked By: Anonymous
I have the following code:
<div class="content">
<p>Hello World</p>
</div>
And I have the following div count:
data() {
return {
divs: 2
}
}
So, if divs
is 2
then it should generate two divs and wrap the div.content
inside it so it becomes something like this:
<div>
<div>
<div class="content">
<p>Hello World</p>
</div>
</div>
</div>
As you can see there’s two divs and then only there’s this div.content
! I tried using v-for
but it generates 2 separate divs! Please help!
Solution
Answered By: Anonymous
First off: this sounds like a pretty unnecessary requirement and most probably re-framing the problem will lead to a much better solution!
That being said, there is a way to achieve what you’re trying to do with some dark Vue magic 😉
What you need is a recursive render function:
render: function (createElement) {
return this.level >= 1 ?
createElement('div', [createElement(DynamicDiv, {
props: {
level: this.level-1
}
}, this.$slots.default)]) :
createElement('div', this.$slots.default)
},
props: {
level: {
type: Number,
required: true
}
}
https://vuejs.org/v2/guide/render-function.html
You can find a working example over here: https://codesandbox.io/s/k9p16wzmyo