Skip to content

useTitle

反应式文档标题。

¥Reactive document title.

提示

当与 Nuxt 3 一起使用时,该函数不会自动导入,而是使用 Nuxt 的内置 useTitle()。如果你想使用 VueUse 中的函数,请使用显式导入。

¥When using with Nuxt 3, this function will NOT be auto imported in favor of Nuxt's built-in useTitle(). Use explicit import if you want to use the function from VueUse.

示例

Title

用法

¥Usage

js
import { useTitle } from '@vueuse/core'

const title = useTitle()
console.log(title.value) // print current title
title.value = 'Hello' // change current title

立即设置初始标题:

¥Set initial title immediately:

js
const title = useTitle('New Title')

通过 ref,标题将在源引用更改时更新:

¥Pass a ref and the title will be updated when the source ref changes:

js
import { useTitle } from '@vueuse/core'

const messages = ref(0)

const title = computed(() => {
  return !messages.value ? 'No message' : `${messages.value} new messages`
})

useTitle(title) // document title will match with the ref "title"

传递一个可选的模板标签 Vue 元标题模板 来更新要注入到该模板中的标题:

¥Pass an optional template tag Vue Meta Title Template to update the title to be injected into this template:

js
const title = useTitle('New Title', { titleTemplate: '%s | My Awesome Website' })

警告

observetitleTemplate 不兼容。

¥observe is incompatible with titleTemplate.

类型声明

显示类型声明
typescript
export type UseTitleOptionsBase = {
  /**
   * Restore the original title when unmounted
   * @param originTitle original title
   * @returns restored title
   */
  restoreOnUnmount?:
    | false
    | ((
        originalTitle: string,
        currentTitle: string,
      ) => string | null | undefined)
} & (
  | {
      /**
       * Observe `document.title` changes using MutationObserve
       * Cannot be used together with `titleTemplate` option.
       *
       * @default false
       */
      observe?: boolean
    }
  | {
      /**
       * The template string to parse the title (e.g., '%s | My Website')
       * Cannot be used together with `observe` option.
       *
       * @default '%s'
       */
      titleTemplate?: MaybeRef<string> | ((title: string) => string)
    }
)
export type UseTitleOptions = ConfigurableDocument & UseTitleOptionsBase
export declare function useTitle(
  newTitle: ReadonlyRefOrGetter<string | null | undefined>,
  options?: UseTitleOptions,
): ComputedRef<string | null | undefined>
export declare function useTitle(
  newTitle?: MaybeRef<string | null | undefined>,
  options?: UseTitleOptions,
): Ref<string | null | undefined>
export type UseTitleReturn = ReturnType<typeof useTitle>

源代码

源代码示例文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号