【Vue】nextTick

文章讲述了在Vue3中,由于DOM更新是异步的,如何使用`nextTick`解决聊天发送消息后,新消息无法立即滚动到底部的问题,介绍了三种使用`nextTick`的方法:回调函数、await/then和`onUpdated`监听。
摘要由CSDN通过智能技术生成

Vue3 中的 nextTick

将同步语句转换为异步,即当 DOM 异步结束更新之后,再执行的语句。

先写一个简易的聊天发送框:

<template>
  <div ref="box" class="wraps">
      <div class="item" v-for="item in chatList">
        <div>{{ item.name }}:</div>
        <div>{{ item.message }}</div>
      </div>
  </div>
  <div class="ipt">
      <textarea v-model="ipt" type="text" />
      <button @click="send">send</button>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, nextTick, getCurrentInstance, watch } from 'vue'
let chatList = reactive([
  { name: '张三', message: "xxxxxxxxx" },
])
let ipt = ref('')
const send = () => {
  chatList.push({ name: '李四', message: ipt.value })
  // 为了演示,先不清除ipt框内数据
  // ipt.value = ''
}
</script>
 
<style scoped lang='less'>
.wraps {
  margin: 10px auto;
  width: 500px;
  height: 400px;
  overflow: auto;
  overflow-x: hidden;
  background: #fff;
  border: 1px solid #ccc;

  .item {
    width: 100%;
    height: 50px;
    background: #ccc;
    display: flex;
    align-items: center;
    padding: 0 10px;
    border-bottom: 1px solid #fff;
  }
}

.ipt {
  margin: 10px auto;
  width: 500px;
  height: 40px;
  background: #fff;
  border: 1px solid #ccc;

  textarea {
    // 使完全贴合 .ipt
    width: 100%;
    height: 100%;
    border: none;
    outline: none;
  }

  button {
    width: 100px;
    margin: 10px 0;
    float: right;
  }
}
</style>

在这里插入图片描述

但是信息总是保持处于最上面,不能移动到最后最新发送的信息处。

按照我们的逻辑,只需要让最后的可视区到内容顶部的距离为无限大即可看到最新信息。

<template>
  <div ref="box" class="wraps">
    <div class="item" v-for="item in chatList">
      <div>{{ item.name }}:</div>
      <div>{{ item.message }}</div>
    </div>
  </div>
  <div class="ipt">
    <textarea v-model="ipt" type="text" />
    <button @click="send">send</button>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, nextTick, getCurrentInstance, watch } from 'vue'
const chatList = reactive([
  { name: '张三', message: "xxxxxxxxx" },
])
const ipt = ref('')
// 用 ref 获取 box 元素
const box = ref<HTMLDivElement>()
const send = () => {
  chatList.push({ name: '李四', message: ipt.value })
  // 为了演示,先不清除ipt框内数据
  // ipt.value = ''
  // scrollTop 元素的内容顶部(卷起来的)到它的视口可见内容(的顶部)的距离的度量
  box.value!.scrollTop = 99999
}
</script>
 
<style scoped lang='less'>
.wraps {
  margin: 10px auto;
  width: 500px;
  height: 400px;
  overflow: auto;
  overflow-x: hidden;
  background: #fff;
  border: 1px solid #ccc;

  .item {
    width: 100%;
    height: 50px;
    background: #ccc;
    display: flex;
    align-items: center;
    padding: 0 10px;
    border-bottom: 1px solid #fff;
  }
}

.ipt {
  margin: 10px auto;
  width: 500px;
  height: 40px;
  background: #fff;
  border: 1px solid #ccc;

  textarea {
    // 使完全贴合 .ipt
    width: 100%;
    height: 100%;
    border: none;
    outline: none;
  }

  button {
    width: 100px;
    margin: 10px 0;
    float: right;
  }
}
</style>

在这里插入图片描述

但是发现,此时只是到达最新发出的信息的前一条信息。

原因是:Vue 更新 DOM 是异步的,而数据更新是同步的。

但上述执行的是同步代码,因此出现问题。

所以就需要我们使用 nextTick

<template>
  <div ref="box" class="wraps">
    <div class="item" v-for="item in chatList">
      <div>{{ item.name }}:</div>
      <div>{{ item.message }}</div>
    </div>
  </div>
  <div class="ipt">
    <textarea v-model="ipt" type="text" />
    <button @click="send">send</button>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, nextTick, getCurrentInstance, watch } from 'vue'
const chatList = reactive([
  { name: '张三', message: "xxxxxxxxx" },
])
const ipt = ref('')
// 用 ref 获取 box 元素
const box = ref<HTMLDivElement>()
const send = async () => {
  chatList.push({ name: '李四', message: ipt.value })
  // 为了演示,先不清除ipt框内数据
  // ipt.value = ''
  // scrollTop 元素的内容顶部(卷起来的)到它的视口可见内容(的顶部)的距离的度量

  // 写法一:回调函数模式
  // nextTick(() => {
  //   box.value!.scrollTop = 99999
  // })
  // 写法二:async 和 await  await 下面的代码都是异步的
  // 同时,因为支持 async 和 await,所以返回就是一个 Promise,也支持 .then() 的写法 nextTick().then(()=>{})
  await nextTick()
  box.value!.scrollTop = 99999
}
// 写法三:使用 onUpdated 监听
// onUpdated(() => {
//   box.value!.scrollTop = 99999
// })
</script>
 
<style scoped lang='less'>
.wraps {
  margin: 10px auto;
  width: 500px;
  height: 400px;
  overflow: auto;
  overflow-x: hidden;
  background: #fff;
  border: 1px solid #ccc;

  .item {
    width: 100%;
    height: 50px;
    background: #ccc;
    display: flex;
    align-items: center;
    padding: 0 10px;
    border-bottom: 1px solid #fff;
  }
}

.ipt {
  margin: 10px auto;
  width: 500px;
  height: 40px;
  background: #fff;
  border: 1px solid #ccc;

  textarea {
    // 使完全贴合 .ipt
    width: 100%;
    height: 100%;
    border: none;
    outline: none;
  }

  button {
    width: 100px;
    margin: 10px 0;
    float: right;
  }
}
</style>

在这里插入图片描述

成功解决!

总结:操作 DOM 的时候,如果发现数据读取的是上次的,就需要使用 nextTick 。

那么,为什么 Vue 更新 DOM 是要做成异步的的呢?这里我先举一个小栗子:

const current = ref(0)
watch(current, (newVal, oldVal) => {
  console.log(newVal, oldVal);
})
for (let i = 0; i < 10000; i++) {
  current.value = i
}

在这里插入图片描述
结果只输出了最终结果这一次,节省了性能,但后果就是我们操作 DOM 的时候需要把它放到微任务里面,此时的解决方法就是使用 nextTick

Vue2 中的 $nextTick

$nextTick等 DOM更新后,才会触发执行此方法里的函数体

语法: this.$nextTick(函数体)

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

注意:$nextTick 内的函数体 一定是箭头函数,这样才能让函数内部的this指向Vue实例。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小秀_heo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值