在VScode中,把v-if和v-for写在同一个标签内,你会发现报错。
错误代码:
原因:
v-for 的优先级比 v-if 的高,所以每次渲染时都会先循环再进行条件判断,而又因为 v-if 会根据条件为 true 或 false 来决定渲染与否,所以如果将 v-if 和 v-for 一起使用时会特别消耗性能如果有语法检查,则会报语法错误。
解决方法:
1、将 v-for 放在外层标签,v-if 放在内层标签。
<template>
<div
v-for="(item,index) in list"
:key="index"
>
<div v-if="item === '1'">{{ item }}</div>
</div>
</template>
<script>
export default {
data () {
return {
list: ['1', '2', '3', '4']
}
},
}
</script>
2、使用 computed ,将 list 替换为计算属性中的 listData ,再渲染到页面上。
<template>
<div
v-for="(item,index) in listData"
:key="index"
>
<div>{{ item }}</div>
</div>
</template>
<script>
export default {
data () {
return {
list: ['1', '2', '3', '4']
}
},
computed: {
listData: function () {
return this.list.filter((item) => {
return item === '1'
})
}
}
}
</script>
3、直接在for循环后面使用数组的过滤方法,会先过滤数组,在进行循环。
<template>
<div
v-for="(item,index) in list.filter((item) => { return item === '1' })"
:key="index"
>
<div>{{ item }}</div>
</div>
</template>
<script>
export default {
data () {
return {
list: ['1', '2', '3', '4']
}
}
}
</script>