Skip to content

【VUE】v-for和v-if,哪个优先级比较高? #31

@Dliling

Description

@Dliling

两者一起使用时,v-for优先级更高。这意味着,当我们使用v-for循环一个列表时,v-if会在每个循环中执行,所以Vue官网不建议在同一个元素上使用v-for和v-if。

为了避免一起使用,我们通常会有以下方式:

  1. 将v-if的判断放在父元素上,这种方式可以有条件的跳过循环
<ul v-if="state">
    <li v-for="todo in todos"></li>
</ul>
  1. 将v-if需要判断的数据放在computed属性中
<template>
    <ul>
        <li v-for="todo in todolist"></li>
    </ul>
</template>

export default {
    computed: {
        todolist() {
            return this.todos.filter(todo => {
                return todo.completed;
            });
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions