v-if和v-for

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="author" content="杨欣">
    <title>v-if和v-for</title>
</head>

<body>
    <div id="app">
        <p v-if="hasFlag" v-for="(list, index) in lists" :key="index">{{list.title}}</p>
        <!-- <template v-if="hasFlag">
            <p v-for="(list, index) in lists" :key="index">{{list.title}}</p>
        </template> -->
    </div>

    <script src="./dist/vue.js"></script>
    <script>
        let app = new Vue({
            el: "#app",
            data: {
                lists: [
                    { title: 123 },
                    { title: 456 }
                ]
            },
            computed: {
                hasFlag() {
                    return this.lists && this.lists.length > 0
                }
            },
        })
        console.log(app.$options.render);
        // ƒ anonymous(
        // ) {
        //     with (this) { return _c('div', { attrs: { "id": "app" } }, _l((lists), function (list, index) { return (hasFlag) ? _c('p', { key: index }, [_v(_s(list.title))]) : _e() })) }
        // }

        // 1、v-for优先于v-if被解析
        // 2、如果同时出现,每次渲染都会先执行循环再判断条件,无论如何循环都不可避免,浪费了性能
        // 3、要避免出现这种情况,则在外层嵌套template,在这一层进行v-if判断,然后在内部进行v-for循环
        // 4、如果条件出现在循环内部,可通过计算属性提前过滤掉那些不需要显示的项

    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/samsara-yx/p/12689819.html