Source to find the answer in compiler/codegen/index, js (vue2.5 version) do a test as follows
<p v-for="item in items" v-if="condition">
Copy the code
<! DOCTYPE html><html>
<head>
<title>Vue event processing</title>
</head>
<body>
<div id="demo">
<h1>Who has a higher priority, V-for or V-if? How should it be used correctly to avoid performance problems?</h1>
<! -- <p v-for="child in children" v-if="isFolder">{{child.title}}</p> -->
<template v-if="isFolder">
<p v-for="child in children">{{child.title}}</p>
</template>
</div>
<script src=".. /.. /dist/vue.js"></script>
<script>
// Create an instance
const app = new Vue({
el: '#demo'.data() {
return {
children: [{title:'foo'},
{title:'bar'}}},],computed: {
isFolder() {
return this.children && this.children.length > 0}}});console.log(app.$options.render);
</script>
</body>
</html>
Copy the code
At the same level, the rendering function looks like this:
(function anonymous(
) {
with(this){return _c('div', {attrs: {"id":"demo"}},[_c('h1',[_v("Who has a higher priority, V-for or V-if? How should it be used correctly to avoid performance problems?")]),_v(""),
_l((children),function(child){return(isFolder)? _c('p',
[_v(_s(child.title))]):_e()})],2)}})// Contains the isFolder conditional judgment
Copy the code
When the two are of different levels, the rendering function is as follows
(function anonymous(
) {
with(this){return _c('div', {attrs: {"id":"demo"}},[_c('h1',[_v("Who has a higher priority, V-for or V-if? How should it be used correctly to avoid performance problems?")]),_v(""), (isFolder)? _l((children),function(child){return _c('p',
[_v(_s(child.title))])}):_e()],2)}})// execute _l
Copy the code
The source code is as follows
Conclusion:
- Obviously v-for is resolved before V-if (tell the interviewer how you know that)
- If it happens at the same time, each render will execute a loop before judging the condition, so the loop is inevitable anyway, wasting performance
- To avoid this, nest the template in the outer layer, do a V-if judgment in this layer, and then do a V-for loop inside
- If conditions occur inside the loop, items that do not need to be displayed can be filtered out ahead of time by evaluating attributes
Note: The opposite is true in VUE3