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 v-if/v-for哪个优先级更高? #70

Closed
GGXXMM opened this issue Dec 29, 2020 · 0 comments
Closed

Vue v-if/v-for哪个优先级更高? #70

GGXXMM opened this issue Dec 29, 2020 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Dec 29, 2020

v-if、v-for的优先级

  • Vue2中,v-for优先级高于v-if
  • Vue3中,刚好相反

分析

做个实验,把v-if和v-for放在一块,输出渲染函数可以判断指令执行的先后顺序。
我们可以用vue2做个demo,在过滤列表的div绑定 v-for="user in users" v-if="user.isActive" 指令,打印其渲染函数:

ƒ anonymous(
) {
with(this){return _c('div',{attrs:{"id":"app"}},_l((items),function(item){return (item.isActive)?_c('div',{key:item.id},[_v("\n      "+_s(item.name)+"\n    ")]):_e()}),0)}
}

注意事项

  • 永远不要把v-if、v-for同时用在一个元素上
  • 建议父元素先做v-if判断,再v-for遍历生成子列表

源码中找答案 vue2:https://github1s.com/vuejs/vue/blob/HEAD/src/compiler/codegen/index.js#L65-L66 vue3:https://github1s.com/vuejs/core/blob/HEAD/packages/compiler-core/src/codegen.ts#L586-L587

@GGXXMM GGXXMM added the vue label Dec 6, 2021
@GGXXMM GGXXMM closed this as completed Mar 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant