certPreview.vue
2.34 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<template>
<view class="preview-container">
<view class="loading-tip" v-if="loading">加载中...</view>
<view class="error-tip" v-else-if="showError">{{ errorMsg }}</view>
<view class="download-btn" @click="openDocument">
<text>查看会员证</text>
</view>
</view>
</template>
<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import config from "@/config.js";
const pdfUrl = ref("");
const loading = ref(true);
const showError = ref(false);
const errorMsg = ref("");
const tempFilePath = ref("");
onLoad(async (option) => {
if (option.url) {
pdfUrl.value = config.baseUrl_api + decodeURIComponent(option.url);
await downloadPdf();
}
});
const downloadPdf = () => {
return new Promise((resolve) => {
uni.showLoading({ title: "加载中..." });
uni.downloadFile({
url: pdfUrl.value,
success: (res) => {
uni.hideLoading();
if (res.statusCode === 200) {
tempFilePath.value = res.tempFilePath;
loading.value = false;
// 自动打开文档
openDocument();
} else {
showError.value = true;
errorMsg.value = "下载失败";
}
resolve();
},
fail: () => {
uni.hideLoading();
showError.value = true;
errorMsg.value = "下载失败";
resolve();
}
});
});
};
const openDocument = () => {
if (!tempFilePath.value) {
uni.showToast({ title: "文件未准备好", icon: "none" });
return;
}
uni.openDocument({
filePath: tempFilePath.value,
fileType: "pdf",
showMenu: true,
success: () => {
console.log("打开文档成功");
},
fail: () => {
uni.showToast({ title: "打开失败,请在右上角菜单中下载", icon: "none" });
}
});
};
</script>
<style lang="scss" scoped>
.preview-container {
min-height: 100vh;
background: #f5f5f5;
position: relative;
}
.loading-tip {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 28rpx;
color: #666;
}
.error-tip {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 28rpx;
color: #C40F18;
}
.download-btn {
position: fixed;
bottom: 50rpx;
left: 50%;
transform: translateX(-50%);
background: #C40F18;
color: #fff;
padding: 24rpx 60rpx;
border-radius: 40rpx;
font-size: 28rpx;
z-index: 100;
}
</style>