feat(hooks): 抽离剪贴板hook方法

This commit is contained in:
Coffee-crocodile 2022-10-13 11:32:13 +08:00
parent 4bb35a5c2a
commit 097a83b9a3
3 changed files with 30 additions and 19 deletions

View File

@ -2,3 +2,4 @@ export * from './useAppRouter';
export * from './useBoolean';
export * from './useLoading';
export * from './useEcharts';
export * from './useClipBoard';

26
src/hook/useClipBoard.ts Normal file
View File

@ -0,0 +1,26 @@
export function useClipBoard() {
function isSupport() {
return !navigator.clipboard;
}
async function copy(text: string) {
if (isSupport()) {
return window.$message?.error('当前浏览器不支持复制!');
}
if (!text) {
window.$message?.error('请输入要复制的内容');
return;
}
navigator.clipboard.writeText(text).then(
() => {
window.$message?.success(`复制成功:${text}`);
},
() => {
window.$message?.error('复制失败');
},
);
}
return {
copy,
};
}

View File

@ -2,33 +2,17 @@
<n-card>
<n-input-group>
<n-input v-model:value="text" placeholder="请输入要复制的内容" />
<n-button type="primary" @click="handleCopy">复制</n-button>
<n-button type="primary" @click="copy(text)">复制</n-button>
</n-input-group>
</n-card>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useClipBoard } from '@/hook';
const { copy } = useClipBoard();
const text = ref('Hello Clipboard');
function handleCopy() {
if (!navigator.clipboard) {
window.$message?.error('当前浏览器不支持复制!');
}
if (!text.value) {
window.$message?.error('请输入要复制的内容');
return;
}
navigator.clipboard.writeText(text.value).then(
(res) => {
window.$message?.success(`复制成功:${text.value}`);
},
(err) => {
window.$message?.error('复制失败');
},
);
}
</script>
<style scoped></style>