Ver código fonte

token过期跳转到登录页

hzj18279462576@163.com 4 dias atrás
pai
commit
f82dc4999f

+ 1 - 0
src/components/chart/Basic.vue

@@ -53,6 +53,7 @@ export default {
         .getSchoolUser({ id: this.id })
         .then(res => {
           // console.log(res);
+          
           this.data = res.data;
           let affinityScoreName = this.data.affinityScoreName.join("、");
           this.data.affinityScoreName = affinityScoreName;

+ 1 - 0
src/components/chart/Card.vue

@@ -264,6 +264,7 @@ export default {
         .track(params)
         .then(res => {
           // console.log(res.data.length);
+          
           if (res.data.length !== 0) {
             res.data.forEach(item => {
               let data = dayjs(item.dateTime).format("M.DD HH:mm:ss");

+ 1 - 0
src/components/chart/ComeChart.vue

@@ -63,6 +63,7 @@ export default {
         .comeMonth(params)
         .then((res) => {
           // console.log(res);
+          
           res.data.forEach((item) => {
             // this.dateList.push(dayjs(item.startTime).format("MM.DD"));
             if (item.address == "宿舍") {

+ 1 - 0
src/components/chart/HabitChart.vue

@@ -66,6 +66,7 @@ export default {
       this.API.growing
         .stall(params)
         .then((res) => {
+          
           console.log(res, "洞察分析");
           this.tableData = res.data.records;
         })

+ 1 - 0
src/components/chart/IntimacyChart.vue

@@ -256,6 +256,7 @@ export default {
         .classSchedule(params)
         .then((res) => {
           console.log(res, "课表数据");
+          
           let arr = Array.from({ length: 11 }, () => ({ list: [] }));
           res.data.reverse().forEach((item, index) => {
             for (let i = 0; i <= 10; i++) {

+ 1 - 0
src/components/chart/LiveChart.vue

@@ -38,6 +38,7 @@ export default {
         .energy(params)
         .then((res) => {
           // console.log(res);
+          
           this.electricity = [];
           this.electricityTime = [];
           let electricity = res.data.electricityAndColdWater.list.reverse();

+ 1 - 0
src/components/chart/PieChart.vue

@@ -59,6 +59,7 @@ export default {
         this.API.personal
           .personConsum(params)
           .then(res => {
+            
             // console.log(res);
             this.value = res.data;
             this.data = [];

+ 1 - 0
src/components/chart/RadarChart.vue

@@ -121,6 +121,7 @@ export default {
         .capacity(params)
         .then((res) => {
           // console.log(res);
+          
           this.average = res.data.average;
 
           res.data.list.forEach((item, index) => {

+ 14 - 1
src/components/growing/ComeChart.vue

@@ -57,6 +57,19 @@ export default {
         .comeDay()
         .then((res) => {
           // console.log(res);
+          // 先防御判断,防止res为空报错
+          if (!res) {
+            return;
+          }
+          // 判断token失效
+          if (res.desc === "token为空" || res.desc === "无效token,请重新登录") {
+            // 1. 清空本地token
+            sessionStorage.removeItem("key");
+            this.$message.error(res.desc);
+            // 2. 跳转登录页,不是Growing
+            this.$router.push({ path: "/login" });
+            return;
+          }
           let arr = res.data;
           arr.forEach((item) => {
             if (item.address == "宿舍") {
@@ -340,4 +353,4 @@ export default {
     color: transparent;
   }
 }
-</style>
+</style>

Diferenças do arquivo suprimidas por serem muito extensas
+ 933 - 0
src/components/portrait/Map copy.vue


+ 133 - 336
src/components/portrait/Map.vue

@@ -6,6 +6,7 @@
       <svg width="1920" height="1080" viewBox="0 0 1920 1080">
         <g id="road">
           <path
+            v-if="valueL"
             id="biking-road"
             fill="none"
             stroke-miterlimit="2"
@@ -117,7 +118,7 @@
           <div class="headerTrack">轨迹详情</div>
           <div class="close" @click="closeImg">
             <div>
-              <img src="../../assets/cha.png" alt="" style="width:25px" />
+              <img src="../../assets/cha.png" alt="" style="width: 25px" />
             </div>
           </div>
         </div>
@@ -157,7 +158,7 @@
         style="width: 22px; margin-right: 6px"
         alt
       />
-      <span style="color:white;font-size: 16px;">返回</span>
+      <span style="color: white; font-size: 16px">返回</span>
     </div>
     <!-- <div class="img">
       <img src="../../assets/body.png" alt />
@@ -174,404 +175,198 @@
 
 <script>
 import dayjs from "dayjs";
+// import gsap from "gsap";
+// import { MotionPathPlugin } from "gsap/MotionPathPlugin";
+// gsap.registerPlugin(MotionPathPlugin);
+
 export default {
   name: "Card",
   data() {
     return {
       data: [],
       imgSrc: "",
-      scaleImg: false, // 控制点位弹窗按钮
-      clickImg: false, // 控制点击图片弹窗按钮
+      scaleImg: false,
+      clickImg: false,
       animationData: [],
       timer: "",
-      move: "关闭", // 展开 关闭
-      trackTable: [], // 点击学生经过的点位显示这个点位的全部数据
-      map: [],
+      move: "关闭",
+      trackTable: [],
       point: [],
-      map: "",
-      lushu: "",
       valueL: "",
-      // valueR: "M354 639 L641 637 L1161 417 L897 421 L1021 168",
-      lengths: ""
+      lengths: "",
+      // 新增:存储动画实例,页面销毁销毁动画
+      circleTween: null,
     };
   },
   async mounted() {
     let params = { id: sessionStorage.getItem("id") };
-    // this.point = [];
-    // 请求学生轨迹数据
     try {
-      let res = await this.API.personal.track(params);
-      let animationData = await this.API.personal.coordinate(params);
-      this.animationData = animationData.data;
-      // console.log(res.data.length);
-      if (res.data.length !== 0) {
-        res.data.forEach(item => {
-          item.day = dayjs(item.dateTime).format("MM-DD");
-          item.hour = dayjs(item.dateTime).format("HH:mm:ss");
-          // this.$set(item, "doorLockShow", false);
-        });
-        let str = "";
-        res.data.forEach((item, index) => {
-          // console.log(item.longitude, item.latitude, item.affair);
-          this.point.push({
-            lng: Number(item.longitude),
-            lat: Number(item.latitude),
-            txt: item.affair,
-            img: item.image,
-            date: `${item.day} ${item.hour}`
-          });
+      const [trackRes, coordinateRes] = await Promise.all([
+        this.API.personal.track(params),
+        this.API.personal.coordinate(params),
+      ]);
+      console.log(trackRes);
+      console.log(coordinateRes);
 
-          // this.bj(item.longitude, item.latitude, item.affair, "", "", item);
-
-          if (index == 0) {
-            str = "M" + item.longitude + " " + item.latitude;
-          } else {
-            str = str + " " + "L" + item.longitude + " " + item.latitude;
-          }
-        });
-        // console.log(str);
-        this.valueL = str;
-        this.data = res.data;
+      this.animationData =
+        coordinateRes && coordinateRes.data ? coordinateRes.data : [];
+      // 无轨迹数据,只清空svg路径,点位照常渲染
+      if (!trackRes || !trackRes.data || trackRes.data.length === 0) {
+        this.valueL = "";
+        return;
       }
-    } catch (error) {
-      console.log(error);
-    }
 
-    // this.carGPSIP();
+      trackRes.data.forEach((item) => {
+        item.day = dayjs(item.dateTime).format("MM-DD");
+        item.hour = dayjs(item.dateTime).format("HH:mm:ss");
+      });
 
-    //初始化画板
+      let str = "";
+      let hasNullCoord = false;
+      trackRes.data.forEach((item, index) => {
+        const lng = item && item.longitude ? Number(item.longitude) : null;
+        const lat = item && item.latitude ? Number(item.latitude) : null;
 
-    // {
-    //   this.bj(811, 877, "科技楼");
-    //   this.bj(1283, 875, "行政办公楼");
-    //   this.bj(421, 968, "1 # 系办大楼");
-    //   this.bj(280, 965, "2 # 系办大楼");
-    //   this.bj(445, 808, "3 # 系办大楼");
-    //   this.bj(307, 807, "4 # 系办大楼");
-    //   this.bj(1620, 688, "5 # 系办大楼");
-    //   this.bj(1770, 687, "6 # 系办大楼", 106, 24);
-    //   this.bj(1586, 564, "7 # 系办大楼");
-    //   this.bj(1727, 561, "8 # 系办大楼");
-    //   this.bj(897, 421, "1 # 教学大楼");
-    //   this.bj(1161, 417, "2 # 教学大楼");
-    //   this.bj(641, 637, "学生创就业中心");
-    //   this.bj(354, 639, "1 # 食堂");
-    //   // this.bj(1430, 137, "2 # 食堂");
-    //   this.bj(581, 493, "1 # 学生公寓");
-    //   this.bj(590, 436, "2 # 学生公寓");
-    //   this.bj(605, 384, "3 # 学生公寓");
-    //   this.bj(613, 333, "4 # 学生公寓");
-    //   this.bj(677, 275, "5 # 学生公寓");
-    //   this.bj(683, 233, "6 # 学生公寓");
-    //   this.bj(690, 188, "7 # 学生公寓");
-    //   this.bj(701, 148, "8 # 学生公寓");
-    //   this.bj(429, 495, "9 # 学生公寓");
-    //   this.bj(441, 441, "10 # 学生公寓");
-    //   this.bj(466, 384, "11 # 学生公寓");
-    //   this.bj(478, 337, "12 # 学生公寓");
-    //   this.bj(541, 276, "13 # 学生公寓");
-    //   this.bj(554, 232, "14 # 学生公寓");
-    //   this.bj(566, 191, "15 # 学生公寓");
-    //   this.bj(574, 151, "16 # 学生公寓");
-    //   this.bj(1021, 168, "图文信息中心");
-    //   this.bj(571, 23, "田径场");
-    //   this.bj(1329, 40, "礼堂");
-    //   this.bj(1827, 468, "17 # 学生公寓", 117, 24);
-    //   this.bj(1804, 415, "18 # 学生公寓");
-    //   this.bj(1783, 375, "19 # 学生公寓");
-    //   this.bj(1760, 325, "20 # 学生公寓");
-    //   this.bj(1729, 271, "21 # 学生公寓");
-    //   this.bj(1704, 228, "22 # 学生公寓");
-    //   this.bj(1691, 196, "23 # 学生公寓");
-    //   this.bj(1664, 162, "24 # 学生公寓");
-    //   this.bj(1647, 117, "25 # 学生公寓");
-    //   this.bj(1629, 83, "26 # 学生公寓");
-    //   this.bj(1608, 47, "27 # 学生公寓");
-    //   this.bj(1591, 12, "28 # 学生公寓");
-    //   this.bj(997, 983, "校门出口");
-    //   this.bj(1075, 983, "校门进口");
-    //   this.bj(1363, 1041, "北大门左侧1");
-    //   this.bj(1199, 1041, "北大门左侧2");
-    //   this.bj(877, 1052, "北大门右侧1");
-    //   this.bj(732, 1052, "北大门右侧2");
-    //   this.bj(483, 1052, "北大门右侧3");
-    //   this.bj(324, 1052, "北大门右侧4");
-    //   this.bj(127, 1052, " 系办楼东面1");
-    //   this.bj(167, 903, " 系办楼东面2");
-    //   this.bj(548, 315, "前8栋路口");
-    //   this.bj(505, 547, "宿舍楼北面");
-    // }
+        // 存在空坐标标记
+        if (lng === null || lat === null || isNaN(lng) || isNaN(lat)) {
+          hasNullCoord = true;
+        }
 
-    // let bikingRoad = document.getElementById("biking-road");
-    // console.log(bikingRoad);
-    this.$nextTick(() => {
-      var path = document.querySelector("#biking-road");
-      var lengths = path.getTotalLength();
-      this.lengths = lengths;
-      this.animationData.forEach((item, index) => {
-        // console.log(item, item.totalName, index);
-        this.bj(item);
-      });
-      gsap.registerPlugin(MotionPathPlugin);
-      // bikingRoad.animation = "dash 10s linear forwards";
+        // 点位兜底0,保证点位能正常渲染
+        this.point.push({
+          lng: lng || 0,
+          lat: lat || 0,
+          txt: item.affair,
+          img: item.image,
+          date: `${item.day} ${item.hour}`,
+        });
 
-      gsap.to("#circle", {
-        duration: 25, // 多少时间完成动画
-        repeat: 0, // 重复次数 -1为无限次
-        ease: Linear.easeNone, //动画的运动方式(匀速)
-        motionPath: {
-          path: "#biking-road",
-          align: "#biking-road",
-          autoRotate: true,
-          alignOrigin: [0.5, 0.5]
+        if (index === 0) {
+          str = `M${lng} ${lat}`;
+        } else {
+          str += ` L${lng} ${lat}`;
         }
       });
 
-      // gsap.registerPlugin(MotionPathPlugin);
-      // gsap.to("#circle2", {
-      //   duration: 20, // 多少时间完成动画
-      //   repeat: 0, // 重复次数 -1为无限次
-      //   ease: Linear.easeNone, //动画的运动方式(匀速)
-      //   motionPath: {
-      //     path: "#C-biking-road",
-      //     align: "#C-biking-road",
-      //     autoRotate: true,
-      //     alignOrigin: [0.5, 0.5]
-      //   }
-      // });
-    });
-  },
+      // 有空坐标:清空svg路径,点位数据保留正常渲染
+      if (hasNullCoord) {
+        this.valueL = "";
+      } else {
+        this.valueL = str;
+      }
+      this.data = trackRes.data;
+
+      this.$nextTick(() => {
+        // 点位固定渲染,不受svg控制
+        this.animationData.forEach((item) => {
+          this.bj(item);
+        });
 
+        // 只有合法路径才执行动画
+        if (!this.valueL) return;
+        const path = document.querySelector("#biking-road");
+        if (!path) return;
+        const lengths = path.getTotalLength();
+        this.lengths = lengths;
+
+        this.circleTween = gsap.to("#circle", {
+          duration: 25,
+          repeat: 0,
+          ease: gsap.parseEase("Linear.easeNone"),
+          motionPath: {
+            path: "#biking-road",
+            align: "#biking-road",
+            autoRotate: true,
+            alignOrigin: [0.5, 0.5],
+          },
+        });
+      });
+    } catch (error) {
+      console.log("轨迹接口请求失败", error);
+      this.valueL = "";
+      return;
+    }
+  },
+  // 关键:组件销毁钩子,清除动画、定时器、DOM事件
+  beforeUnmount() {
+    // 清除位移定时器
+    if (this.timer) {
+      clearInterval(this.timer);
+      this.timer = null;
+    }
+    // 销毁GSAP动画,防止页面销毁后继续执行
+    if (this.circleTween) {
+      this.circleTween.kill();
+      this.circleTween = null;
+    }
+    // 移除动态创建的点位DOM,避免残留事件
+    const bjBox = document.getElementById("bj");
+    if (bjBox) bjBox.innerHTML = "";
+  },
   methods: {
     xy(event) {
       let t = { value: "" };
-      var event = event || window.event; //标准化事件对象
+      var event = event || window.event;
       if (event.offsetX || event.offsetY) {
         t.value = event.offsetX + "," + event.offsetY;
       } else if (event.layerX || event.layerY) {
         t.value = event.layerX - 1 + "," + (event.layerY - 1);
       }
-      // console.log(t.value);
     },
     bj(item) {
+      // 移除 ??
+      const lat = item && item.latitude ? Number(item.latitude) : 0;
+      const lng = item && item.longitude ? Number(item.longitude) : 0;
       var bj = document.getElementById("bj");
+      if (!bj) return;
       var a = document.createElement("span");
       a.setAttribute("class", "a1");
       a.style.background = "#112b61";
       a.style.height = "20px";
       a.style.position = "absolute";
-      a.style.top = `${item.latitude}px`;
-      a.style.left = `${item.longitude}px`;
+      a.style.top = `${lat}px`;
+      a.style.left = `${lng}px`;
       a.style.color = "#fff";
       a.style.fontSize = "14px";
       a.style.padding = "2px 8px";
       a.style.borderRadius = "5px";
       a.style.transform = "translate(-50% ,-50%)";
       a.style.cursor = "pointer";
-      a.innerHTML = item.totalName;
+      a.innerHTML = item && item.totalName ? item.totalName : "点位";
       bj.appendChild(a);
       let _this = this;
-      a.addEventListener("click", function(e) {
-        // console.log(item);
-
-        if (item.dateTime) {
-          _this.scaleImg = true;
-          // _this.imgSrc = item.image;
-          // console.log(e.target.innerHTML);
-          // console.log(item);
-          let params = {
-            id: sessionStorage.getItem("id"),
-            latitude: item.latitude,
-            longitude: item.longitude
-          };
-          _this.API.personal.allTrack(params).then(res => {
-            // console.log(res);
-            if (res.data.length == 0) {
-            } else {
-              _this.trackTable = res.data;
-            }
+      a.addEventListener("click", function (e) {
+        if (!item || !item.dateTime) return;
+        _this.scaleImg = true;
+        let params = {
+          id: sessionStorage.getItem("id"),
+          latitude: item.latitude || 0,
+          longitude: item.longitude || 0,
+        };
+        _this.API.personal
+          .allTrack(params)
+          .then((res) => {
+            _this.trackTable = res && res.data ? res.data : [];
+          })
+          .catch((err) => {
+            console.log("点位详情接口失败", err);
+            _this.trackTable = [];
           });
-        }
       });
     },
-    // 关闭点击点位时的弹窗
     closeImg() {
       this.scaleImg = false;
       this.clickImg = false;
     },
     imgtrack(i) {
-      // console.log(i);
       this.imgSrc = i.pictureScene;
       this.clickImg = true;
     },
     closeImgTrack() {
       this.clickImg = false;
     },
-    // carGPSIP() {
-    //   // let body = require("@/assets/dw.png");
-    //   // this.map = new BMapGL.Map("container");
-    //   // var point = new BMapGL.Point(115.396311, 28.794279);
-    //   // this.map.centerAndZoom(point, 19);
-    //   // 启用滚轮放大缩小,默认禁用
-    //   //   map.enableScrollWheelZoom(true);
-    //   // 启用地图惯性拖拽,默认禁用
-    //   // this.map.enableContinuousZoom(true);
-    //   // let points = [];
-    //   // console.log(this.point.length == 0);
-    //   if (this.point.length !== 0) {
-    //     this.point.forEach((item, index) => {
-    //       points.push(
-    //         new BMapGL.Marker(new BMapGL.Point(item.lng, item.lat), {
-    //           icon: new BMapGL.Icon(body, new BMapGL.Size(26, 26))
-    //         })
-    //       );
-    //       // console.log(points);
-    //       // this.map.addOverlay(points[index]);
-    //       // // 创建图文信息窗口(点击标记)
-    //       // this.mark(points[index], item);
-    //       // this.content(item.lng, item.lat, item.txt);
-    //     });
-
-    //     // this.animations();
-    //   }
-
-    //   // 创建标记标注内容
-    // },
-    // 创建图文信息窗口(点击标记)
-    //   mark(marker, item) {
-    //     // 创建图文信息窗口
-    //     // console.log(marker, item);
-    //     let _this = this;
-    //     var sContent = `<div style="display:flex;flex-direction: column;justify-content: center;align-items: center;">
-    //     <h3 style='padding:0;margin:0 0 5px 0'>${item.date}</h3>
-    //     <div style='margin:0 0 0 0;padding:0'>${item.txt}</div>
-    //   <img style='margin:15px 0' id='imgDemo' src='${item.img}' width='139' height='104'/>
-    //  </div>`;
-    //     var infoWindow = new BMapGL.InfoWindow(sContent);
-    //     // marker添加点击事件
-    //     marker.addEventListener("click", function() {
-    //       this.openInfoWindow(infoWindow);
-    //       // 图片加载完毕重绘infoWindow
-    //       document.getElementById("imgDemo").onclick = e => {
-    //         _this.imgSrc = item.img;
-    //         _this.scaleImg = true;
-    //         // console.log("onmouseover", e);
-    //       };
-    //       document.getElementById("scaleImg").onclick = () => {
-    //         // _this.img = "";
-    //         _this.scaleImg = false;
-    //         // console.log("onmouseout");
-    //       };
-    //       document.getElementById("imgDemo").onload = function() {
-    //         infoWindow.redraw(); // 防止在网速较慢时生成的信息框高度比图片总高度小,导致图片部分被隐藏
-    //       };
-    //     });
-    //     marker.setTop(true, 27000000);
-    //   },
-    // 创建标记标注内容
-    // content(lng, lat, txt) {
-    //   var opts = {
-    //     position: new BMapGL.Point(lng, lat), // 指定文本标注所在的地理位置
-    //     offset: new BMapGL.Size(10, -40) // 设置文本偏移量
-    //   };
-    //   // 创建文本标注对象
-    //   var label = new BMapGL.Label(txt, opts);
-    //   // 自定义文本标注样式
-    //   label.setStyle({
-    //     color: "red",
-    //     borderRadius: "5px",
-    //     borderColor: "#ccc",
-    //     padding: "5px",
-    //     fontSize: "12px",
-    //     height: "24px",
-    //     lineHeight: "24px",
-    //     fontFamily: "微软雅黑"
-    //   });
-    //   this.map.addOverlay(label);
-    // },
-    // 创建动画
-    // animations() {
-    //   // console.log(this.point);
-    //   let arr = [];
-    //   var path = this.point;
-    //   var point = [];
-    //   for (let i = 0; i < path.length; i++) {
-    //     point.push(new BMapGL.Point(path[i].lng, path[i].lat));
-    //   }
-    //   this.start(point);
-    // },
-    // start(point) {
-    // var lushu;
-    // // 路线宽度和颜色
-    // this.map.addOverlay(
-    //   new BMapGL.Polyline(point, {
-    //     strokeColor: "#4d5dfa",
-    //     strokeWeight: 4,
-    //     strokeOpacity: 0.5
-    //   })
-    // );
-    // this.map.setViewport(point);
-    // //步行图标
-    // var fly = require("@/assets/walk.png");
-    // let data = [];
-    // console.log(point);
-    // this.point.forEach((item, index) => {
-    //   // console.log(item);
-    //   if (index !== 0) {
-    //     data.push({
-    //       lng: item.lng,
-    //       lat: item.lat,
-    //       html: `
-    //   <h4 style='margin:0 0 10px 0;'>${item.txt}</h4>`,
-    //       pauseTime: 2
-    //     });
-    //   }
-    // });
-    // // console.log(this.point);
-    // if (BMapGLLib.LuShu) {
-    //   lushu = new BMapGLLib.LuShu(this.map, point, {
-    //     defaultContent: "轨迹路线", // "信息窗口文案"
-    //     autoView: true, // 是否开启自动视野调整,如果开启那么路书在运动过程中会根据视野自动调整
-    //     speed: 20,
-    //     // icon: new BMapGL.Icon('./images/car.png', new BMapGL.Size(32, 32), { anchor: new BMapGL.Size(10, 10) }),
-    //     icon: new BMapGL.Icon(fly, new BMapGL.Size(30, 30), {
-    //       // anchor: new BMapGL.Size(0, 18)
-    //     }),
-    //     enableRotation: true // 是否设置marker随着道路的走向进行旋转
-    //   });
-    // } else {
-    //   alert("刷新页面");
-    // }
-    // this.lushu = lushu;
-    // this.run();
-    // },
-
-    // run() {
-    //   //开始
-
-    //   this.lushu.start();
-    // },
-    // stop() {
-    //   //停止
-    //   this.lushu.stop();
-    // },
-    // // pause() {
-    // //   //暂停
-    // //   this.lushu.pause();
-    // // },
-    // hide() {
-    //   //隐藏信息窗口
-    //   this.lushu.hideInfoWindow();
-    // },
-    // show() {
-    //   //展示信息窗口
-    //   this.lushu.showInfoWindow();
-    // },
-    // 展开按钮
-    // 展开和关闭按钮
     spread() {
       let list = document.getElementsByClassName("list")[0];
-
       if (this.move == "展开") {
         this.startMove(0);
         this.move = "关闭";
@@ -582,12 +377,14 @@ export default {
     },
     startMove(iTarget) {
       let box = document.getElementsByClassName("list")[0];
+      if (!box) return;
       clearInterval(this.timer);
       this.timer = setInterval(() => {
         let speed = (iTarget - box.offsetLeft) / 15;
         speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
         if (box.offsetLeft == iTarget) {
           clearInterval(this.timer);
+          this.timer = null;
         } else {
           box.style.left = box.offsetLeft + speed + "px";
         }
@@ -595,8 +392,8 @@ export default {
     },
     black() {
       this.$router.back();
-    }
-  }
+    },
+  },
 };
 </script>
 <style scoped lang="less">

+ 1 - 1
src/components/portrait/login.vue

@@ -43,7 +43,7 @@ export default {
       this.API.login
         .login(data)
         .then((res) => {
-          console.log(res);
+          // console.log(res);
           if (res.status == 201) {
             sessionStorage.setItem("key", res.data);
             this.$router.push({

+ 41 - 27
src/utils/request.js

@@ -1,46 +1,61 @@
 /****   request.js   ****/
 // 导入axios
-import axios from 'axios'
+import axios from "axios";
+import router from '@/router' // 引入路由实例,用来跳转登录
 // 使用element-ui Message做消息提醒
 // import Cookies from 'js-cookie'
 //1. 创建新的axios实例,
 const service = axios.create({
-    // 公共接口--这里注意后面会讲
-    baseURL: process.env.BASE_API,
-    // 超时时间 单位是ms,这里设置了100s的超时时间
-    timeout: 100 * 1000,
-
-})
+  // 公共接口--这里注意后面会讲
+  baseURL: process.env.BASE_API,
+  // 超时时间 单位是ms,这里设置了100s的超时时间
+  timeout: 100 * 1000,
+});
 // 2.请求拦截器
-service.interceptors.request.use(config => {
+service.interceptors.request.use(
+  (config) => {
     //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
     config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
     // config.headers = {
     //     'Content-Type': 'application/json' //配置请求头
     // }
     // config.headers = { 'Content-Type': 'application/x-www-form-urlencoded' } //配置请求头
-
+    // console.log(config, "请求拦截");
     //如有需要:注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
-    const token = sessionStorage.getItem('key')
+    const token = sessionStorage.getItem("key");
     if (token) {
-        // config.params = { 'admin_token': token } //如果要求携带在参数中
-        config.headers['token'] = token; //如果要求携带在请求头中
+      // config.params = { 'admin_token': token } //如果要求携带在参数中
+      config.headers["token"] = token; //如果要求携带在请求头中
     }
 
-
-    return config
-}, error => {
-    Promise.reject(error)
-})
-
-
+    return config;
+  },
+  (error) => {
+    Promise.reject(error);
+  }
+);
 
 // 3.响应拦截器
-service.interceptors.response.use(response => {
+service.interceptors.response.use(
+  (response) => {
     //接收到响应数据并成功后的一些共有的处理,关闭loading等
-
-    return response.data
-}, error => {
+    const res = response.data;
+    console.log(res.message, "响应拦截");
+    if (
+      res.message == "无效token,请重新登入" ||
+      res.message == "token为空"
+    ) {
+      // 1. 清除本地token
+      sessionStorage.clear();
+      //  this.$message.error(res.message);
+      // 2. 跳登录页
+      router.push('/login')
+      // 中断后续接口then逻辑,页面不会执行正常业务代码
+      return Promise.reject(res);
+    }
+    return res;
+  },
+  (error) => {
     /***** 接收到异常响应的处理开始 *****/
     // if (error && error.response) {
     //     // 1.公共错误处理
@@ -107,7 +122,6 @@ service.interceptors.response.use(response => {
     //         case 16008:
     //             error.message = '文件太大'
     //             break;
-
     //         default:
     //             error.message = `连接错误${error.response.status}`
     //     }
@@ -119,11 +133,11 @@ service.interceptors.response.use(response => {
     //     }
     //     error.message = '连接服务器失败'
     // }
-
     // Message.error(error.message)
     // /***** 处理结束 *****/
     // //如果不需要错误处理,以上的处理过程都可省略
     // return Promise.resolve(error.response)
-})
+  }
+);
 //4.导入文件
-export default service
+export default service;