浏览代码

fix bug 自定义分析多个文件 50kb、表格删除、乱码问题展示

liujiejie 5 月之前
父节点
当前提交
00f76a2ae7

+ 0 - 4
src/store/dragChart.js

@@ -90,12 +90,10 @@ export default {
         );
       }
     },
-
     // 删除图表
     deleteChart(state, index) {
       state.currentChartList.splice(index, 1);
     },
-
     // 设置当前图表列表
     setCurrentChartList(state, list = []) {
       state.currentChartList = list;
@@ -106,7 +104,6 @@ export default {
       const index = state.fileList.indexOf(item);
       state.fileList.splice(index, 1);
     },
-
     // 文件添加
     fileListAdd(state, item) {
       state.fileList.push(item);
@@ -135,7 +132,6 @@ export default {
         Message.warning("未找到文件!");
       }
     },
-
     // 缩放屏幕
     scaleScreen(state, isGrow) {
       if (isGrow) {

+ 5 - 1
src/styles/global.scss

@@ -4,6 +4,9 @@
   border-color: var(--primary-color) !important;
   color: var(--text-color) !important;
 }
+.el-menu-item.is-active {
+  color: var(--primary-color) !important;
+}
 
 .el-dialog__header {
   background-color: var(--primary-color) !important;
@@ -21,6 +24,7 @@
   color: var(--primary-color) !important;
   // color: var(--primary-color) !important;
 }
+
 .el-button--text {
   color: var(--primary-color) !important;
 }
@@ -32,7 +36,7 @@
 }
 
 // 改变振动分析边框色
-.head{
+.head {
   border-top: 5px solid var(--primary-color) !important;
   border-bottom: 5px solid var(--primary-color) !important;
 }

+ 0 - 3
src/utils/indexedDb.js

@@ -107,13 +107,10 @@ export async function clearAllDataFromIndexedDB() {
         db.close();
         return resolve();
       }
-
       const currentVersion = db.version;
       db.close();
-
       // 使用当前版本或更高版本打开数据库
       const request = indexedDB.open("FileDataDB", currentVersion);
-
       request.onsuccess = (event) => {
         const db = event.target.result;
         const transaction = db.transaction(["files"], "readwrite");

+ 0 - 2
src/utils/vuexIndexedDBPlugin.js

@@ -58,7 +58,6 @@ const vuexIndexedDBPlugin = (store) => {
     );
     return clonedState;
   };
-
   // 初始化 IndexedDB 并加载状态
   openDB(dbName, 1).then(() => {
     getData(dbName, keyName).then((savedState) => {
@@ -67,7 +66,6 @@ const vuexIndexedDBPlugin = (store) => {
           ...store.state,
           ...savedState,
         });
-        // console.log("Vuex state loaded from IndexedDB");
       }
     });
   });

+ 0 - 1
src/views/health/vibration.vue

@@ -307,7 +307,6 @@ export default {
       }
     },
   },
-
   methods: {
     handleLoading(currentRow, loading, activeIndex, params) {
       if (loading) {

+ 2 - 1
src/views/performance/components/custonAsCom/AssociatedFields.vue

@@ -190,7 +190,8 @@ export default {
             filename: this.ruleForm.name + "关联表",
             fileData: data,
             fileOldName: this.ruleForm.name + "关联表",
-            fileId: new Date().getTime(),
+            fileId:
+              new Date().getTime() + "_" + Math.floor(Math.random() * 1000),
           };
           storeSetData(database, "files", "fileDataArray", fileData, () => {
             this.setRelatedFieldsData({

+ 99 - 10
src/views/performance/components/custonAsCom/dataTable.vue

@@ -1,7 +1,7 @@
 <!--
  * @Author: your name
  * @Date: 2024-10-28 16:46:38
- * @LastEditTime: 2024-12-05 15:27:24
+ * @LastEditTime: 2024-12-20 15:05:57
  * @LastEditors: bogon
  * @Description: In User Settings Edit
  * @FilePath: /performance-test/src/views/performance/components/custonAsCom/dataTable.vue
@@ -12,12 +12,14 @@
       v-if="tabData.length > 0"
       v-model="activeName"
       @tab-click="handleClick"
+      closable
+      @tab-remove="removeTab"
       class="tabsBox"
     >
       <template v-for="(tabItem, ind) in tabData">
         <el-tab-pane
           :label="tabItem.filename"
-          :name="String(tabItem.filename + tabItem.fileId)"
+          :name="String(tabItem.fileId)"
           :key="tabItem.fileData + ind + 'tabPane'"
         >
           <el-row
@@ -26,9 +28,9 @@
             justify="end"
             :key="tabItem.filename + ind + 'row'"
           >
-            <el-button type="primary" @click="handleEditTable(tabItem.fileId)"
-              >编辑</el-button
-            >
+            <el-button type="primary" @click="handleEditTable(tabItem.fileId)">
+              编辑
+            </el-button>
           </el-row>
           <template v-if="tabItem.fileData && tabItem.fileData.length > 0">
             <el-table
@@ -106,17 +108,104 @@ export default {
       });
   },
   methods: {
-    ...mapMutations("dragChart", ["setTriggerGetData"]),
+    ...mapMutations("dragChart", [
+      "setTriggerGetData",
+      "setUpdateTriggerGetData",
+    ]),
     async getIndexDbData() {
       // this.loading = true;
       const jsonData = await getDataFromIndexedDB();
       this.tabData = jsonData;
-      this.activeName =
-        jsonData &&
-        jsonData[0] &&
-        String(jsonData[0].filename + jsonData[0].fileId);
+      this.activeName = jsonData && jsonData[0] && String(jsonData[0].fileId);
       this.loading = false;
     },
+    // removeTab(targetName) {
+    //   //this.tabData 循环判断每一项的filename 如果和filename相等的情况下就在indexeddb中删除这一项
+    //   // this.setTriggerGetData(true);
+    //   // this.setUpdateTriggerGetData(true);
+    // },
+    // 删除 tab 方法
+    removeTab(targetName) {
+      // 1. 在 tabData 中删除对应的 tab
+      const index = this.tabData.findIndex((tab) => tab.fileId === targetName);
+      console.log(this.tabData, targetName, "targetName");
+      if (index !== -1) {
+        // 删除 tabData 中的对应项
+        const data = this.tabData;
+        const removedTab = data.splice(index, 1)[0]; // 获取被删除的 tab 数据
+
+        // 2. 更新 IndexedDB
+        this.updateDataInIndexedDB(removedTab);
+
+        // 3. 触发需要更新的状态
+        this.setTriggerGetData(true);
+        this.setUpdateTriggerGetData(true);
+      }
+    },
+
+    async updateDataInIndexedDB(removedTab) {
+      try {
+        const db = await this.openIndexedDB(); // 打开 IndexedDB
+
+        // 创建事务,指定操作对象存储空间
+        const transaction = db.transaction(["files"], "readwrite");
+        const store = transaction.objectStore("files");
+
+        // 使用 getAll 获取所有数据
+        const getRequest = store.getAll();
+        getRequest.onsuccess = () => {
+          const data = getRequest.result;
+          console.log(data, "所有数据");
+
+          // 假设文件数据在 data[0].data 中
+          let updatedData = data[0]?.data || [];
+
+          // 从数据中移除被删除的 tab 数据
+          updatedData = updatedData.filter(
+            (item) => item.fileId !== removedTab.fileId
+          );
+
+          // 更新存储的数据(这里假设数据存储在 id 为 "fileDataArray" 的键下)
+          const putRequest = store.put({
+            id: "fileDataArray", // 使用 "fileDataArray" 作为 id
+            data: updatedData,
+          });
+
+          putRequest.onsuccess = () => {
+            console.log("Updated data successfully in IndexedDB");
+          };
+
+          putRequest.onerror = (event) => {
+            console.error(
+              "Error updating data in IndexedDB:",
+              event.target.error
+            );
+          };
+        };
+
+        getRequest.onerror = (event) => {
+          console.error(
+            "Error retrieving data from IndexedDB:",
+            event.target.error
+          );
+        };
+      } catch (error) {
+        console.error("Failed to update data in IndexedDB:", error);
+      }
+    },
+
+    // 打开 IndexedDB 数据库
+    openIndexedDB() {
+      return new Promise((resolve, reject) => {
+        const request = indexedDB.open("FileDataDB");
+        request.onsuccess = (event) => {
+          resolve(event.target.result);
+        };
+        request.onerror = (event) => {
+          reject(event.target.error);
+        };
+      });
+    },
     handleClick(tab, event) {},
     handleEditTable(id) {
       this.$router.push({

+ 55 - 41
src/views/performance/customAnalysis.vue

@@ -14,6 +14,7 @@
               <el-upload
                 action=""
                 class="upload-demo"
+                multiple
                 :http-request="customUpload"
                 :on-change="validateAndHandleChange"
                 :before-upload="checkFileType"
@@ -102,7 +103,6 @@
             </span>
           </el-tooltip>
         </span>
-        计算器弹出框
       </el-tab-pane>
       <el-tab-pane name="associatedFields">
         <span slot="label" class="iconFont">
@@ -476,7 +476,6 @@ export default {
       };
       this.dialogVisible = false; // 重置表单状态
     },
-
     async storeData(newFileData) {
       await storeSetData(this.db, "files", "fileDataArray", newFileData, () => {
         this.setTriggerGetData(true);
@@ -503,27 +502,64 @@ export default {
         this.activeName = tab.name;
       }
     },
+
     // 自定义上传方法
     customUpload(file) {
       const formData = new FormData();
       formData.append("file", file);
       // 使用 axios 自定义上传逻辑
+      console.log("自定义上传", file.name);
     },
+
     // 验证并处理文件变化
-    validateAndHandleChange(file) {
-      if (this.checkFileType(file)) {
-        this.handleChange(file); // 仅当验证通过时调用 handleChange
+    validateAndHandleChange(fileList) {
+      // 判断 fileList 是否为数组(多个文件)还是单个文件
+      if (Array.isArray(fileList)) {
+        // 如果是数组(多个文件),遍历每个文件进行处理
+        fileList.forEach((file) => {
+          if (this.checkFileType(file)) {
+            this.handleChange(file); // 验证通过后逐一处理
+          }
+        });
+      } else {
+        // 如果是单个文件,直接处理
+        if (this.checkFileType(fileList)) {
+          this.handleChange(fileList);
+        }
       }
     },
-    // 文件变化时的处理
-    handleChange(file) {
-      this.checkFileType(file);
 
+    // 检查文件类型&多个文件选择,但多个文件总数大小不能超过50KB
+    checkFileType(file) {
+      // 判断文件类型
+      const isValidType =
+        file.type === "text/csv" ||
+        file.name.endsWith(".csv") ||
+        file.type ===
+          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
+        file.name.endsWith(".xlsx") ||
+        file.name.endsWith(".xls");
+
+      if (!isValidType) {
+        this.$message.error("只能上传csv文件或xlsx或xls文件");
+        return false; // 返回false,阻止上传
+      }
+
+      // 判断文件大小(以字节为单位,50KB = 51200字节)
+      const maxSize = 50 * 1024; // 50KB
+      if (file.size > maxSize) {
+        this.$message.error("文件大小不能超过50KB");
+        return false; // 返回false,阻止上传
+      }
+      return true; // 如果验证通过,允许上传
+    },
+
+    // 处理文件
+    handleChange(file) {
       // 如果是 CSV 文件
-      if (file && file.name.endsWith(".csv")) {
+      if (file.name.endsWith(".csv")) {
         const reader = new FileReader();
         reader.onload = (e) => {
-          // 检测文件编码并解析
           const encoding = this.detectFileEncoding(e.target.result);
           const text = new TextDecoder(encoding).decode(
             new Uint8Array(e.target.result)
@@ -537,7 +573,8 @@ export default {
                 filename: format(new Date(), "yyyyMMdd-HH:mm:ss") + file.name,
                 fileOldName: file.name,
                 fileData: results.data,
-                fileId: new Date().getTime(),
+                fileId:
+                  new Date().getTime() + "_" + Math.floor(Math.random() * 1000),
               };
               if (results.data.length > 0) {
                 this.storeData(fileData);
@@ -550,7 +587,7 @@ export default {
             },
           });
         };
-        reader.readAsArrayBuffer(file.raw); // 以 ArrayBuffer 读取文件
+        reader.readAsArrayBuffer(file.raw);
       } else {
         // 如果是 Excel 文件
         const reader = new FileReader();
@@ -581,43 +618,17 @@ export default {
             }
           });
         };
-        reader.readAsArrayBuffer(file.raw); // 以 ArrayBuffer 读取文件
+        reader.readAsArrayBuffer(file.raw);
       }
     },
-
     // 检测文件编码的方法
     detectFileEncoding(arrayBuffer) {
-      // 简单判断编码,默认 UTF-8,如果需要更精确,可以引入第三方库如 `jschardet`
       const text = new TextDecoder("utf-8").decode(new Uint8Array(arrayBuffer));
       if (text.includes("�")) {
-        // 如果有乱码字符,可能是 GBK 编码
-        return "gbk";
+        return "gbk"; // 如果有乱码字符,可能是 GBK 编码
       }
       return "utf-8";
     },
-
-    //判断上传文件类型
-    checkFileType(file) {
-      const isPdf =
-        file.type === "text/csv" ||
-        file.name.endsWith(".csv") ||
-        file.type ===
-          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
-        file.name.endsWith(".xlsx") ||
-        file.name.endsWith(".xls");
-      if (!isPdf) {
-        this.$message.error("只能上传csv文件或xlsx或xls文件");
-        return false;
-      }
-      // 判断文件大小(以字节为单位,100kB = 102400字节)
-      const maxSize = 50 * 1024; // 100kB
-      if (file.size > maxSize) {
-        this.$message.error("文件大小不能超过50kB");
-        return false;
-      }
-      this.loading = true;
-      return true;
-    },
   },
   async mounted() {
     await this.initDB(); // 初始化数据库
@@ -643,8 +654,11 @@ export default {
   .popover-footer {
     text-align: right;
   }
-  .iconFont {
+  ::v-deep .iconFont {
     padding: 0 20px;
+    width: 100% !important;
+    height: 100% !important;
+    display: inline-block;
   }
 
   ::v-deep .el-tabs__content {