diff --git a/README.md b/README.md index d2d93e4..428cec7 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,33 @@ | conf | 配置更新 | conf: 项目 base 路径 | | chore | 其他 | chore: 其他 | +## 全局方法 + +> 使用示例 + +```javascript +import { copy } from '@/plugins/global-api.js'; +copy('hello world'); +``` + +```javascript +const { proxy } = getCurrentInstance(); +proxy.$copy('hello world'); +``` + +| 名称 | 功能介绍 | +| -------- | --------------------- | +| copy | 复制文本 | +| download | 下载指定地址文件 | +| excel | 导出 excel 文件并下载 | + +## 全局组件 + +| 名称 | 功能介绍 | +| --------- | ------------ | +| ElEditor | 富文本编辑器 | +| TableList | 通用列表组件 | + ## 心得总结 ### prettier diff --git a/src/plugins/global-api.js b/src/plugins/global-api.js index c855971..1b620ce 100644 --- a/src/plugins/global-api.js +++ b/src/plugins/global-api.js @@ -1,16 +1,70 @@ import { ElMessage } from './element-plus'; - -export const copy = (content) => { - const el = document.createElement('textarea'); - el.style.position = 'absolute'; - el.style.zIndex = '-9999'; - el.value = content; - document.body.appendChild(el); - el.select(); - document.execCommand('copy'); - el.remove(); - ElMessage.success('复制成功'); +/** + * 复制文本 + * @param {string} content 要复制的内容 + */ +export const copy = async (content) => { + if (typeof navigator?.clipboard?.writeText === 'function') { + try { + await navigator.clipboard.writeText(content); + ElMessage.success('复制成功'); + } catch (e) { + ElMessage.error('复制失败'); + console.warn('复制失败', e); + } + } else { + const el = document.createElement('textarea'); + el.style.position = 'absolute'; + el.style.zIndex = '-9999'; + el.value = content; + document.body.appendChild(el); + el.select(); + if (document.execCommand('copy')) { + ElMessage.success('复制成功'); + } else { + ElMessage.erorr('复制失败'); + } + el.remove(); + } +}; +/** + * 下载指定地址的文件 + * @param {*} fileName 文件名称 + * @param {*} href 文件地址 + */ +export const download = (fileName, href) => { + if ('download' in document.createElement('a')) { + const elink = document.createElement('a'); + elink.download = fileName; + elink.style.display = 'none'; + elink.href = href; + document.body.appendChild(elink); + elink.click(); + document.body.removeChild(elink); + } else { + window.open(href, '_blank'); + } }; +/** + * 导出为excel并下载 + * @param {*} fileName 文件名称 + * @param {*} data excel数据 + */ +export const excel = (fileName, data) => { + const blob = new Blob([data], { type: 'text/plain,charset=UTF-8' }); + if ('download' in document.createElement('a')) { + const elink = document.createElement('a'); + elink.download = fileName; + elink.href = URL.createObjectURL(blob); + document.body.appendChild(elink); + elink.click(); + URL.revokeObjectURL(elink.href); + document.body.removeChild(elink); + } else { + navigator.msSaveBlob(blob, fileName); + } +}; + export default (app) => { app.config.globalProperties.$copy = copy; };