コンテンツにスキップ

useTitle

カテゴリ
エクスポートサイズ
903 B
最終更新日
先週

リアクティブなドキュメントタイトル。

ヒント

Nuxt 3 で使用する場合、この関数は Nuxt の組み込み `useTitle()` を優先して自動インポートされ**ません**。 VueUse の関数を使用する場合は、明示的にインポートしてください。

デモ

タイトル

使用方法

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 { 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 Meta タイトルテンプレート を渡して、このテンプレートに挿入されるタイトルを更新します

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

警告

`observe` は `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>

ソース

ソースデモドキュメント

貢献者

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

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除、バンドルを最適化、クリーンアップ (#4349)
v10.7.0 2023/12/5
0ab76 - feat: アンマウント時にタイトルを復元 (#3570)
v10.0.0-beta.5 2023/4/13
cb644 - refactor!: `isFunction` および `isString` ユーティリティを削除
v10.0.0-beta.4 2023年4月13日
4d757 - feat(types)!: MaybeComputedRefMaybeRefOrGetter に名称変更
10e98 - feat(toRef)!: resolveReftoRef に名称変更
v9.3.1 2022年10月17日
8c1ba - fix: observetitleTemplate が同時に指定されるのを防ぐ (#2049)

MITライセンスの下でリリースされています。