封装代码片段语法 vue2语法

关于函数导入

1.在untils写一个pdfService.js 关于pdf预览和下载的方法

export const previewPdf = async (record) => {
	const pdfUrln = record.url; // 直接使用 PDF 文件的 URL
	// const pdfUrln = indexConfig.VITE_GLOB_VIEW_URL + 'static/pdf/web/viewer.html?file=' + record.url;
	uni.downloadFile({
		url: pdfUrln,
		success: function(res) {

			if (res.statusCode === 200) {
				console.log('文件下载成功', res);
				let filePath = res.tempFilePath; // 确认文件路径
				uni.openDocument({
					filePath: filePath,
					fileType: 'pdf', // 明确指定为pdf文件
					success: function(res) {
						console.log("文档打开成功");
					},
					fail: function(res) {
						console.error("文档打开失败", res);
					}
				});
			} else {
				console.error('文件下载失败,状态码:', res.statusCode);
			}
		},
		fail: function(err) {
			console.error('文件下载失败', err);
		}
	});
};

export const downloadPdf = async (record) => {
	uni.showLoading({
		title: '文件下载中...',
	});
	// 使用微信小程序专用 API
	wx.downloadFile({
		url: record.url, // 这里需要是 HTTPS 地址
		success(res) {
			if (res.statusCode === 200) {
				console.log('文件下载成功,文件路径:', res.tempFilePath);
				uni.showModal({
					title: '提示',
					content: '文件下载成功,是否打开?',
					success: function(modalRes) {
						if (modalRes.confirm) {

							wx.openDocument({
								filePath: res.tempFilePath,
								showMenu: true, // 支持右上角菜单
								fileType: 'pdf', // 指定文件类型为 pdf
								success() {
									console.log('文档打开成功');
								},
								fail(err) {
									console.log('打开文档失败', err);
								}
							});
						}
					}
				});
			} else {
				console.log('文件下载失败,状态码:', res.statusCode);
			}
		},
		fail(err) {
			uni.hideLoading();
			console.log('文件下载失败', err);
		},
		complete() {
			uni.hideLoading();
		}
	});
};

2.引用

 import { 	previewPdf,downloadPdf } from '@/utils/pdfService';

<u-modal :show="showFile" :title="getTitle" @confirm="confirm" @cancel="cancel" :asyncClose="true"
			:showCancelButton="true" :closeOnClickOverlay="true" width="590rpx">
			<view class="slot-content">
				<uni-table ref="table" border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<uni-tr class="custom-header">
						<uni-th align="center">附件名称</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<!-- 表格数据行 -->
					<uni-tr v-for="(item, index) in fileList" :key="index">
						<uni-td align="center">{{ item.fileName }}</uni-td>
						<uni-td width="300rpx" align="center">
							<a @click="previewPdf(item)">预览</a>
							<a @click="downloadPdf(item)">下载</a>
						</uni-td>
					</uni-tr>


				</uni-table>
			</view>
		</u-modal>

问题来了 报错 说我没注册 也就是说在methods里面 还要写函数

previewPdf(record) {
	previewPdf(record)
	},
downloadPdf(record) {
	downloadPdf(record)
	},

这样子要写两遍 太麻烦了

于是有

第二种

在utils里面新建目录mixin 封装,组件中通过 Mixin 的方式使用,而不是每次都手动导入和定义方法

// utils/PdfMixin.js
export const PdfMixin = {
  methods: {
    previewPdf(record) {
      const pdfUrl = record.url;
      uni.downloadFile({
        url: pdfUrl,
        success: function (res) {
          if (res.statusCode === 200) {
            let filePath = res.tempFilePath;
            uni.openDocument({
              filePath: filePath,
              fileType: 'pdf',
              success: function () {
                console.log("文档打开成功");
              },
              fail: function (res) {
                console.error("文档打开失败", res);
              },
            });
          } else {
            console.error("文件下载失败,状态码:", res.statusCode);
          }
        },
        fail: function (err) {
          console.error("文件下载失败", err);
        },
      });
    },

    downloadPdf(record) {
      uni.showLoading({
        title: "文件下载中...",
      });
      wx.downloadFile({
        url: record.url,
        success(res) {
          if (res.statusCode === 200) {
            uni.showModal({
              title: "提示",
              content: "文件下载成功,是否打开?",
              success: function (modalRes) {
                if (modalRes.confirm) {
                  wx.openDocument({
                    filePath: res.tempFilePath,
                    showMenu: true,
                    fileType: 'pdf',
                    success() {
                      console.log("文档打开成功");
                    },
                    fail(err) {
                      console.log("打开文档失败", err);
                    },
                  });
                }
              },
            });
          } else {
            console.log("文件下载失败,状态码:", res.statusCode);
          }
        },
        fail(err) {
          uni.hideLoading();
          console.log("文件下载失败", err);
        },
        complete() {
          uni.hideLoading();
        },
      });
    },
  },
};

引入

	import {
		PdfMixin
	} from '@/utils/mixin/pdfMixin';

注册

mixins: [PdfMixin], // 引入 Mixin

可以了

相关推荐
夏天想2 天前
微信小程序使用picker,数组怎么设置默认值
微信小程序·小程序·notepad++
一 乐3 天前
英语词汇小程序小程序|英语词汇小程序系统|基于java的四六级词汇小程序设计与实现(源码+数据库+文档)
java·数据库·小程序·源码·notepad++·英语词汇
一 乐3 天前
租拼车平台|小区租拼车管理|基于java的小区租拼车管理信息系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·微信·notepad++·拼车
漏刻有时3 天前
微信小程序学习实录9:掌握wx.chooseMedia实现多图片文件上传功能(选择图片、预览图片、上传图片)
学习·微信小程序·notepad++
山语山7 天前
微信小程序 蓝牙通讯
网络·微信小程序·小程序·github·notepad++
程序手艺人9 天前
Notepad++ 之 AndroidLogger插件
notepad++
迷雾yx9 天前
开发微信小程序 案例01-本地生活首页页面
微信小程序·生活·notepad++·xss
灯火不休ᝰ9 天前
[Notepad++] 文本编辑器的下载及详细安装使用过程(附有下载文件)
notepad++
无敌开心11 天前
微信小程序开发第八课
微信小程序·小程序·notepad++