【问题标题】:How to create dynamic tag based on props with Vue 2如何使用 Vue 2 基于 props 创建动态标签
【发布时间】:2017-06-04 13:46:11
【问题描述】:

如何制作类似于 vue-router router-link 的组件,通过 props 获取标签来呈现我的模板?

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

将呈现:

<ul>
  anything inside my-component
</ul>

【问题讨论】:

    标签: vue.js vuejs2 vue-router


    【解决方案1】:

    您可以像这样使用内置的component 元素:

    <component is="ul" class="foo" style="color:red">
      anything inside component
    </component>
    

    见:https://vuejs.org/v2/guide/components.html#Dynamic-Components

    【讨论】:

    • 这只会用 span 替换组件,没有任何组件的初始逻辑。
    • @rayrutjes 什么是“初始逻辑”? OP 询问如何“基于道具创建动态标签”,这正是这样做的。也许你有不同的情况?
    • 还记得你可以使用&lt;component v-bind:is="nameOfPropOrComputedProperty"&gt;,这样做你可以通过prop在父模板中传递包装器标签名称。来源:https://vuejs.org/v2/guide/components.html#Dynamic-Components
    • 这是更好的答案,因为“组件”组件可以完成接受的答案所做的一切,但也可以接受其他 Vue.js 组件/VNodes。此外,这不需要重新创建轮子。
    【解决方案2】:

    编辑:请检查@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>
    

    要了解更多关于渲染函数的信息,请参阅official documentation

    【讨论】:

    • 有没有不需要使用render函数的解决方案?
    • @rayrutjes,请参阅 krukid 的回答。
    • 顺便说一句,this.tag 在您的代码中不起作用,而 this.$props.tag 可以。
    猜你喜欢
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多