# 前端 ## 问题 ### vue3 引入@路径 #### 引入path模块问题 node.js 自带的path模块,是JavaScript代码,要引入ts文件,需要安装@type/node模块。 ```shell npm install @types/node --save-dev ``` 之后就可以加载path。在 vite.config.ts 中加上 ```typescript import path from "path"; resolve: { //配置别名 alias: [ { find: /^~/, replacement: "", }, { find: "@", replacement: path.resolve( __dirname, "src" ), }, ], }, ``` ### tomcat 跨域下载文件 tomcat 默认是不支持跨域的,不做配置使用vue下载文件会有Access-Control-Allow-Origin问题。 解决方法: 编辑 web.xml 文件,找到 ```xml ``` 在下面添加 ```xml CorsFilter org.apache.catalina.filters.CorsFilter cors.allowed.origins * CorsFilter /* ``` 重启 tomcat 解决。 ## 组件 ### pdf预览组件 使用 ## 技术 ### element-plus 文件上传 element-plus 文件上传组件的响应函数,作为:on-success属性值。要传递的参数作为:data属性值。 ```typescript import { type FileUploadResponse } from "@/utils/fileUpload.js"; import { type UploadProps, type UploadFile, type UploadFiles, ElMessage, ElMessageBox } from "element-plus"; const onUploadSuccess: UploadProps["onSuccess"] = ( response: FileUploadResponse, uploadFile: UploadFile, uploadFiles: UploadFiles ): void => { // 先判断成功标志位 if ( response.success ) { // 成功,发出导入报表请求 if ( response.fileList.length === 0 ) { // 上传文件路径有问题,提示一下 ElMessageBox.confirm( "上传文件的保存路径有误,请联系开发人员。", "上传文件错误", { confirmButtonText: "确定", type: "warning", center: true, } ) .then((): void => {}) .catch((): void => {}); } const request: ImportBIReportRequest = { filePath: response.fileList[0], reportType: ui.selectedReportType, firstRow: ui.firstRow, sheetIndex: ui.sheetIndex, }; console.log( "请求参数", request ); // 发出请求 importBIReport( request, importResponseHandler ); } else { // 失败了,提示一下 ElMessageBox.confirm( response.message, "上传文件错误", { confirmButtonText: "确定", type: "warning", center: true, } ) .then((): void => {}) .catch((): void => {}); } }; ``` ### typescript 的安全链式调用 和 强制链式调用 在链式调用时,在成员访问操作符前加上?,表示安全链式调用;加上!表示强制链式调用。 如果?前的属性存在,则正常调用,否则返回null。 ```typescript // 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示 // 出错 TS2532: Object is possibly 'undefined'. return new Error().stack.split('\n'); // 我们可以添加?操作符,当stack属性存在时,调用 stack.split。 // 若stack不存在,则返回空 return new Error().stack?.split('\n'); // 以上代码等同以下代码, 感谢 @dingyanhe 的监督 const err = new Error(); return err.stack && err.stack.split('\n'); ``` 强制链式调用表示!前的属性一定会存在。 ```typescript // 这里 Error对象定义的stack是可选参数,如果这样写的话编译器会提示 // 出错 TS2532: Object is possibly 'undefined'. new Error().stack.split('\n'); // 我们确信这个字段100%出现,那么就可以添加!,强调这个字段一定存在 new Error().stack!.split('\n'); ```