useTitle
响应式的文档标题。
WARNING
此组合式函数与 SSR 不兼容。
Demo
Title
用法
js
import { useTitle } from '@vueuse/core'
const title = useTitle()
console.log(title.value) // 打印当前标题
title.value = 'Hello' // 更改当前标题
立即设置初始标题:
js
const title = useTitle('新标题')
传递一个 ref
,当源 ref 更改时标题将更新:
js
import { shallowRef } from 'vue'
import { useTitle } from '@vueuse/core'
const messages = shallowRef(0)
const title = computed(() => {
return !messages.value ? '没有消息' : `${messages.value} 条新消息`
})
useTitle(title) // 文档标题将与 ref "title" 匹配
传递一个可选的模板标签 Vue Meta Title Template 以更新要注入到此模板中的标题:
js
const title = useTitle('新标题', { titleTemplate: '%s | 我的精彩网站' })
WARNING
observe
与 titleTemplate
不兼容。
Type Declarations
Show Type Declarations
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/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>