Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue中if和for指令不能同时使用 #128

Open
wuxianqiang opened this issue Apr 13, 2019 · 0 comments
Open

vue中if和for指令不能同时使用 #128

wuxianqiang opened this issue Apr 13, 2019 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

建议不要在与v-for相同的元素上使用v-if。因为v-for指令的优先级高于v-if当它们处于同一节点。v-for 的优先级比 v-if 更高,这意味着 v-if 将分别重复运行于每个 v-for 循环中。

<ul>
  <li
    v-for="user in users"
    v-if="user.isActive"
    :key="user.id"
  >
    {{ user.name }}
  <li>
</ul>

如果需要在列表中过滤掉不需要的某一项,建议使用计算属性。

computed: {
  activeUsers: function () {
    return this.users.filter(function (user) {
      return user.isActive
    })
  }
}
...... //
...... //
<ul>
  <li
    v-for="user in activeUsers"
    :key="user.id">
    {{ user.name }}
  <li>
</ul>

if指令添加到父级元素上,这可以避免对每个列表项进行条件判断。

<ul v-if="shouldShowUsers">
  <li
    v-for="user in users"
    :key="user.id"
  >
    {{ user.name }}
  <li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant