How to create dynamic tag based on props with Vue

2020-02-26 14:32发布

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>

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-26 15:05

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

查看更多
Anthone
3楼-- · 2020-02-26 15:15

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

查看更多
登录 后发表回答