在 Vue 模板中使用三元

hen*_*hen 7 vue.js

是否可以在视图模板中使用三元条件来返回 HTML,类似于 Reacts 渲染函数?

<some-vue-component :someProp="someVal" />

// some-vue-component template file
{{someProp == true ? <h1>Hello</h1> : <h1>Bye</h1>}}

This doesnt seem to work
Run Code Online (Sandbox Code Playgroud)

编辑:我需要使用v-if吗?

// some-vue-component template file
<div>
  <div v-if="someProp === true">
    <h1>Hello</h1>
  </div>
  <div v-else>
    <h1>Bye</h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

ski*_*tle 14

使用的所有输出都{{ ... }}将被转义,因此您不能包含 HTML 标签。

在这个例子中你给你只需移动<h1>外面的{{ ... }}

<h1>{{ someProp ? 'Hello' : 'Bye' }}</h1>
Run Code Online (Sandbox Code Playgroud)

更一般地,你会使用v-if

<h1 v-if="someProp">Hello</h1>
<h2 v-else>Bye</h2>
Run Code Online (Sandbox Code Playgroud)

另请注意,如果您不希望它向完成的 DOM 添加额外元素,则v-if可以将其放置在<template>标签上:

<template v-if="someProp">Hello</template>
<strong v-else>Bye</strong>
Run Code Online (Sandbox Code Playgroud)

在紧要关头也有v-html但你应该尽可能避免使用它。它允许您直接注入 HTML,但这很少需要,因为模板可以处理绝大多数用例。