【问题标题】:VueJS HTML element type based on condition基于条件的VueJS HTML元素类型
【发布时间】:2019-10-04 20:45:33
【问题描述】:

在 Vue JS 中,我可以做到

<h1 v-if="someCondition">MY TITLE</h1>

有没有办法让元素类型基于某种条件?

例如,基于someCondition,我希望我的标题为<h1><h2>

我想我可以使用

<template v-if="someCondition === 0">
  <h1>MY TITLE</h1>
</template>

<template v-if="someCondition === 1">
  <h2>MY TITLE</h2>
</template>

但是有没有更直接的写法呢?

【问题讨论】:

标签: javascript html vue.js vuejs2


【解决方案1】:
<component :is="'h'+someCondition">MY TITLE</component>

你的 "someCondition" 可以定义为 props 或 data 属性,它的值可以是 1 到 6,以防你只使用 "H tags"

【讨论】:

    【解决方案2】:

    如果只有 2 个变体,最好的选择是坚持使用 v-ifv-else

    如果有更多可能的变化,则可以选择动态组件 (https://vuejs.org/v2/guide/components-dynamic-async.html)

    <component :is="dynamicComponent">Foo</component>
    
    ...
    
    computed: {
      dynamicComponent() {
        return 'h'+this.i
      }
    }
    

    依次渲染为&lt;h1&gt;&lt;h2&gt;&lt;h{i}&gt;。 这在实际组件之间切换时更有用,而不是 HTML h 标签。

    https://codesandbox.io/s/vue-template-z40u7

    【讨论】:

      【解决方案3】:

      这就是render 函数有用的地方。每当您的模板需要更高级的逻辑时,渲染函数都提供使用 Javascript 及其所有逻辑流能力来生成模板,而不是 HTML 标记。你可以阅读更多关于Vue's render functions here的信息。

      Here is a fiddle 来演示这个例子:

      data() {
        return {
          someCondition: 1
        }
      },
      render(h){
        let tagType;
        if (this.someCondition === 0) {
          tagType = 'h1';
        } else if(this.someCondition === 1) {
          tagType = 'h2';
        }
        return h(tagType, null, 'MY TITLE');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 1970-01-01
        • 2017-11-01
        • 2018-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多