コンテンツにスキップ

useStyleTag

カテゴリ
エクスポートサイズ
474 バイト
最終更新日
先週

リアクティブな`style`要素をheadに挿入します。

デモ

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>

メディアクエリ

メディア属性をオブジェクト内の最後の引数として渡すことができます。

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: Ref<string>
  load: () => void
  unload: () => void
  isLoaded: Readonly<Ref<boolean>>
}
/**
 * Inject <style> element in head.
 *
 * Overload: Omitted id
 *
 * @see https://vueuse.dokyumento.jp/useStyleTag
 * @param css
 * @param options
 */
export declare function useStyleTag(
  css: MaybeRef<string>,
  options?: UseStyleTagOptions,
): UseStyleTagReturn

ソース

ソースデモドキュメント

貢献者

Anthony Fu
sibbng
James Wragg
Anthony Fu
mrayi
Jelf

変更履歴

v12.0.0-beta.1 2024/11/21
0a9ed - feat!: Vue 2 のサポートを削除、バンドルを最適化、クリーンアップ (#4349)
v9.7.0 2022/12/16
cfcc2 - fix: 複数行の CSS を許可 (#2476)
v9.6.0 2022/11/22
94413 - fix: 既存ノードの使用を許可 (#2442)

MITライセンスでリリースされています。