跳到主要內容

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.dev.org.tw/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>

原始碼

SourceDemo文件

貢獻者

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@vueuse/shared,改用 Vue 的原生類型
v12.0.0-beta.1 於 11/21/2024
0a9ed - feat!:移除 Vue 2 支援,優化捆綁包並清理程式碼 (#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 許可證發布。