跳到主要内容

useScriptTag

分类
导出大小
1.16 kB
上次更改
4 个月前

创建一个脚本标签,支持在卸载时自动卸载(删除)脚本标签。

如果给定 URL 的脚本标签已存在,useScriptTag() 将不会创建另一个脚本标签,但请记住,根据您的使用方式,useScriptTag() 可能已从先前的 useScriptTag() 调用中加载然后卸载了该特定 JS 文件。

用法

ts
import { 
useScriptTag
} from '@vueuse/core'
useScriptTag
(
'https://player.twitch.tv/js/embed/v1.js', // on script tag loaded. (
el
: HTMLScriptElement) => {
// do something }, )
js
import { useScriptTag } from '@vueuse/core'
useScriptTag(
  'https://player.twitch.tv/js/embed/v1.js',
  // on script tag loaded.
  (el) => {
    // do something
  },
)

该脚本将在组件挂载时自动加载,并在组件卸载时移除。

配置

设置 manual: true 以手动控制脚本加载的时机。

ts
import { 
useScriptTag
} from '@vueuse/core'
const {
scriptTag
,
load
,
unload
} =
useScriptTag
(
'https://player.twitch.tv/js/embed/v1.js', () => { // do something }, {
manual
: true },
) // manual controls await
load
()
await
unload
()

类型声明

显示类型声明
ts
export interface UseScriptTagOptions extends ConfigurableDocument {
  /**
   * Load the script immediately
   *
   * @default true
   */
  
immediate
?: boolean
/** * Add `async` attribute to the script tag * * @default true */
async
?: boolean
/** * Script type * * @default 'text/javascript' */
type
?: string
/** * Manual controls the timing of loading and unloading * * @default false */
manual
?: boolean
crossOrigin
?: "anonymous" | "use-credentials"
referrerPolicy
?:
| "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url"
noModule
?: boolean
defer
?: boolean
/** * Add custom attribute to the script tag * */
attrs
?:
Record
<string, string>
/** * Nonce value for CSP (Content Security Policy) * @default undefined */
nonce
?: string
} /** * Async script tag loading. * * @see https://vueuse.org.cn/useScriptTag * @param src * @param onLoaded * @param options */ export declare function
useScriptTag
(
src
:
MaybeRefOrGetter
<string>,
onLoaded
?: (
el
: HTMLScriptElement) => void,
options
?: UseScriptTagOptions,
): {
scriptTag
:
ShallowRef
<HTMLScriptElement | null, HTMLScriptElement | null>
load
: (
waitForScriptLoad
?: boolean) =>
Promise
<HTMLScriptElement | boolean>
unload
: () => void
} export type
UseScriptTagReturn
=
ReturnType
<typeof
useScriptTag
>

来源

源文件文档

贡献者

Anthony Fu
Anthony Fu
IlyaL
Denis Blazhkun
BeamDong
Robin
Fernando Fernández
Robin
Craig Riley
David B Ludlow
Levi (Nguyễn Lương Huy)
Tomáš Livora
webfansplz
Preston Alvarado
Shinigami
Alex Kozack
Yaël GUILLOUX

更新日志

v13.4.0
57370 - 修复:支持传递 nonce (#4753)
v12.8.0
7432f - feat(types): 废弃 MaybeRefMaybeRefOrGetter,转而使用 Vue 的原生类型 (#4636)
v12.5.0
c6c6e - feat: 在未使用 useEventListener 的地方使用它 (#4479)
v12.3.0
59f75 - feat(toValue): 废弃 @vueuse/shared 中的 toValue,转而使用 Vue 的原生函数
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。