Skip to content

useTitle

类别
导出体积
903 B
上次更改
2 minutes ago

响应式的文档标题。

TIP

在 Nuxt 3 中使用时,此函数将不会自动导入,而是使用 Nuxt 内置的 useTitle()。 如果要从 VueUse 使用该函数,请显式导入。

示例

Title

用法

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

const title = useTitle()
console.log(title.value) // 打印当前标题
title.value = 'Hello' // 更改当前标题

立即设置初始标题:

js
const title = useTitle('New Title')

传递一个 ref,当源 ref 发生变化时,标题将被更新:

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

const messages = ref(0)

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

useTitle(title) // 文档标题将与 ref "title" 匹配

传递一个可选的模板标记 Vue Meta Title Template 来更新要注入到该模板中的标题:

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

WARNING

observetitleTemplate 不兼容。

类型声明

显示类型声明
typescript
export type UseTitleOptionsBase = {
  /**
   * 在组件卸载时恢复原始标题
   * @param originTitle 原始标题
   * @returns 恢复的标题
   */
  restoreOnUnmount?:
    | false
    | ((
        originalTitle: string,
        currentTitle: string,
      ) => string | null | undefined)
} & (
  | {
      /**
       * 使用 MutationObserve 观察 `document.title` 的变化
       * 不能与 `titleTemplate` 选项一起使用。
       *
       * @default false
       */
      observe?: boolean
    }
  | {
      /**
       * 用于解析标题的模板字符串(例如,'%s | My Website')
       * 不能与 `observe` 选项一起使用。
       *
       * @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>

源码

源码演示文档

贡献者

Anthony Fu
一纸忘忧
Alex Kozack
Antério Vieira
Anthony Fu
Doctorwu
ClemDee
Eugen Istoc
Levi (Nguyễn Lương Huy)
Preetesh Jain
Michael Roberts

更新日志

v10.7.0 on 12/5/2023
0ab76 - feat: restore title on unmounted (#3570)
v10.0.0-beta.5 on 4/13/2023
cb644 - refactor!: remove isFunction and isString utils
v10.0.0-beta.4 on 4/13/2023
4d757 - feat(types)!: rename MaybeComputedRef to MaybeRefOrGetter
10e98 - feat(toRef)!: rename resolveRef to toRef
v9.3.1 on 10/17/2022
8c1ba - fix: prevent observe and titleTemplate been specified at the same time (#2049)