Analysis of vue common problems (1) priority of v-for and v-if

Background: v-for and v-if are often used in vue, so what is their priority? How can performance optimization be achieved? Here's a brief analysis, how to analyze, please refer to the following test demo, and refer to src/compiler/codegen/index.js in the source code. The demo code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue  v-if  v-for</title>
</head>
<body>
    <div>v-if和v-for哪个优先级更高?如果两个同时出现,应该怎么优化得到更好的性能?源码中找答案src/compiler/codegen/index.js</div>


    <div id="demo">
        <!--用法一,不推荐,先走循环浪费性能-->
        <!-- <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="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        //创建实例
        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>

Execute method 1, view the render function, and get the following results:

Execute method 2, check the rendering function, and get the following results:

It is concluded from the above execution that:

1. v-for is obviously prioritized over v-if to be parsed. If it appears at the same level at the same time, each rendering will execute the loop first and then judge the condition. It can be seen that the performance loss is relatively large, so we can use the second method, in the outer layer Add judgment conditions and inner loops to optimize performance. The following is source code verification:

The above is an in-depth analysis of v-for and v-if in vue. I hope it will be helpful for everyone to understand vue.

Guess you like

Origin blog.csdn.net/wh_xmy/article/details/109594128