Vue nextTick 應用場景與實踐

前言

當使用 Vue.js 開發應用時,nextTick 是一個非常有用的方法,當資料變化時 Vue 會異步更新 DOM,有時候你可能會在資料改變後立即嘗試訪問 DOM,卻發現其實 DOM 還沒有更新。為了解決這個問題,nextTick 可以讓你在下次 DOM 更新循環後執行一段代碼,可以幫助你在 DOM 更新後執行某些操作。

基本用法

以下是在 Vue 中使用 nextTick 的一個方法,用於在 DOM 更新後執行操作

1
2
3
4
5
6
<template>
<div>
<input v-if="inputState" ref="inputText" type="text" :value="text">
<button type="button" @click="inputHandler">隱藏/顯示</button>
</div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<script>
export default {
name: 'App',
data() {
return {
text: 'Hello Vue!',
inputState: true,
}
},
created() {
// 當元件建立完成時,自動 focus 到 input
this.$nextTic(() => {
this.$refs.inputText.focus()
})
},
methods: {
inputHandler() {
this.inputState = !this.inputState
if (this.inputState) {
this.$nextTic(() => {
this.$refs.inputText.focus()
})
}
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<script>
import { ref, onMounted, nextTick } from 'vue';

export default {
name: 'App',
setup() {
const text = ref('Hello Vue!');
const inputState = ref(true);
const inputText = ref(null);

const inputHandler = () => {
inputState.value = !inputState.value;
if (inputState.value) {
nextTick(() => {
inputText.value.focus();
});
}
};

onMounted(() => {
nextTick(() => {
inputText.value.focus();
});
});

return {
text,
inputState,
inputHandler,
inputText,
};
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script setup>
import { ref, onMounted, nextTick } from 'vue';

const text = ref('Hello Vue!');
const inputState = ref(true);
const inputText = ref(null);

const inputHandler = () => {
inputState.value = !inputState.value;
if (inputState.value) {
nextTick(() => {
inputText.value.focus();
});
}
};

onMounted(() => {
nextTick(() => {
inputText.value.focus();
});
});
</script>

在這個範例中,會等到 input 顯示後才會自動 focus,確保用戶可以立即輸入內容。

注意事項

  • 在 Vue 2 中使用 nextTick 前面要加上 $
  • nextTick 可以接受一個回調函數,這個回調會在 DOM 更新完成後被調用。
  • 你也可以使用 Promise 語法來處理 nextTick,這在使用 async/await 時特別方便:
1
2
3
4
5
async updateMessage() {
this.message = 'Hello Async Next Tick!';
await this.$nextTic();
console.log('DOM updated (async):', this.$el.textContent);
}

總結

nextTick 是一個強大的工具,可以幫助你在 Vue 應用中確保在 DOM 更新後執行代碼。合理使用 nextTick 可以提高應用的穩定性和性能,特別是在處理複雜的 UI 更新時。希望這些筆記能幫助你更好地理解和運用 nextTick