Skip to content

useStyleTag

类别
导出体积
513 B
上次更改
4 months ago

<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; }')
// 以后可以修改样式
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
<!-- 注入到 <head> 中 -->
<style id="custom-id">
  .foo {
    margin-top: 32px;
  }
</style>

媒体查询

你可以在对象中的最后一个参数中传递媒体属性。

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

类型声明

ts
export interface UseStyleTagOptions extends ConfigurableDocument {
  /**
   * 要应用的样式的媒体查询
   */
  
media
?: string
/** * 立即加载样式 * * @default true */
immediate
?: boolean
/** * 手动控制加载和卸载的时机 * * @default false */
manual
?: boolean
/** * 样式标签的 DOM id * * @default 自动递增 */
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>>
} /** * 在头部注入 <style> 元素。 * * 重载:省略了 id * * @see https://vueuse.org/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

更新日志

fa2c0 - feat: support passing nonce (#4749)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
f5a29 - fix: eslint import/newline-after-import