跳到主要内容

useStyleTag

分类
导出大小
513 B
上次更改
5 个月前

在 head 中注入响应式 style 元素。

演示

编辑 CSS

ID: vueuse_styletag_1

已加载: false

用法

基本用法

提供一个 CSS 字符串,然后 useStyleTag 将自动生成一个 id 并将其注入到 <head> 中。

ts
import { 
useStyleTag
} from '@vueuse/core'
const {
id
,
css
,
load
,
unload
,
isLoaded
,
} =
useStyleTag
('.foo { margin-top: 32px; }')
// Later you can modify styles
css
.
value
= '.foo { margin-top: 64px; }'

此代码将注入到 <head>

html
<style id="vueuse_styletag_1">
  .foo {
    margin-top: 64px;
  }
</style>

自定义 ID

如果您需要定义自己的 id,可以将 id 作为第一个参数传入。

ts
useStyleTag
('.foo { margin-top: 32px; }', {
id
: 'custom-id' })
html
<!-- injected to <head> -->
<style id="custom-id">
  .foo {
    margin-top: 32px;
  }
</style>

媒体查询

您可以在对象中作为最后一个参数传入媒体属性。

ts
useStyleTag
('.foo { margin-top: 32px; }', {
media
: 'print' })
html
<!-- injected to <head> -->
<style id="vueuse_styletag_1" media="print">
  .foo {
    margin-top: 32px;
  }
</style>

类型声明

ts
export interface UseStyleTagOptions extends ConfigurableDocument {
  /**
   * Media query for styles to apply
   */
  
media
?: string
/** * Load the style immediately * * @default true */
immediate
?: boolean
/** * Manual controls the timing of loading and unloading * * @default false */
manual
?: boolean
/** * DOM id of the style tag * * @default auto-incremented */
id
?: string
/** * Nonce value for CSP (Content Security Policy) * * @default undefined */
nonce
?: string
} export interface UseStyleTagReturn {
id
: string
css
:
ShallowRef
<string>
load
: () => void
unload
: () => void
isLoaded
:
Readonly
<
ShallowRef
<boolean>>
} /** * Inject <style> element in head. * * Overload: Omitted id * * @see https://vueuse.org.cn/useStyleTag * @param css * @param options */ export declare function
useStyleTag
(
css
:
MaybeRef
<string>,
options
?: UseStyleTagOptions,
): UseStyleTagReturn

来源

源文件演示文档

贡献者

Anthony Fu
sibbng
IlyaL
Anthony Fu
James Wragg
SerKo
BeamDong
mrayi
Jelf

更新日志

v13.2.0
fa2c0 - feat: 支持传入 nonce (#4749)
v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。