跳到内容

useTitle

类别
导出大小
954 B
最后更改
5 天前

响应式文档标题。

警告

此组合项与 SSR 不兼容。

演示

标题

用法

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

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

立即设置初始标题

js
const title = useTitle('New Title')

传递一个 ref,当源 ref 更改时标题将更新

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

const messages = shallowRef(0)

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

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

传递一个可选的模板标签 Vue Meta Title Template 以更新要注入到此模板中的标题

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

警告

observetitleTemplate 不兼容。

类型声明

显示类型声明
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
/**
 * Reactive document title.
 *
 * @see https://vueuse.org.cn/useTitle
 * @param newTitle
 * @param options
 * @description It's not SSR compatible. Your value will be applied only on client-side.
 */
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>

源代码

SourceDemoDocs

贡献者

Anthony Fu
IlyaL
Anthony Fu
Alex Kozack
Antério Vieira
Yauheni Vasiukevich
Robin
Doctorwu
ClemDee
Eugen Istoc
Levi (Nguyễn Lương Huy)
Preetesh Jain
Michael Roberts

更新日志

v12.8.0 于 3/5/2025
7432f - feat(types): 弃用 MaybeRefMaybeRefOrGetter,支持 Vue 原生 (#4636)
v12.3.0 于 1/2/2025
59f75 - feat(toValue): 弃用 toValue from @vueuse/shared,支持 Vue 原生
v12.0.0-beta.1 于 11/21/2024
0a9ed - feat!: 删除 Vue 2 支持,优化 bundles 并清理 (#4349)
v10.7.0 于 12/5/2023
0ab76 - feat: 在卸载时恢复标题 (#3570)
v10.0.0-beta.5 于 4/13/2023
cb644 - refactor!: 移除 isFunctionisString 工具函数
v10.0.0-beta.4 于 4/13/2023
4d757 - feat(types)!: 将 MaybeComputedRef 重命名为 MaybeRefOrGetter
10e98 - feat(toRef)!: 将 resolveRef 重命名为 toRef

在 MIT 许可证下发布。