-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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不建议一起用? #7
Comments
一、作用
在 两者在用法上 <Modal v-if="isShow" />
<li v-for="item in items" :key="item.id">
{{ item.label }}
</li> 二、优先级
在 示例编写一个 <div id="app">
<p v-if="isShow" v-for="item in items">
{{ item.title }}
</p>
</div> 创建 const app = new Vue({
el: "#app",
data() {
return {
items: [
{ title: "foo" },
{ title: "baz" }]
}
},
computed: {
isShow() {
return this.items && this.items.length > 0
}
}
}) 模板指令的代码都会生成在 ƒ anonymous() {
with (this) { return
_c('div', { attrs: { "id": "app" } },
_l((items), function (item)
{ return (isShow) ? _c('p', [_v("\n" + _s(item.title) + "\n")]) : _e() }), 0) }
}
初步得到结论: 再将 <div id="app">
<template v-if="isShow">
<p v-for="item in items">{{item.title}}</p>
</template>
</div> 再输出下 ƒ anonymous() {
with(this){return
_c('div',{attrs:{"id":"app"}},
[(isShow)?[_v("\n"),
_l((items),function(item){return _c('p',[_v(_s(item.title))])})]:_e()],2)}
} 这时候我们可以看到, 我们再在查看下 源码位置: export function genElement (el: ASTElement, state: CodegenState): string {
if (el.parent) {
el.pre = el.pre || el.parent.pre
}
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el, state)
} else if (el.once && !el.onceProcessed) {
return genOnce(el, state)
} else if (el.for && !el.forProcessed) {
return genFor(el, state)
} else if (el.if && !el.ifProcessed) {
return genIf(el, state)
} else if (el.tag === 'template' && !el.slotTarget && !state.pre) {
return genChildren(el, state) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el, state)
} else {
// component or element
...
} 在进行 最终结论: 三、注意事项
<template v-if="isShow">
<p v-for="item in items">
</template>
computed: {
items: function() {
return this.list.filter(function (item) {
return item.isShow
})
}
} |
3.x 版本中 v-if 总是优先于 v-for 生效。 |
嗯,是的哈 |
棒棒棒! |
list是啥 |
一个变量,就是一个数组。 |
你举得例子没 |
嗯,大概就是这个意思,先将源数据(list)处理一次, |
list在哪里定义 |
但是,有时候v-if的值是根据v-for的item来判断,比如自定义table列 |
还是没看懂,最后if在内部处理的那部分代码 |
尽可能的在computed中处理好数据。 |
没错的 |
尽可能保证,渲染的值,里面的每一项都是“可靠数据”。 |
data |
No description provided.
The text was updated successfully, but these errors were encountered: