不推荐
在同一元素上使用 v-if 和 v-for
const App = {data() {return {todoList: [{id: 1,content: 'CONCTENT 1',completed: false},{id: 2,content: 'CONCTENT 2',completed: true},{id: 3,content: 'CONCTENT 3',completed: false}]}},template: `<ul><liv-for="todo of todoList" :key="todo.id"v-if="!todo.completed">{{ todo.content }}</li></ul>`}Vue.createApp(App).mount('#app');
Vue3
v-if 权限是大于 v-for,即 v-if 静态式内部的变量是没办法从 v-for 表达式中获取
Vue2
v-for 权限是大于 v-if,v-for 比 v-if 有更高的优先级
为何到 Vue3 作出这样的改变
- 在逻辑层级来看,if > for
if 是决定渲染不渲染,而 for 是怎么渲染
- 性能问题
如果先渲染再,决定是否渲染会造成性能浪费
但最后是结论还是不要把 v-if 和 v-for 在同组件中连用,可以看下面的解决方法。
解决方法
使用 <template>
{// ...template: `<ul><template v-for="todo of todoList" :key="todo.id"><li v-if="!todo.completed">{{ todo.content }}</li></template></ul>`}
使用 computed
{// ...template: `<ul><li v-for="todo of NotCompletedTodoList" :key="todo.id"{{ todo.content }}</li></ul>`,computed: {NotCompletedTodoList() {return this.todoList.filter(item => !item.completed);}}}
