How to create dynamic tag based on props with Vue 2

老子叫甜甜 提交于 2019-11-29 16:21:41

问题


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>

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/41748934/how-to-create-dynamic-tag-based-on-props-with-vue-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!