Vue 通过 VueUse 的 useStyleTag 实现动态注入 css 样式

Vue 通过 VueUseuseStyleTag 实现动态注入 css 样式,你可以动态加载css文件和css样式。

代码示例

import { useStyleTag } from '@vueuse/core'

let ops={
  id:"itxst",//可选 ID
  media:"screen and (max-width: 2600px)", //可选 媒体查询
  manual:true //是否手动加载CSS
}
const {
  id,
  css,
  load,
  unload,
  isLoaded,
} = useStyleTag('.dock { background: #f6fff0; }',ops)

在线例子

例子

类型定义

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.org/useStyleTag
 * @param css
 * @param options
 */
export declare function useStyleTag(
  css: MaybeRef<string>,
  options?: UseStyleTagOptions,
): UseStyleTagReturn