获取 Vue3 设置脚本中的下一个刻度

nat*_*nat 17 vue.js vuejs3

如何在 vue3 的设置脚本中使用下一个刻度?

<script setup>


const msg = 'Hello!'

this.$nextTick(() => {
   console.log("next tick ... do something")
});

</script>

<template>
  <p>{{ msg }}</p>
</template>
Run Code Online (Sandbox Code Playgroud)

我使用了多种不同的方法,但找不到一种可以在正常脚本标记之外工作的方法。

我尝试的另一种方法是。

import Vue from "vue";

Vue.nextTick(() => {});
Run Code Online (Sandbox Code Playgroud)

Mis*_*ses 41

这是在 Vue 3 中使用的方式nextTick()

<script setup>
import { ref, nextTick } from 'vue'

const count = ref(0)

async function increment() {
  count.value++

  // DOM not yet updated
  console.log(document.getElementById('counter').textContent) // 0

  await nextTick()
  // DOM is now updated
  console.log(document.getElementById('counter').textContent) // 1
}
</script>

<template>
  <button id="counter" @click="increment">{{ count }}</button>
</template>
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到更多信息: https: //vuejs.org/api/general.html#nexttick


jas*_*ram 8

虽然Mises的答案是正确的,但 nextTick() 也可以在没有 async/await 的情况下使用,如下所示:

nextTick().then(() => {
    // DOM is now updated
    console.log("Continue here")
}
Run Code Online (Sandbox Code Playgroud)

我认为这是更好的实践,因为它允许您使用 Promise。