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() { 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); }
|