跳到内容

useStyleTag

类别
导出大小
497 B
最后更改
5 天前

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

演示

编辑 CSS

ID: vueuse_styletag_1

已加载: false

用法

基本用法

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

js
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 作为第一个参数传递。

js
import { useStyleTag } from '@vueuse/core'

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

媒体查询

您可以将 media 属性作为对象中的最后一个参数传递。

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

类型声明

typescript
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
}
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
mrayi
Jelf

更新日志

v12.8.0 于 2025/3/5
7432f - feat(types): 弃用 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.0.0-beta.1 于 2024/11/21
0a9ed - feat!: 移除 Vue 2 支持,优化捆绑包并清理代码 (#4349)

在 MIT 许可证下发布。