vue中操作dom没有及时更新时,可以使用nextTick()
滚动条没有到最底部
添加nextTick()之后
<template>
<div>
<div class="box" ref="box">
<span v-for="item in list" :key="item"><div>{{item}}</div></span>
</div>
<button @click="add">send</button>
</div>
</template>
<script setup lang="ts">
import {ref,nextTick} from 'vue'
const list=ref<string[]>(['1111','22222'])
const box=ref<HTMLElement>()
//vue更新dom是异步,数据更新是同步
//本次执行代码是同步代码 因此需要使用nextTick
const add = () => {
list.value.push('33333')
//dom更新不及时 没有滚动条没有滑动到最底部
box.value!.scrollTop=9999999
}
</script>
<style scoped>
.box{
height: 100px;
width: 200px;
overflow: auto;
border: 1px solid #000;
margin-bottom: 30px;
}
</style>
1.回调函数写法
const add =async () => {
list.value.push('33333')
nextTick(()=>{
box.value!.scrollTop=9999999
})
}
2.await写法
const add =async () => {
list.value.push('33333')
await nextTick()
box.value!.scrollTop=9999999
}