$nextTick

$nextTick是一个生命钩子,我们可以理解成,Vue 在更新 DOM 时是异步执行的。当数据发生变化,Vue将开启一个异步更新队列,视图需要等队列中所有数据变化完成之后,再统一进行更新

先简单写一个$nextTick的例子

<template>
	<div class="app">
        <div v-if="isShow">
            <input ref="inp" type="text" v-model="change">
            <button>确定</button>
        </div>
        
        <div v-else>
            <span>{{ title }}</span>
            <button @click="handleChange">编辑</button>
        </div>
	</div>
</template>
<script>
export default {
	name: 'app',
	data(){
        return {
            title:'标题',
            change:'',
            isShow:false
        }
    },
    methods:{
        handleChange(){
            this.isShow = true
        }
    }
}
</script>

在这里插入图片描述
我们的要求是点击编辑展示输入框并立刻获取焦点

handleChange(){
 	this.isShow = true
    this.$ref.inp.focus()
}

要是按照我们正常思维去想的话,我们会直接使用this.$ref.inp.focus()获取
在这里插入图片描述

但是这样会报错,因为Vue是异步更新DOM的,所以我们就需要用到$nextTick

handleChange(){
    this.isShow = true
    this.$nextTick(()=>{
        this.$refs.inp.focus()
    })
}

在这里插入图片描述
下面是$nextTick与setTimeout的区别

<template>
	<div class="app">
        <button @click="func">确定</button>
	</div>
</template>
<script>
export default {
	name: 'app',
    methods:{
        func(){
            console.log(11111111);
            setTimeout(()=>{
                console.log(222222222222);
            })
            this.$nextTick(()=>{
                console.log(33333333333);
            })
            console.log(4444444444);
        }
    }
}
</script>

<style scoped="scoped">
	
</style>

打印结果为
在这里插入图片描述
我们可以看到先打印333333在打印2222222
所以$nextTick比setTimeout先执行

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值