Vue之nextTick的用法

首先我们需要知道:
Vue是异步渲染
date改变之后,Dom并不会立即渲染
$nextTick会在Dom渲染之后被触发,从而获取最新的Dom

下面先看没有用$nextTick方法获取刚更新的Dom

<template>
    <div>
        <button @click="newAdd">新增+</button>
        <!-- ------------------------------- -->
        <ul ref="uls">
            <li v-for="(item, index) in list" :key="index">{{ item }}</li>
        </ul>
    </div>
</template>

<script>
export default {
    data() {
        return {
            list: [1, 2, 3],
        };
    },
    methods: {
        newAdd() {
            this.list.push(parseInt(Math.random() * 10));
            this.list.push(parseInt(Math.random() * 10));
            this.list.push(parseInt(Math.random() * 10));

            const u = this.$refs.uls;
            console.log(u.childNodes.length);
        },
    },
};
</script>

呈现的页面如下:ul下有三个默认子元素li
当点击新增按钮,会向数组中追加三个随机数并立即打印
当前Dom的子元素长度

在这里插入图片描述
当我们点击了新增,页面的确是渲染出了最新的数据,
但是打印出的Dom子元素长度为3
这里的3其实是默认的三个元素的长度,而最新追加进去的三个并没有被计算
在这里插入图片描述
这时候我们在试试用$nextTick
很简单,只是在定义变量和打印的外面包裹上了$nextTick
这个时候再次点击,发现一切正常,没有出现问题

 methods: {
        newAdd() {
            this.list.push(parseInt(Math.random() * 10));
            this.list.push(parseInt(Math.random() * 10));
            this.list.push(parseInt(Math.random() * 10));

            this.$nextTick(() => {
                const u = this.$refs.uls;
                console.log(u.childNodes.length);
            })
        },
    },

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值