certPreview.vue 2.34 KB
<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>