useExternal
用于动态地向页面加载或卸载外部资源
Demo
PrimarySecondarySuccessDangerWarningInfoLightDark
Usage
html
<template>
<div>
<!-- 图片挂载 -->
<div style="width: 200px; height: 200px" ref="parent" />
<button @click="imgLoad">加载 img</button>
<button @click="imgUnload">卸载 img</button>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { useExternal } from '@morehook/core'
// 监听 src 变化自动加载
// const srcRef = ref(
// 'http://img-steward-online.goodaa.com.cn/449c2e5dd6a948e3af67b69c4ece907a.js'
// )
// useExternal(srcRef, el => {
// console.log('加载 js 文件2 成功', el)
// })
// setTimeout(() => {
// srcRef.value = 'https://ahooks.js.org/useExternal/bootstrap-badge.css'
// }, 1000)
// ps: 加载 img 文件
const parent = ref()
const { load: imgLoad, unload: imgUnload } = useExternal(
'https://s6.jpg.cm/2022/08/23/PVSGyi.png',
el => {
console.log('加载 img 文件成功', el)
},
{
manual: true,
target: parent
}
)
</script>
Type Declarations
Show Type Declarations
typescript
type Elements = HTMLScriptElement | HTMLLinkElement | HTMLImageElement
/**
* manual: 是否手动下载 (默认 false)
* async: script 标签属性
* crossOrigin: script 标签属性
* referrerPolicy: script 标签属性
* noModule: script 标签属性
* defer: script 标签属性
* media: link 标签属性 (默认 all)
* target: 资源挂载在哪 (默认 document.body)
*/
interface Options {
manual?: boolean
async?: 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
media?: string
target?: HTMLElement | Ref<HTMLElement> | undefined
}
/**
* 用于动态地向页面加载或卸载外部资源(js,图片,css)
* @param src 下载地址
* @param onLoaded 下载成功回调
* @param options
* @remark 图片需要手动控制下载,否则可能会出现没有及时拿到外部 target 元素
*/
export declare function useExternal(
src: string | Ref<string>,
onLoaded?: (el: Elements) => void,
options?: Options
): {
resources: Ref<Elements | null>
load: () => Promise<unknown>
unload: () => void
}