首页 > 解决方案 > 如何使用条件而不将其附加到元素?

问题描述

在 vue 中,我们有需要附加到元素的指令 v-if。

有没有一种方法可以使用条件而不将它们附加到 mustachejs 方式之类的东西上?

我正在遍历一系列单词,它在每个单词中添加了 div,这很烦人

这是我的模板

<div v-for="(str, index) in reference" :key="index">
  <div v-if="patternIncluded(str)">
    <input type="text" v-model="remarks[index]">
  </div>
  <div v-else>
    {{str}}
  </div>
</div>

如果我能这样做,我会很好:|

{{if true}}
something goes here
{{else}}
other thing goes here
{{\if}}

标签: vue.js

解决方案


这是您的代码,但使用< 模板 >标签

<template v-if="patternIncluded(str)">
    <input type="text" v-model="remarks[index]">
</template>
<template v-else>
    {{str}}
</template>

以下是 Vue 官方文档中的示例:

<template v-if="loginType === 'username'">
  <label>Username</label>
  <input placeholder="Enter your username">
</template>
<template v-else>
  <label>Email</label>
  <input placeholder="Enter your email address">
</template>

更多信息:https ://vuejs.org/v2/guide/conditional.html#Controlling-Reusable-Elements-with-key

您还可以使用方法并在文件底部的< script >中使用普通 Javascript

希望这有帮助,干杯


推荐阅读