How to create dynamic tag based on props with Vue 2

vue.jsVuejs2Vue Router

vue.js Problem Overview


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>

vue.js Solutions


Solution 1 - vue.js

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

Solution 2 - vue.js

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCassio CabralView Question on Stackoverflow
Solution 1 - vue.jskrukidView Answer on Stackoverflow
Solution 2 - vue.jsAldoRomo88View Answer on Stackoverflow