How to create dynamic tag based on props with Vue 2
How can I make a component similar to vue-router router-link
where I get the tag via props to render my template ?
<my-component tag="ul">
</my-component>
Would render:
<ul>
anything inside my-component
</ul>
You can use a built-in component
element like so:
<component is="ul" class="foo" style="color:red">
anything inside component
</component>
See: https://vuejs.org/v2/guide/components.html#Dynamic-Components
EDIT: Please check @krukid answer, it is a better solution, I didn't know about component
element when I answered
Render function ways:
You need to create a "wrapper component" that use a render function.
import Vue from 'vue';
Vue.component('wrapper-component', {
name: 'wrapper-component',
render(createElement) {
return createElement(
this.tag, // tag name
this.$slots.default // array of children
);
},
props: {
tag: {
type: String,
required: true,
},
},
});
then in any other template just use as follows
<wrapper-component tag="div">
<span>All this will be rendered to inside a div</span>
<p>
All
</p>
</wrapper-component>
and that should render to this
<div>
<span data-v-4fcf631e="">All this will be rendered to inside a div</span>
<p data-v-4fcf631e="">
All
</p>
</div>
To know more about render functions please see official documentation