广瀚云办公
55.99MB · 2025-10-09
nextTick
是 Vue
提供的方法,它会在 DOM
更新完成后执行回调函数。
Vue 内部使用批量处理机制来优化 DOM 更新
主要原因:
引入方式不同
// Vue2
this.$nextTick(() => {
// 操作DOM
});
// Vue3
import { nextTick } from "vue";
nextTick(() => {
// 操作DOM
});
支持 async/await
:
import { ref, nextTick } from "vue";
const message = ref("初始消息");
const content = ref(null);
const updateData = async () => {
message.value = "更新后的消息";
// 等待DOM更新完成
await nextTick();
// 这里可以安全操作DOM了
console.log(content.value.textContent); // "更新后的消息"
content.value.style.color = "red";
};
import { ref, nextTick } from'vue'
const showInput = ref(false)
const inputRef = ref(null)
const openInput = async () => {
showInput.value = true
await nextTick()
inputRef.value.focus() // 确保input已经渲染
}
import { ref, nextTick } from'vue'
const messages = ref([])
const listRef = ref(null)
const addMessage = async (text) => {
messages.value.push(text)
await nextTick()
// 滚动到最新消息
listRef.value.scrollTop = listRef.value.scrollHeight
}
import { ref, nextTick } from'vue'
const isVisible = ref(false)
const elementRef = ref(null)
const showWithAnimation = async () => {
isVisible.value = true
await nextTick()
// 确保元素已经渲染,然后添加动画
elementRef.value.classList.add('fade-in')
}