nextTick使用场景

<template>
    <section>
        <div ref="hello">
            <h1>{{name}}</h1>
        </div>
        <button @click="get">点击</button>
    </section>
</template>

<script>
export default{
    data(){
        return{
            name:'库里'
        }
    },
    created(){
        // 1、created中的同步代码先执行
        console.log(111)
        console.log(this.$refs['hello'])
        // 3、created()里使用this.$nextTick()可以等待dom生成以后再来获取dom对象。
        // 在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
        this.$nextTick(()=>{
            console.log(222)
            console.log(this.$refs['hello']);
        })
    },
    mounted(){
        // mounted 不会承诺所有的子组件也都一起被挂载。如果你希望等到整个视图都渲染完毕,
        // 可以用 vm.$nextTick 替换掉 mounted。
        // mounted中
        console.log(333)
        console.log(this.$refs['hello'])
        // 4、执行完子组件的Mounted后会立即执行父组件的mounted函数,
        // 也就是说mounted函数直接是同步执行的
        //但是我们的页面渲染是一个异步操作
        // 也就说说执行父组件的mounted方法时,页面还没有渲染完成,
        // 所以导致了打印结果不一致
        this.$nextTick(()=>{
            console.log(444)
            console.log(this.$refs['hello'])
        })
    },
    methods:{
        get(){
            this.name='詹姆斯'
        //同步执行代码,此时DOM并未来的及更新 
            console.log(this.$refs['hello'].innerText);
        //在DOM更新后立即执行    
            this.$nextTick(()=>{
                console.log(this.$refs['hello'].innerText)
            })
        }
    }
   }
</script>

初始mounted created之后的执行结果
在这里插入图片描述
点击按钮后的执行结果
在这里插入图片描述
链接:
https://www.shuzhiduo.com/A/rV57yQ6XzP/
https://baijiahao.baidu.com/s?id=1744468847076684281&wfr=spider&for=pc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值