关于Vue2里 v-for和v-if一起用的时候会出现的问题

2 篇文章 0 订阅

关于Vue2里 v-for和v-if一起用的时候会出现的问题

🎉🎉🎉欢迎来到我的博客,我是一名自学了2年半前端的大一学生,熟悉的技术是JavaScript与Vue.目前正在往全栈方向前进, 如果我的博客给您带来了帮助欢迎您关注我,我将会持续不断的更新文章!!!🙏🙏🙏

在这里插入图片描述

1.介绍

在vue2里 v-forv-if一起用会出现一些不可预料的问题,因为v-for的优先级会比v-if要高,所以v-if会在每个for循环里面都会执行,当你需要根据条件渲染文本的时候,文本可能会渲染多次.

在vue2官方文档里面是这样描述这个问题的:

在这里插入图片描述

2.案例

这是我同学在学习vue2过程中遇到的该问题.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            #app {
                width: 600px;
                margin: auto;
            }
            .tb {
                border-collapse: collapse;
            }
            .tb tr th {
                color: white;
            }
            .tb tr th,
            .tb tr td {
                padding: 5px 40px;
                border: 1px solid #5e5e5e;
                text-align: center;
            }
            .tb tr:nth-child(1) {
                background-color: rgb(94, 188, 255);
            }
        </style>
    </head>
    <body>
        <div id="app">
            <table>
                <table class="tb">
                    <tr>
                        <th>编号</th>
                        <th>品牌名称</th>
                        <th>创立时间</th>
                        <th>操作</th>
                    </tr>
                    <!-- 循环渲染的元素tr -->
                    <tr v-if="list.length > 2" v-for="(item,index) in list" :key="item.id">
                        <td>{{index+1}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.time}}</td>
                        <td>
                            <button @click="del(item.id)">删除</button>
                        </td>
                    </tr>
                    <tr v-else>
                        <td colspan="4">没有数据咯~</td>
                    </tr>
                </table>
            </table>
        </div>
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.13/vue.js"></script>
        <script>
            const app = new Vue({
                el: "#app",
                data: {
                    list: [
                        { id: +new Date(), name: "奔驰", time: "2020 - 05 - 01" },
                        { id: +new Date() + 1, name: "宝马", time: "2024 - 02 - 09" },
                        { id: +new Date() + 2, name: "奥迪", time: "2021 - 08 - 03" },
                    ],
                },
                methods: {
                    del(id) {
                        this.list = this.list.filter(item => item.id != id);
                    },
                },
            });
        </script>
    </body>
</html>

可以看到模板里面很明显的同时使用了v-for和v-if,但看表面逻辑是没有什么问题的,接下来我们看一下渲染结果和逻辑是否正确.
在这里插入图片描述

逻辑看起来是对的 当list.length > 2时正常显示 当 list.length<=2时显示没有数据咯

但是为什么没有数据咯渲染了两次呢?

要知道这个问题是怎么造成的我们首先要知道vue的渲染逻辑

原理解析

vue的渲染逻辑无非就是 解析#app里面的html模板将它转换为ast语法树 再通过将语法树转换为render函数

render函数里面包含 _v _s _ c _l _m这几个方法

上面的案例编译出来的render函数如下

(function anonymous() {
    with (this) {
        return _c('div', {
            attrs: {
                "id": "app"
            }
        }, [_c('table'), _c('table', {
            staticClass: "tb"
        }, [_c('tbody', [_m(0), _v(" "), _l((list), function(item, index) {
            return (list.length > 2) ? _c('tr', {
                key: item.id
            }, [_c('td', [_v(_s(index + 1))]), _v(" "), _c('td', [_v(_s(item.name))]), _v(" "), _c('td', [_v(_s(item.time))]), _v(" "), _c('td', [_c('button', {
                on: {
                    "click": function($event) {
                        return del(item.id)
                    }
                }
            }, [_v("删除")])])]) : _c('tr', [_c('td', {
                attrs: {
                    "colspan": "4"
                }
            }, [_v("没有数据咯~")])])
        })], 2)])])
    }
}
)

  • _v:创建文本节点
  • _s:替换变量为一个文本,变量的值从Vue里面的data对象拿
  • _c:创建一个dom节点
  • _l:v-for的实现
  • _m:标识静态render函数,静态render就是渲染时没用到动态数据的 所以渲染结果永远不会变

可以看到,因为v-for的优先级比v-if高 所以就算list.length <= 2 了 v-for还是会循环两次 而不是直接进入v-for在这里插入图片描述

所以v-else里面的内容会渲染两次

这样上面的渲染结果就说的通了,那该怎么解决这种问题呢?

解决办法1

上面的逻辑无非就是在list.length小于等于2的时候显示没有数据咯 那我们就不要在模板里面编写逻辑 在del方法里面编写逻辑 当list.length小于等于2的时候直接把list清空 然后没有数据咯的显示条件就是list.length === 0.

代码实现:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <style>
            #app {
                width: 600px;
                margin: auto;
            }
            .tb {
                border-collapse: collapse;
            }
            .tb tr th {
                color: white;
            }
            .tb tr th,
            .tb tr td {
                padding: 5px 40px;
                border: 1px solid #5e5e5e;
                text-align: center;
            }
            .tb tr:nth-child(1) {
                background-color: rgb(94, 188, 255);
            }
        </style>
    </head>
    <body>
        <div id="app">
            <table>
                <table class="tb">
                    <tr>
                        <th>编号</th>
                        <th>品牌名称</th>
                        <th>创立时间</th>
                        <th>操作</th>
                    </tr>
                    <!-- 循环渲染的元素tr -->
                    <tr v-for="(item,index) in list" :key="item.id">
                        <td>{{index+1}}</td>
                        <td>{{item.name}}</td>
                        <td>{{item.time}}</td>
                        <td>
                            <button @click="del(item.id)">删除</button>
                        </td>
                    </tr>
                    <tr v-if="list.length === 0">
                        <td colspan="4">没有数据咯~</td>
                    </tr>
                </table>
            </table>
        </div>
        <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.13/vue.js"></script>
        <script>
            const app = new Vue({
                el: "#app",
                data: {
                    list: [
                        { id: +new Date(), name: "奔驰", time: "2020 - 05 - 01" },
                        { id: +new Date() + 1, name: "宝马", time: "2024 - 02 - 09" },
                        { id: +new Date() + 2, name: "奥迪", time: "2021 - 08 - 03" },
                    ],
                },
                methods: {
                    del(id) {
                        this.list = this.list.filter(item => item.id != id);
                        if (this.list.length <= 2) this.list = [];
                    },
                },
            });
        </script>
    </body>
</html>

页面逻辑如下

在这里插入图片描述

可以看到逻辑已经正常了.

解决办法2

仔细看看上面的渲染逻辑 因为v-else只要上面的v-if没成立 就会进入v-else 所以才会渲染两次v-else

所以我们只要把v-else改成v-if=“list.length === 2” 就可以了, 相当于两个if分开了 这样v-for循环就只会执行一个if而不是第一个if没成立就直接用v-else 这样render函数就会变成:

(function anonymous() {
    with (this) {
        return _c('div', {
            attrs: {
                "id": "app"
            }
        }, [_c('table'), _c('table', {
            staticClass: "tb"
        }, [_c('tbody', [_m(0), _v(" "), _l((list), function(item, index) {
            return (list.length > 2) ? _c('tr', {
                key: item.id
            }, [_c('td', [_v(_s(index + 1))]), _v(" "), _c('td', [_v(_s(item.name))]), _v(" "), _c('td', [_v(_s(item.time))]), _v(" "), _c('td', [_c('button', {
                on: {
                    "click": function($event) {
                        return del(item.id)
                    }
                }
            }, [_v("删除")])])]) : _e()
        }), _v(" "), (list.length === 2) ? _c('tr', [_c('td', {
            attrs: {
                "colspan": "4"
            }
        }, [_v("没有数据咯~")])]) : _e()], 2)])])
    }
}
)

其中_e()是创建一个空文本节点也就是条件不满足的时候渲染一个空节点并把他标识为注释 到时候渲染的时候该节点就会被渲染成一个html注释

3.结语

vue2里面的渲染逻辑还是有些小问题 不过在Vue3里面已经全面修复了并且大幅提升了渲染性能,所以在2024年的今天还是推荐大家使用Vue3

Hi👋,这里是瑞雨溪->一个喜欢JavaScript和Vue的大学生,如果我的文章给你带来的帮助,欢迎您关注我我会持续不断的更新更多优质文章.你的关注就是我的动力!!!🎉🎉🎉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瑞雨溪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值