PreviewCode.vue
2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<template>
<div>
<div class="v-json-box">
<CodeEditor :value="editorJson" ref="myEditor" :mode="MODE.JSON" />
</div>
<div class="copy-btn-box">
<a-button
@click="handleCopyJson"
type="primary"
class="copy-btn"
data-clipboard-action="copy"
:data-clipboard-text="editorJson"
>
复制数据
</a-button>
<a-button @click="handleExportJson" type="primary">导出代码</a-button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, unref } from 'vue';
import { CodeEditor, MODE } from '/@/components/CodeEditor';
import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
import { useMessage } from '/@/hooks/web/useMessage';
export default defineComponent({
name: 'PreviewCode',
components: {
CodeEditor,
},
props: {
fileFormat: {
type: String,
default: 'json',
},
editorJson: {
type: String,
default: '',
},
},
setup(props) {
const state = reactive({
visible: false,
});
const exportData = (data: string, fileName = `file.${props.fileFormat}`) => {
let content = 'data:text/csv;charset=utf-8,';
content += data;
const encodedUri = encodeURI(content);
const actions = document.createElement('a');
actions.setAttribute('href', encodedUri);
actions.setAttribute('download', fileName);
actions.click();
};
const handleExportJson = () => {
exportData(props.editorJson);
};
const { clipboardRef, copiedRef } = useCopyToClipboard();
const { createMessage } = useMessage();
const handleCopyJson = () => {
// 复制数据
const value = props.editorJson;
if (!value) {
createMessage.warning('代码为空!');
return;
}
clipboardRef.value = value;
if (unref(copiedRef)) {
createMessage.warning('复制成功!');
}
};
return {
...toRefs(state),
exportData,
handleCopyJson,
handleExportJson,
MODE,
};
},
});
</script>
<style lang="less" scoped>
// modal复制按钮样式
.copy-btn-box {
padding-top: 8px;
text-align: center;
.copy-btn {
margin-right: 8px;
}
}
</style>