如何在Vue 2中基于props创建动态标签

70

我该如何制作类似于vue-router的组件,其中我可以通过props获取标签以渲染我的模板?

<my-component tag="ul">
</my-component>

会产生以下结果:

<ul>
  anything inside my-component
</ul>
2个回答

165

16

编辑: 请查看@krukid的答案,那是一个更好的解决方案,当我回答时我不知道有component元素。

渲染函数的方法:

您需要创建一个使用渲染函数的“包装组件”。

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,
    },
  },
});

然后在任何其他模板中,只需按以下方式使用

<wrapper-component tag="div">
  <span>All this will be rendered to inside a div</span>
  <p>
    All 
  </p>
</wrapper-component>

这应该呈现为这个样子

<div>
  <span data-v-4fcf631e="">All this will be rendered to inside a div</span> 
  <p data-v-4fcf631e="">
    All 
  </p>
</div>

要了解有关渲染函数的更多信息,请参阅官方文档


1
有没有不需要使用渲染函数的解决方案? - rayrutjes
@rayrutjes,请查看krukid的回答。 - Jordan Pickwell
顺便提一下,在你的代码中,“this.tag”不起作用,而应该使用“this.$props.tag”。 - Alexander Kim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接