跳到主要内容

useTitle

分类
导出大小
912 B
上次更改
8 个月前

响应式文档标题。

警告

此可组合函数与 SSR 不兼容。

演示

用法

ts
import { 
useTitle
} from '@vueuse/core'
const
title
=
useTitle
()
console
.
log
(
title
.
value
) // print current title
title
.
value
= 'Hello' // change current title

立即设置初始标题

ts
const 
title
=
useTitle
('New Title')

传入一个 ref,当源 ref 改变时,标题将更新。

ts
import { 
useTitle
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
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 标题模板,以更新要注入此模板的标题。

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

警告

observetitleTemplate 不兼容。

类型声明

显示类型声明
ts
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
>

来源

源码示例文档

贡献者

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

更新日志

v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v10.7.0
0ab76 - feat: 卸载时恢复标题 (#3570)

根据 MIT 许可证发布。