callOnce

在服务器端渲染 (SSR) 或客户端渲染 (CSR) 期间运行一次给定的函数或代码块。
此实用程序自 Nuxt v3.9 起可用。

用途

¥Purpose

callOnce 函数旨在在以下情况下仅执行一次给定函数或代码块:

¥The callOnce function is designed to execute a given function or block of code only once during:

  • 服务器端渲染,但不进行数据融合
  • 客户端导航

这对于只应执行一次的代码很有用,例如记录事件或设置全局状态。

¥This is useful for code that should be executed only once, such as logging an event or setting up a global state.

用法

¥Usage

callOnce 的默认模式是仅运行一次代码。例如,如果代码在服务器上运行,它将不会在客户端再次运行。如果你在客户端多次调用 callOnce,例如导航回此页面,它也不会再次运行。

¥The default mode of callOnce is to run code only once. For example, if the code runs on the server it won't run again on the client. It also won't run again if you callOnce more than once on the client, for example by navigating back to this page.

app.vue
<script setup lang="ts">
const websiteConfig = useState('config')

await callOnce(async () => {
  console.log('This will only be logged once')
  websiteConfig.value = await $fetch('https://my-cms.com/api/website-config')
})
</script>

它也可以在每个导航中运行,同时避免初始服务器/客户端双重加载。对于 webpack 用户,请参阅 navigation

¥It is also possible to run on every navigation while still avoiding the initial server/client double load. For this, it is possible to use the navigation mode:

app.vue
<script setup lang="ts">
const websiteConfig = useState('config')

await callOnce(async () => {
  console.log('This will only be logged once and then on every client side navigation')
  websiteConfig.value = await $fetch('https://my-cms.com/api/website-config')
}, { mode: 'navigation' })
</script>
navigation 模式自 Nuxt v3.15 起可用。
callOncePinia 模块 结合使用时可用于调用存储操作。¥callOnce is useful in combination with the Pinia module to call store actions.
Read more in Docs > Getting Started > State Management.
请注意,callOnce 不会返回任何内容。如果你想在服务器端渲染 (SSR) 期间进行数据获取,则应使用 useAsyncDatauseFetch。¥Note that callOnce doesn't return anything. You should use useAsyncData or useFetch if you want to do data fetching during SSR.
callOnce 是一个可组合函数,旨在直接在设置函数、插件或路由中间件中调用,因为它需要将数据添加到 Nuxt 负载中,以避免在页面数据合并时在客户端重新调用该函数。

类型

¥Type

callOnce (key?: string, fn?: (() => any | Promise<any>), options?: CallOnceOptions): Promise<void>
callOnce(fn?: (() => any | Promise<any>), options?: CallOnceOptions): Promise<void>

type CallOnceOptions = {
  /**

   * Execution mode for the callOnce function

   * @default 'render'
   */
  mode?: 'navigation' | 'render'
}

参数

¥Parameters

  • key:一个唯一键,用于确保代码只运行一次。如果你未提供密钥,那么系统将为你生成一个与 callOnce 实例的文件和行号唯一的密钥。
  • fn:要运行一次的函数。它可以是异步的。
  • options:设置模式,可在导航时重新执行(navigation),或在应用生命周期内仅执行一次(render)。默认为 render
    • render:在初始渲染(服务器端渲染或客户端渲染)期间执行一次 - 默认模式
    • navigation:在初始渲染期间执行一次,并在后续的客户端导航中执行一次