VUE 中let that = this 或者 var that = this 有什么意义

在Vue开发中,由于this的动态指向特性,常常需要将this赋值给that来保持引用。例如,在事件处理函数中,this会根据调用位置改变,如在jQuery的点击事件中,this先是被点击的元素,在each循环内则变为循环中的当前元素。保存that是为了在后续操作中保持对原始对象的引用不变。

在vue 开发过程中我们经常会发现

 let  that = this

这样写有什么好处呢
首先要理解this,下面简述两点

1、this 永远指向一个对象
2、this 的指向取决于函数调用的位置
首先 this 指向的是一个对象,这个好理解,难就难在第二点,在JavaScript 中 一切都是对象,运行环境也是对象,this 的指向是动态的很难确定指向那个对象
举例:

$('#content').click(function(){
     //this是被点击的#content
     var that =this;
     $('.content').each(function(){
         //this是.content循环中当前的对象
         //that仍是刚才被点击我的#content
     })
 })

this指向的对象发生了变化,故需要在函数前将this指向的对象提前保存一下

<template> <!-- 客流OD--> <div class="layout-wrapper passengerflowOd-wrap"> <logo></logo> <animate-b-g-image name="passengerflowOd-wrap"></animate-b-g-image> <div class="header-wrapper" style="z-index: 200"> <img class="header-image" :src="titleSrc" /> <select-model :typeName="'客流OD'"></select-model> </div> <area-module class="left-wrap" :nowIndex="nowIndex" @getAreaInfo="customAreaData" ref="searchChild" @transferData="transferData" :editingStatus="editingStatus"> </area-module> <right-module class="right-wrap" :nowIndex="nowIndex" :isShowAllArea="showAllArea" :searchParams="searchParams" :rightMode="rightMode" :liquidFillChartInfo="liquidFillChartInfo" :odTableList="odTableList" @changeFlowEvent="changeFlowEvent" :flag="flag" @getLineMap="getLineMap" @enlargeBtn="enlargeBtn"> </right-module> <div class="od-line" v-show="showGraphicsMode && showCustomMode && !sliderDisabled"> <div> OD线 </div> <div class="od-slider"> <el-slider v-model="sliderOdLine" range :marks="marks" :max="legendList.oDNumMax" @change="changeOdLine" :disabled="sliderDisabled"> </el-slider> </div> </div> <div class="check-map" v-show="showGraphicsMode && showCustomMode"> <ul> <li v-for="(item, index) in options" :key="index" :class="[nowIndex == index ? 'checkType' : '']" @click="changeModule(item.value)"> <img :src="item.icon" alt="" /> <span>{{ item.label }}</span> </li> </ul> </div> <div class="legend-map" v-show="showGraphicsMode && showCustomMode"> <div class="item"> <div :class="['base-color','color-'+ 0]"></div> <span> {{legendList.oDNumMax}}</span> </div> <div class="item"> <div :class="['base-color','color-'+ 1]"></div> <span> {{legendList.oDNumMid}}</span> </div> <div class="item"> <div :class="['base-color','color-'+ 2]"></div> <span> {{legendList.oDNumMin}}</span> </div> </div> <!-- 站点线路地图 --> <div id="container" style="width:100%;height:100%" v-loading="isLoading" element-loading-background="rgba(255, 255, 255, 0)" element-loading-text="加载,请稍后..." element-loading-spinner="el-icon-loading"> </div> <!-- 站点搜索 --> <div class="siteSearch" v-show="savaState"> <el-select v-model="searchKeys" placeholder="请输入站点名" suffix-icon="el-icon-search" class="search-input" filterable remote clearable :remote-method="remoteMethod" @change="checkValue" @clear="clearMarker"> <el-option v-for="(item, index) in searchSiteValues" :key="index" :label="item.stationName + '('+ item.roadName +')'" :value="index"> </el-option> </el-select> </div> <div class="areaName" v-show="savaState"> <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :inline="true"> <el-form-item prop="name"> <el-input placeholder="设定区域名称" clearable v-model="ruleForm.name"> </el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">保存</el-button> </el-form-item> </el-form> </div> <InfoWindow v-show="showInfoWindow" ref="infoWindow" :itemObj="infoWindowData" :info-window="stationInfoWindow" :infoTitle="infoTitle" :expandStatus="false"></InfoWindow> <el-dialog :visible.sync="dialogVisible" :before-close="handleClose" id="DvelopmentTargets" custom-class="my-dialog"> <table-list :isSort="true" :tableData="tableDataEnlargeBtn" :colorCircle="true" style="max-height: 100%;padding: 0 20px;" /> </el-dialog> </div> </template> <script> import API_PASSENGEROD from '@/api/api_passengerOD' import VueSlider from 'vue-slider-component' import 'vue-slider-component/theme/default.css' import selectModel from "@/components/selectModel"; import "./../layout/layout.scss"; import InfoWindow from "@/components/stationInfoWindows.vue" import areaModule from "./areaModule"; import rightModule from "./rightModule"; import { AMapManager, lazyAMapApiLoaderInstance } from "vue-amap"; import tableList from "@/components/tableList"; let lineColor = null; // od线颜色 // 站点地图 let stationPathSimplifierIns = null; let showStations = null; let hideStations = null; // 线路地图 let linePathSimplifierIns = null; let showLine = null; let hideLine= null; // 选站点od let lineStationPathSimplifierIns = null; let showStationLine = null; let hideStationLine = null; // 区域地图 let areaPathSimplifierIns = null; let showAreaLine = null; let hideAreaLine = null; // 展示圆多边形 let circleCase = null; let polygonCase = null; let siteMarker = null; // 搜索站点 // 绘制编辑圆多边形 let circleEditor = null; let polyEditor = null; import AnimateBGImage from "@/components/AnimateBGImage"; import logo from '@/components/logo' let layer1 = null let layer2 = null let layer3 = null let markIcon1 = null let markIcon2 = null let markIcon3 = null export default { name: "passengerFlowOd", components: { selectModel, VueSlider, areaModule, rightModule, InfoWindow, tableList, AnimateBGImage, logo }, data() { return { max : null, mid : null, min : null, layerList : [], redIcon:require('../../assets/red.gif'), yellowIcon:require('../../assets/yellow.gif'), tableDataEnlargeBtn:[], dialogVisible:false, selectLineCase:{ data:[], id:'' }, showInfoWindow: false, stationInfoWindow: null, // 信息框 infoTitle:'', radius: '', center: [], path: [], pathArea: '', mouseTool: null, ruleForm: { name: '', }, rules: { name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }, { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' } ], }, searchSiteValues: [], // 模糊搜索数据 searchKeys: '', // 搜索关键词 siteCenter: [], // 搜索站点坐标 infoWindowData: [{ overviewTitle: '区域面积', overviewValue: '', }, { overviewTitle: '流入数量', overviewValue: '', }, { overviewTitle: '流出数量', overviewValue: '', } ], searchParams: {}, //查询条件 searchId: '', odTableList: [], //top10表格数据 titleSrc: require("../../assets/images/common/bcImg.png"), sliderOdLine: [null, null], odLineData: [], legendList: { oDNumMin: null, oDNumMid: null, oDNumMax: null, // OD最大 }, marks: {}, options: [{ value: 0, label: "站点", icon: require("../../assets/images/layout/lines.png"), }, { value: 1, label: "线路", icon: require("../../assets/images/layout/site.png"), }, { value: 2, label: "区域", icon: require("../../assets/images/layout/vehicle.png"), }, ], showGraphicsMode: true, showCustomMode: true, savaState: false, nowIndex: 0, //0 站点 1线路 2区域 checkModeIndex: '', // 自定义圆坐标 customCircleData: { radius: '', location: [], }, customPolygonData: { areaCoverage: '', // 面积 location: [], }, // 自定义矩形坐标 liquidFillChartInfo: { chartId: "coverAreaRateInfo", chartName: "流入/流出占比", chartValue: [0.4, 0.6], }, showAllArea: true, rightMode: true, dotOptions: [{ tooltip: 'always' }, { tooltip: 'always' }], isLoading: false, // od线加载 exportParams: {}, odLinePrams: { ODNumBefore: '', ODNumAfter: '', }, flag: false, // 流入流出渲染 editingStatus: true, allAreaState: false, // 全城od线 customState: false, // 自定义od线 stationMapData:[], lineMapData:[], checkLineObj:{ linePath:[], lineStationInfo:[], lineName:'', passengerNum:'', stationNum:"", timeImbalanceFactor:"", }, checkStationOd:[], map:null, sliderDisabled:false, stationMarkerArr:[], } }, methods: { /** * @Description: 清空地图信息 飞线图 站点 * @author konghaitao * @date 2023-2-16 */ clearMap(){ if(layer1 ){ layer1.setMap(null); layer2.setMap(null); layer3.setMap(null); } if(markIcon1){ markIcon1.setMap(null); markIcon2.setMap(null); } }, //放大功能 enlargeBtn(data) { console.log(data,'dataaa') $(".my-dialog").css({ margin: "0 auto ", width: "80%", 'max-height':data.tableList.length <= 10 ? '50%':"90%", padding: "1%", top: data.tableList.length <= 10 ? '20%' :'5%' }); this.tableDataEnlargeBtn = data this.dialogVisible = true; }, //关闭 handleClose(done) { $(".el-dialog__wrapper").css({ "z-index": "-11100", }); this.$nextTick(() => { done(); }); }, remoteMethod(query) { let that = this; if (query !== "") { setTimeout(() => { that.getSearchStation(query); }, 500); } }, getSearchStation(query) { API_PASSENGEROD .getStationInfo({ stationName: query, }) .then((response) => { if (response.code == 0) { this.searchSiteValues = response.value; } else { console.log(response.message); } }) .catch((error) => { console.log(error) }); }, // 站点搜索 checkValue(val) { var that = this; if (this.searchKeys !== "") { this.siteCenter = [that.searchSiteValues[val].longitude, that.searchSiteValues[val].latitude] this.$nextTick(() => { that.drawSiteMap() }) } }, drawSiteMap() { var that = this; siteMarker && this.map.remove(siteMarker) siteMarker = new AMap.Marker({ icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png", position: that.siteCenter, offset: new AMap.Pixel(-13, -30) }); siteMarker.setMap(that.map); this.map.setFitView([siteMarker]) }, // 清除覆盖 clearMarker() { siteMarker && this.map.remove(siteMarker) }, // 更改模块 changeModule(value) { this.odTableList = [] this.nowIndex = value }, getDay(day) { var today = new Date(); var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day; today.setTime(targetday_milliseconds); //注意,这行是关键代码 var tYear = today.getFullYear(); var tMonth = today.getMonth(); var tDate = today.getDate(); tMonth = this.doHandleMonth(tMonth + 1); tDate = this.doHandleMonth(tDate); return tYear + tMonth + tDate; }, doHandleMonth(month) { var m = month; if (month.toString().length == 1) { m = "0" + month; } return m; }, /**滑动od线 */ changeOdLine(val) { this.sliderOdLine = val; switch(this.nowIndex) { case 0: if(this.searchParams.platformIdOff == '' && this.searchParams.platformIdOn == '') { this.getStationMap(this.searchParams,false,0); } else { this.getStationMap(this.searchParams,false,1); } // false 滑动od线时不重置起始 break case 1: if(this.searchParams.lineId == '') { this.defaultLineOD(this.searchParams,false) } else { this.getLineStationPassengersOD(this.searchParams,false,1) } break case 2: this.getStationPathOfAreaInfo( this.searchParams, false) break } }, transferData(data) { this.map && this.map.clearMap(); this.searchParams = data; this.customState = false; this.allAreaState = false; this.sliderOdLine = [null, null]; console.log('bbbbbbb') console.log('cccc',new Loca.LinkLayer) this.getInfo(data) }, //获取当前模块所有信息 getInfo(data){ switch (this.nowIndex) { case 0: this.sliderDisabled = false; this.sliderOdLine = [null, null]; // 隐藏 线路 区域地图数据 linePathSimplifierIns && hideLine(); lineStationPathSimplifierIns && hideStationLine(); this.map && this.map.clearMap(); if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) } lineStationPathSimplifierIns && hideStationLine(); areaPathSimplifierIns && hideAreaLine(); // 清除线路 if(data.platformIdOff == '' && data.platformIdOn == ''){ this.showAllArea = true; this.getRoadOD(data); this.getStationMap(data,true,0); // //未选择站点图 }else { this.showAllArea = false; //查询表格信息及站点坐标 this.getStationOD() this.getStationMap(data,true,1); // 1为选站图 } break; case 1: //线路 // 隐藏站点地图 this.sliderOdLine = [null, null]; stationPathSimplifierIns && hideStations(); linePathSimplifierIns && hideLine(); lineStationPathSimplifierIns && hideStationLine(); this.map && this.map.clearMap(); if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) }; lineStationPathSimplifierIns && hideStationLine(); areaPathSimplifierIns && hideAreaLine(); if(data.lineId == '') { this.showAllArea = true; this.sliderDisabled = false; this.getLineOD() //线路top10 this.defaultLineOD(data,true); // 默认线路 }else { //查询单个线路信息 this.showAllArea = false; this.sliderDisabled = true; this.getLineSingelTable(); this.checkLineOD(data); } break; case 2: // 隐藏站点线路地图 this.sliderDisabled = false; this.sliderOdLine = [null, null]; linePathSimplifierIns && hideLine(); stationPathSimplifierIns && hideStations(); linePathSimplifierIns && hideLine(); this.map && this.map.clearMap(); if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) }; // 清除站点 // 清除站点od线 lineStationPathSimplifierIns && hideStationLine(); this.customAreaData(data.id) // 区域图+ 流入流出占比 this.getStationOfAreaInfo(data.id, true) // 自定义区域表格 console.log(data,'33333') this.getStationPathOfAreaInfo(data, true) // 自定义区域Od线 // } break; } }, //查询单个线路信息 getLineSingelTable(){ let params = this.searchParams if(!params.lineId){ return } params.top = 10 API_PASSENGEROD.getRoadSectionPassenger(params).then(response => { if(response.value.length){ this.showAllArea = false this.odTableList = response.value console.log( this.odTableList ,'查询单个线路信息') }else { this.odTableList = [] } }).catch(err =>{ this.$message.error(err); }) }, //查询线路top10 getLineOD(){ let params = this.searchParams params.byLine = true params.top = 10 API_PASSENGEROD.getRegionalTravelOD(params).then(response=>{ if(response.value.length){ this.showAllArea = true this.odTableList = response.value } else { this.odTableList = [] } }).catch(err =>{ this.$message.error(err); }) }, //获取站点表格数据及坐标 getStationOD(flag){ // if(flag){ // this.searchParams.platformIdOff = this.searchParams.stationPointId // this.searchParams.platformIdOn = null // } else { // this.searchParams.platformIdOn = this.searchParams.stationPointId // this.searchParams.platformIdOff = null // } API_PASSENGEROD.getStationOD( this.searchParams).then(response => { console.log(response,'表格数据') if(response.value.length){ this.showAllArea = false this.odTableList = response.value } else { this.odTableList = [] } }).catch(err =>{ this.$message.error(err); }) }, getLineMap(data) { var that = this; if( data.id === that.selectLineCase.id){ that.map.remove( that.selectLineCase.data); that.selectLineCase = { data :[], id :'', } } else { that.demo(data) } }, demo(data){ var that = this; that.map.remove(that.selectLineCase.data); that.selectLineCase = { data :[], id :'', } let newRouteLine = new AMap.Polyline({ path: data.stationLocation, strokeColor: "#a9db35", isOutline: false, geodesic: true, // 大地线 strokeOpacity: 1, strokeWeight: 4, strokeStyle: "solid", strokeDasharray: [10, 5], lineJoin: "round", lineCap: "round", borderWeight: 2, outlineColor: "transparent", }); that.selectLineCase = { data:newRouteLine, id:data.id } newRouteLine.setMap(that.map); }, /* initMapData(data) { var that = this; this.odLineData = []; this.isLoading = true; let params = data; params.ODNumBefore = this.sliderOdLine[0]; params.ODNumAfter = this.sliderOdLine[1]; API_PASSENGEROD .getODNum3(params) .then((response) => { if (response.code === 0) { if (this.allAreaState) { let data = response.value.stationPathDto.splice(0, 100); if (data.length > 0) { data.map((item, index) => { that.odLineData.push({ oDNum: item.oDNum, path: [ [item.startLongitude, item.startLatitude], [item.endLongitude, item.endLatitude] ], startStationName: item.startStationName, endStationName: item.endStationName, }) }) this.isLoading = false; } else { this.isLoading = false; } } else { this.legendList.oDNumMin = response.value.oDNumMin; this.legendList.oDNumMid = response.value.oDNumMid; this.legendList.oDNumMax = response.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; this.sliderOdLine = [0, this.legendList.oDNumMax] let data = response.value.stationPathDto.splice(0, 100); if (data.length > 0) { data.map((item, index) => { that.odLineData.push({ oDNum: item.oDNum, path: [ [item.startLongitude, item.startLatitude], [item.endLongitude, item.endLatitude] ], startStationName: item.startStationName, endStationName: item.endStationName, }) }) this.isLoading = false; } else { this.isLoading = false; } } } else { this.isLoading = false; console.log(response.message); } }) .catch((error) => { this.isLoading = false; this.$message.error(error); }); },*/ //查询 自定义区域数据(地图及流入流出占比) customAreaData(id) { var that = this; let params = this.searchParams; params.id = id; this.customCircleData.location = []; // 圆区域 this.customPolygonData.location = []; // 多边行区域 if (id !== '') { that.flag = false; API_PASSENGEROD.getAreaInfo(params).then((response) => { if (response.code == 0) { // 圆 if (response.value.areaType == 0) { this.customCircleData.radius = response.value.radius; this.customCircleData.location = [response.value.stationLocationDtoList[0].lng, response.value .stationLocationDtoList[0].lat ]; this.circleMarker(this.customCircleData); // 绘制圆 } else if (response.value.areaType == 1) { // 矩形 this.customPolygonData.areaCoverage = response.value.areaCoverage; let data = response.value.stationLocationDtoList; data.map((item, index) => { this.customPolygonData.location.push( [item.lng, item.lat] ) }) // 绘制矩形 this.polygonMarker(this.customPolygonData); }; this.liquidFillChartInfo = { chartId: "coverAreaRateInfo", chartName: "流入/流出占比", chartValue: [], chartTitle: ['流入率', '流出率'] } if (response.value.inflowProportion == null || response.value.outflowProportion == null) { this.liquidFillChartInfo.chartValue.push(0) this.liquidFillChartInfo.chartValue.push(0) } else { this.liquidFillChartInfo.chartValue.push(response.value.inflowProportion) this.liquidFillChartInfo.chartValue.push(response.value.outflowProportion) } this.infoWindowData = [{ overviewTitle: '区域面积', overviewValue: response.value.areaCoverage, }, { overviewTitle: '流入数量', overviewValue: response.value.inflowPassengers, }, { overviewTitle: '流出数量', overviewValue: response.value.outflowPassengers, } ]; this.$nextTick(() => { that.flag = true; }); } else { this.$message({ message: response.message, type: 'warning' }); } }).catch((error) => { console.log(error) }) } else { this.customCircleData.location = []; this.customPolygonData.location = []; } }, circleMarker(val) { var that = this; // 先清除之前的图形 circleCase && this.map.remove(circleCase) polygonCase && this.map.remove(polygonCase) circleCase = new AMap.Circle({ center: val.location, radius: val.radius, //半径 borderWeight: 3, strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, strokeStyle: 'dashed', strokeDasharray: [10, 10], // 线样式还支持 'dashed' fillColor: '#1791fc', zIndex: 50, }) circleCase.setMap(this.map) that.map.setCenter(val.location) // 缩放地图到合适的视野级别 // this.map.setFitView([circleCase]) circleCase.on("click", function (e) { that.setInfoWindows(e.lnglat); }); }, polygonMarker(val) { var that = this; circleCase && this.map.remove(circleCase) polygonCase && this.map.remove(polygonCase) polygonCase = new AMap.Polygon({ path: val.location, strokeColor: "#FF33FF", strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, fillColor: '#1791fc', zIndex: 50, }) this.map.add(polygonCase); polygonCase.on("click", function (e) { that.setInfoWindows(e.lnglat); }); // 缩放地图到合适的视野级别 that.map.setCenter(val.location) // this.map.setFitView([polygonCase]) }, setInfoWindows(e) { var that = this; this.showInfoWindow = true; const infoWindow = new AMap.InfoWindow({ isCustom: true, anchor: "bottom-center", content: this.$refs['infoWindow'].$el, offset: new AMap.Pixel(0, -10), autoMove: true, closeWhenClickMap: true, }); this.stationInfoWindow = infoWindow; this.infoTitle = '基础指标'; // 信息窗口打开 infoWindow.open(that.map, e); }, // 保存后 查询自定义区域地图+ OD线+ 右侧表格+ 图表 seachCustomArea(id, name) { this.editingStatus = true; this.showGraphicsMode = true; this.showCustomMode = true; this.showAllArea = false; this.savaState = false; this.rightMode = true; this.customAreaData(id) // 区域图+ 流入流出占比 this.searchParams.id = id; this.getStationPathOfAreaInfo(this.searchParams, true) // 自定义区域Od线 this.getStationOfAreaInfo(id, true) // 自定义区域表格 this.$refs.searchChild.$emit('childMethod', id, name) // 左侧自定义区域id及名称,保存后改变新增区域状态 }, //选择新增区域类型 checkMode(val) { this.map.clearMap(); this.clearMap(); this.ruleForm.name = ''; this.searchKeys = ''; // this.checkModeIndex = data.label; if (val.label == '图形模式') { if (val.isSelect) { this.showGraphicsMode = false; this.savaState = true; this.rightMode = false; areaPathSimplifierIns && hideAreaLine(); this.mouseTool && this.mouseTool.close(true); circleEditor && circleEditor.close(); this.drawCircleMap() } else { this.showGraphicsMode = true; this.showCustomMode = true; this.savaState = false; this.rightMode = true; areaPathSimplifierIns && showAreaLine(); this.mouseTool && this.mouseTool.close(true); } } else if (val.label == '自定义模式') { if (val.isSelect) { // 选 this.showCustomMode = false; this.savaState = true; this.rightMode = false; areaPathSimplifierIns && hideAreaLine(); this.mouseTool && this.mouseTool.close(true); polyEditor && polyEditor.close(); this.drawPolygonMap() } else { this.showGraphicsMode = true; this.showCustomMode = true; this.savaState = false; this.rightMode = true; areaPathSimplifierIns && showAreaLine(); this.mouseTool && this.mouseTool.close(true); } } }, // 编辑圆 drawCircleMap() { var that = this; this.mouseTool = new AMap.MouseTool(this.map); this.mouseTool.circle({ strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillColor: "#1791fc", fillOpacity: 0.4, strokeStyle: "solid", }); this.mouseTool.on("draw", function (event) { that.radius = event.obj.De.radius.toFixed(0); let centerLng = event.obj.De.center.lng; let centerLat = event.obj.De.center.lat; let position = [centerLng, centerLat]; that.center = [{ lat: centerLat, lng: centerLng }] that.map.clearMap() // 先拿到绘制好的半径圆心再清除进入编辑 var circle = new AMap.Circle({ center: position, radius: that.radius, //半径 borderWeight: 3, strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, strokeStyle: "dashed", strokeDasharray: [10, 10], fillColor: "#1791fc", zIndex: 50, }); circle.setMap(that.map); that.map.setFitView([circle]); circleEditor = new AMap.CircleEditor(that.map, circle); circleEditor.open(); circleEditor.on("move", function (event) {}); circleEditor.on("adjust", function (event) {}); circleEditor.on("end", function (event) { that.radius = event.target.w.radius.toFixed(0); let centerLng = event.target.w.center.lng; let centerLat = event.target.w.center.lat; that.center = [{ lat: centerLat, lng: centerLng }] }); }); }, // 编辑矩形 drawPolygonMap() { var that = this; this.mouseTool = new AMap.MouseTool(this.map); this.mouseTool.polygon({ strokeColor: "#FF33FF", strokeOpacity: 1, strokeWeight: 6, strokeOpacity: 0.2, fillColor: "#1791fc", fillOpacity: 0.4, strokeStyle: "solid", }); this.mouseTool.on("draw", function (event) { that.path = event.obj.w.path; that.map.clearMap(); var polygon = new AMap.Polygon({ path: that.path, strokeColor: "#FF33FF", strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, fillColor: '#1791fc', zIndex: 50, }) that.pathArea = polygon.getArea(); // 编辑前的面积 that.map.add(polygon) that.map.setFitView([polygon]); polyEditor = new AMap.PolyEditor(that.map, polygon); polyEditor.open(); polyEditor.on('addnode', function (event) {}) polyEditor.on('adjust', function (event) {}) polyEditor.on('removenode', function (event) {}) polyEditor.on('end', function (event) { that.path = event.target.w.path; // 编辑后面积 that.pathArea = Math.round(AMap.GeometryUtil.ringArea(event.target.w.path)); }) }); }, // 保存 onSubmit() { var that = this; this.$refs.ruleForm.validate((valid) => { if (valid) { if (!that.showGraphicsMode) { // 圆 that.circleOdLine() } else if (!that.showCustomMode) { // 多边形 that.polygonOdLine() } } else { console.log('error submit!!'); return false; } }); }, // 图形模式保存 circleOdLine() { var that = this; let params = { areaName: this.ruleForm.name, areaType: 0, // 区域类型 radius: this.radius, location: this.center, } API_PASSENGEROD.saveAreaInfo(params).then((response) => { if (response.code == 0) { this.map.clearMap(); let id = response.value; this.mouseTool.close(); circleEditor && circleEditor.close(); this.seachCustomArea(id, this.ruleForm.name) } else { this.$message({ message: response.message, type: 'warning' }); } }).catch((error) => { this.$message({ message: error, type: 'warning' }); }) }, // 自定义模式保存 polygonOdLine() { let location = []; this.path.map((item, index) => { location.push({ lat: item.lat, lng: item.lng }) }) let params = { areaName: this.ruleForm.name, areaType: 1, // 区域类型 location: location, areaCoverage: this.pathArea, } API_PASSENGEROD.saveAreaInfo(params).then((response) => { if (response.code == 0) { this.map.clearMap(); let id = response.value; this.mouseTool.close(); polyEditor && polyEditor.close(); this.seachCustomArea( id, this.ruleForm.name); } else { this.$message({ message: response.message, type: 'warning' }); } }).catch((error) => { this.$message({ message: error, type: 'warning' }); }) }, //右侧全城区域top10表格 getRoadOD(data) { let params = { startTime: data.startTime, endTime: data.endTime, peakSection: data.peakSection, isWeekday: data.isWeekday, top: 10, } API_PASSENGEROD.getRegionalTravelOD(params).then(res => { if (res.code == 0 && res.value.length != 0) { this.odTableList = res.value } else { this.odTableList = []; this.$message.error('未查询到 线路OD Top10 数据') } }) }, // 站点od getStationMap(data,status,isStationId){ this.isLoading = true; let params = {}; params.startTime = data.startTime; params.endTime = data.endTime; params.byLine =false; params.top = 100; params.ODNumBefore =this.sliderOdLine[0]; params.ODNumAfter =this.sliderOdLine[1]; if(isStationId == 0) { params.platformIdOn =''; params.platformIdOn =''; params.peakSection =''; params.isWeekday= ''; } else { params.platformIdOn=data.platformIdOn; params.platformIdOff=data.platformIdOff; params.peakSection=data.peakSection; params.isWeekday=data.isWeekday; } this.stationMapData = []; API_PASSENGEROD.getODNum3(params).then(res => { if(res.code == 0) { this.legendList.oDNumMin = res.value.oDNumMin; this.legendList.oDNumMid = res.value.oDNumMid; this.legendList.oDNumMax = res.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status){ this.sliderOdLine = [0, this.legendList.oDNumMax] } this.stationMapData = res.value this.drawStationMap(); } else { this.isLoading = false; console.log(res.message) } }).catch((error)=>{ this.isLoading = false; console.log(error.msg) }) }, //绘制飞线图 drawStationMap() { var that = this; if(stationPathSimplifierIns !== null){ showStations(); } else { AMapUI.loadUI( ["misc/PathSimplifier", "misc/PointSimplifier"], (PathSimplifier, PointSimplifier) => { if (!PathSimplifier.supportCanvas) { alert("当前环境不支持 Canvas!"); return; } // od线 let oDMaxList = this.stationMapData.oDMaxList let oDMidList = this.stationMapData.oDMidList let oDMinList = this.stationMapData.oDMinList let red = this.stationMapData.red let yellow = this.stationMapData.yellow let arr = [oDMaxList,oDMidList,oDMinList] let iconList = [red,yellow] that.renderLayerMark(arr,iconList) }); } }, // 默认线路 defaultLineOD(data,status){ lineStationPathSimplifierIns && hideStationLine(); this.isLoading = true; let params = { startTime: data.startTime, endTime: data.endTime, ODNumBefore:this.sliderOdLine[0], ODNumAfter:this.sliderOdLine[1], byLine:true, top:100, } this.lineMapData = []; API_PASSENGEROD.getODNum3(params).then(res => { if(res.code == 0) { this.legendList.oDNumMin = res.value.oDNumMin; this.legendList.oDNumMid = res.value.oDNumMid; this.legendList.oDNumMax = res.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status){ this.sliderOdLine = [0, this.legendList.oDNumMax] } this.sliderOdLine = res.value this.drawLineMap(); } else { this.isLoading = false; console.log(res.message) } }).catch((error)=>{ this.isLoading = false; console.log(error.msg) }) }, drawLineMap() { var that = this; if(linePathSimplifierIns !== null) { showLine(); } else { AMapUI.loadUI( ["misc/PathSimplifier", "misc/PointSimplifier"], (PathSimplifier, PointSimplifier) => { if (!PathSimplifier.supportCanvas) { alert("当前环境不支持 Canvas!"); return; } let oDMaxList = this.sliderOdLine.oDMaxList let oDMidList = this.sliderOdLine.oDMidList let oDMinList = this.sliderOdLine.oDMinList let red = this.sliderOdLine.red let yellow = this.sliderOdLine.yellow let arr = [oDMaxList,oDMidList,oDMinList] let iconList = [red,yellow] that.renderLayerMark(arr,iconList) }); } }, // 选线路 checkLineOD(data){ this.sliderDisabled = true; // 先清除之前线路 if(this.stationMarkerArr.length > 0) { this.stationMarkerArr.map((item,index)=>{ this.map.remove(item); }) } this.map.clearMap(); this.stationMarkerArr = []; this.checkLineObj.lineStationInfo = []; let params = { lineId:data.lineId, direction:data.direction , startTime: data.startTime, endTime: data.endTime, peakSection:data.peakSection, isWeekday:data.isWeekday, } API_PASSENGEROD.getLinePassengerODBaseInfo(params).then(res => { if(res.code == 0) { console.log(layer1,'layer1') if(layer1){ layer1.setMap(null); layer2.setMap(null); layer3.setMap(null); } if(markIcon1){ markIcon1.setMap(null); markIcon2.setMap(null); } let data = res.value; this.checkLineObj.linePath = JSON.parse(data.linePath); data.lineStationInfo.map((item,index)=>{ let obj = {}; obj.center = [item.longitude,item.latitude]; obj.name = item.stationName; obj.stationId = item.stationId; this.checkLineObj.lineStationInfo.push(obj); }) this.checkLineObj.lineName = data.lineName; this.checkLineObj.passengerNum = data.passengerNum; this.checkLineObj.stationNum = data.stationNum; this.checkLineObj.timeImbalanceFactor = data.timeImbalanceFactor; this.$nextTick(()=>{ this.getcheckLineMap(this.checkLineObj.linePath,this.checkLineObj.lineStationInfo); }) } else { console.log(res.message) } }).catch((error)=>{ console.log(error.msg) }) }, getcheckLineMap(path,stations){ var that = this; // 站点 let iconStyle = new AMap.Icon({ size: new AMap.Size(15, 15), image: require("@/assets/images/layout/selected-vehicle.png"), imageSize: new AMap.Size(15, 15), }); this.stationMarkerArr = []; stations.forEach((marker) => { var stationMarker= new AMap.Marker({ icon: iconStyle, map: this.map, offset: new AMap.Pixel(-8, -8), position: [marker.center[0], marker.center[1]], }); stationMarker.setLabel({ offset: new AMap.Pixel(5, 20), //设置文本标注偏移量 content: marker.name, direction: "right", //设置文本标注方位 }); that.stationMarkerArr.push(stationMarker); // 点击显示站点od stationMarker.on("click", () => { this.searchParams.stationId = marker.stationId; this.getLineStationPassengersOD(this.searchParams,true,0) }); }); // 线路 // 定义线的风格 var polyline = new AMap.Polyline({ path: path, isOutline: true, outlineColor: "#49C3FC", borderWeight: 1, strokeColor: "#49C3FC", strokeOpacity: 1, strokeWeight: 2, strokeStyle: "solid", strokeDasharray: [10, 5], lineJoin: "round", lineCap: "round", zIndex: 10, }); polyline.setMap(this.map); // 线路 // 路线的起始点 var startMarker = new AMap.Marker({ position: path[0], icon: "https://webapi.amap.com/theme/v1.3/markers/n/start.png", map: this.map, }); var endMarker = new AMap.Marker({ position: path[path.length - 1], icon: "https://webapi.amap.com/theme/v1.3/markers/n/end.png", map: this.map, }); startMarker.setMap(this.map); endMarker.setMap(this.map); // 缩放地图到合适的视野级别 this.map.setFitView([polyline, startMarker, endMarker]); }, // 线路站点基本信息 getLineStationPassengersOD(val,status,initStatus){ // 首次点击无od量 this.isLoading = true; this.sliderDisabled = false; let params = {}; params.lineId = val.lineId; params.direction = val.direction; params.stationId = val.stationId; params.startTime = val.startTime; params.endTime = val.endTime; params.peakSection = val.peakSection; params.isWeekday = val.isWeekday; if(initStatus == 0){ params.ODNumBefore = ''; params.ODNumAfter = ''; } else { params.ODNumBefore =this.sliderOdLine[0]; params.ODNumAfter = this.sliderOdLine[1]; } this.checkStationOd = []; API_PASSENGEROD.getLineStationPassengersOD2(params).then(res => { if(res.code == 0) { this.legendList.oDNumMin = res.value.oDNumMin; this.legendList.oDNumMid = res.value.oDNumMid; this.legendList.oDNumMax = res.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status){ this.sliderOdLine = [0, this.legendList.oDNumMax] } this.checkStationOd = res.value this.$nextTick(()=>{ this.checkStationOdMap(); }) this.isLoading = false; } else { console.log(res.message); this.isLoading = false; } }).catch((error)=>{ console.log(error.msg); this.isLoading = false; }) }, // 选择线路站点 checkStationOdMap(){ var that = this; if(lineStationPathSimplifierIns !== null) { showStationLine() } else { AMapUI.loadUI( ["misc/PathSimplifier", "misc/PointSimplifier"], (PathSimplifier, PointSimplifier) => { if (!PathSimplifier.supportCanvas) { alert("当前环境不支持 Canvas!"); return; } let oDMaxList = this.checkStationOd.oDMaxList let oDMidList = this.checkStationOd.oDMidList let oDMinList = this.checkStationOd.oDMinList let red = this.checkStationOd.red let yellow = this.checkStationOd.yellow let arr = [oDMaxList,oDMidList,oDMinList] let iconList = [red,yellow] that.renderLayerMark(arr,iconList) }); } }, /** * @Description: 创建飞线图及高亮站点 * @author konghaitao * @date 2023-2-20 * @params arr 飞线图数组 iconList 图标数组 */ renderLayerMark(arr,iconList){ //倒叙创建覆盖 let that = this let colors = [ "#FF0000", "#FFC402", "#4E79E9", ]; let icons = [this.redIcon,this.yellowIcon] that.clearMap() layer3 = new Loca.LinkLayer({ map: that.map, fitView: false, }); layer3.setData(arr[2], { lnglat: 'lnglat' }); layer3.setOptions({ style: { // 曲率 [-1, 1] 区间 curveness: function(data) { if(data.value.dis < 300){ return 0.005; } else { return 0.001; } }, borderWidth: 1.5, width: 1, opacity: 0.8, color: colors[2] } }); layer2 = new Loca.LinkLayer({ map: that.map, fitView: false, }); layer2.setData(arr[1], { lnglat: 'lnglat' }); layer2.setOptions({ style: { // 曲率 [-1, 1] 区间 curveness: function(data) { if(data.value.dis < 300){ return 0.005; } else { return 0.001; } }, width: 1, opacity: 0.8, color: colors[1] } }); layer1 = new Loca.LinkLayer({ map: that.map, fitView: false, }); layer1.setData(arr[0], { lnglat: 'lnglat' }); layer1.setOptions({ style: { // 曲率 [-1, 1] 区间 curveness: function(data) { if(data.value.dis < 300){ return 0.005; } else { return 0.001; } }, width: 1, opacity: 0.8, color: colors[0] } }); layer1.render(); layer2.render(); layer3.render(); if(iconList){ markIcon2 = new Loca.IconLayer({ map: that.map, fitView: true, }); markIcon2.setData(iconList[1], { lnglat: 'center' }); markIcon2.setOptions({ source: function (res) { return icons[1]; }, style: { size: 28, } }); markIcon2.render(); markIcon1 = new Loca.IconLayer({ map: that.map, fitView: true, }); markIcon1.setData(iconList[0], { lnglat: 'center' }); markIcon1.setOptions({ source: function (res) { return icons[0]; }, style: { size: 28, } }); markIcon1.render(); } that.$nextTick(()=>{ that.isLoading = false; }) }, changeFlowEvent(data) { // let params = this.searchParams; switch (this.nowIndex) { case 0: this.getStationOD() break case 1: break case 2: this.getStationOfAreaInfo(this.searchId, data); this.getStationPathOfAreaInfo(this.searchId, data) // 自定义区域Od线 break } }, getStationOfAreaInfo(id, data) { let params = this.searchParams; params.id = id; params.flowChoose = data; params.top = 1000; this.searchId = id; API_PASSENGEROD .getStationOfAreaInfo(params) .then((response) => { if (response.code === 0) { this.odTableList = response.value } else { console.log(response.message); } }) .catch((error) => { this.$message.error(error); }); }, getStationPathOfAreaInfo(data, status) { console.log(data.id,'aaaa') var that = this; this.odLineData = []; this.isLoading = true; let params = { id:data.id, startTime:data.startTime, endTime:data.endTime, peakSection:data.peakSection, isWeekday:data.isWeekday, flowChoose:data.flowChoose, ODNumBefore: this.sliderOdLine[0], ODNumAfter:this.sliderOdLine[1], } API_PASSENGEROD .getStationPathOfAreaInfo2(params) .then((response) => { if (response.code === 0) { this.legendList.oDNumMin = response.value.oDNumMin; this.legendList.oDNumMid = response.value.oDNumMid; this.legendList.oDNumMax = response.value.oDNumMax; let keyData = [0, this.legendList.oDNumMin, this.legendList.oDNumMid, this.legendList.oDNumMax]; let valData = [String(0), String(this.legendList.oDNumMin), String(this.legendList.oDNumMid), String( this.legendList.oDNumMax)] let obj = {}; for (let i = 0; i < valData.length; i++) { const key = keyData[i]; obj[key] = valData[i] } this.marks = obj; if(status) { this.sliderOdLine = [0, this.legendList.oDNumMax] } that.odLineData = response.value this.areaOdLineMap(); } else { this.isLoading = false; console.log(response.message); } }) .catch((error) => { this.isLoading = false; this.$message.error(error); }); }, // 区域od线 areaOdLineMap(){ var that = this; if(areaPathSimplifierIns !== null){ showAreaLine(); } else { AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function (PathSimplifier, $) { if (!PathSimplifier.supportCanvas) { alert('当前环境不支持 Canvas!'); return; } let oDMaxList = that.odLineData.oDMaxList let oDMidList = that.odLineData.oDMidList let oDMinList = that.odLineData.oDMinList let arr = [oDMaxList,oDMidList,oDMinList] that.renderLayerMark(arr) }); } }, // 初始化地图 initMap() { lazyAMapApiLoaderInstance.load().then(() => { this.map = new AMap.Map(document.getElementById("container"), { mapStyle: "amap://styles/9824f612cff8dc63104cff89ddfd1a93", expandZoomRange: true, zoom: 13, zooms: [3, 21], resizeEnable: false, center: [117.38, 32.92], keyboardEnable: false, zoomEnable: true, dragEnable: true, animateEnable: true, viewMode: '3D', pitch: 30, }); }); }, }, mounted() { this.$bus.$on('checkMode', (data) => { this.checkMode(data); if(data.type == 1){ //type为1 新增区域模块 this.editingStatus = !data.isSelect; } }) console.log('aaaaaaaaaaaa') this.initMap(); }, created() { }, beforeDestroy() { this.$bus.$off("checkMode"); this.map = null; stationPathSimplifierIns = null; linePathSimplifierIns = null; lineStationPathSimplifierIns = null; areaPathSimplifierIns = null; this.clearMap() }, } </script> <style lang="scss" scoped> // PX 转 rem @function px2Rem($px, $base-font-size: 19.2px) { @if (unitless($px)) { //有无单位 @return ($px / 19.2) * 1rem; } @else if (unit($px)==em) { @return $px; } @return ($px / $base-font-size) * 1rem; } .passengerflowOd-wrap { .left-wrap { .modeList { float: left; position: relative; } .mode { width: px2Rem(150px); height: px2Rem(40px); text-align: center; line-height: px2Rem(40px); background-color: #fff; margin-right: px2Rem(10px); } .mask { position: absolute; left: 0px; top: 0px; width: px2Rem(150px); height: px2Rem(40px); border: 2px solid #2894ec; } } // 图例 .legend-map { position: absolute; bottom: px2Rem(55px); right: 28%; width: px2Rem(80px); height: px2Rem(100px); display: flex; justify-content: space-between; flex-direction: column; color: #fff; background: #001539; box-shadow: 0px 0px 8px 2px rgba(16, 108, 222, 0.8); border-radius: 4px; opacity: 0.8; z-index: 100; .item { height: px2Rem(30px); display: flex; flex-direction: row; // justify-content: start; justify-content: space-around; align-items: center; font-size: px2Rem(14px); margin: 0 15px 0px; .base-color { width: px2Rem(15px); height: px2Rem(6px); border-radius: 2px; } .color-0 { background: #FF0000; } .color-1 { background: #FFC402; } .color-2 { background: #4E79E9; } } } .od-line { position: absolute; bottom: px2Rem(55px); left: 28%; z-index: 100; font-size: px2Rem(18px); color: #fff; .od-slider { margin-top: px2Rem(10px); padding: px2Rem(7px) px2Rem(15px); width: px2Rem(250px); height: px2Rem(60px); background: #001539; box-shadow: 0px 0px 8px 2px rgba(16, 108, 222, 0.8); border-radius: 4px; z-index: 100; } } .siteSearch { position: absolute; top: px2Rem(100px); right: 28%; z-index: 100; } .areaName { position: absolute; bottom: px2Rem(55px); right: 28%; z-index: 100; } } </style> <style lang="scss"> // PX 转 rem @function px2Rem($px, $base-font-size: 19.2px) { @if (unitless($px)) { //有无单位 @return ($px / 19.2) * 1rem; } @else if (unit($px)==em) { @return $px; } @return ($px / $base-font-size) * 1rem; } // 站点名样式 .amap-marker-label { position: absolute; border: none; background-color: transparent; white-space: nowrap; cursor: pointer; padding: 3px; font-size: 9px; font-family: AlibabaPuHuiTiR; color: #ffffff; // l } </style> 分析当前代码,首次切换模块打印new Loca.LinKLayer报错,强制刷新后Loca功能才可使用,排查下原因
06-18
<template> <div class="insure-fill"> <div class="main"> <group class="gap"> <div class="card"> <p><span style="color: red;">*</span>请上传您的保费银行转账截图</p> <div class="photo"> <input type="file" id="upload_filePassport" ref="filePassport" class="upload__input" @change="uploadChangePassport" accept="image/*"> <div class="passport"></div> <div @click="upload_filePassport" class="imgUploadDiv"> <img :src="imgiDPassportUrl" alt=""> </div> </div> </div> </group> <div class="btn-login"> <flexbox> <flexbox-item> <x-button type="primary" @click.native="submitOtherInfor" :disabled="nextDisabled">提交</x-button> </flexbox-item> </flexbox> </div> </div> </div> </template> <script src="http://www.jq22.com/jquery/vue.min.js"></script> <script> import { XHeader, XInput, Group, XButton, Cell, Checker, CheckerItem, Datetime, Flexbox, FlexboxItem } from "vux" let time = null; export default { inject: ['reload'], components: { XHeader, XInput, XButton, Group, Cell, Checker, CheckerItem, Datetime, Flexbox, FlexboxItem }, data () { return { caseNo: '', imgName: '../../assets/img/customer/id_icon_add@2x.png', imgiDPassportUrl: '', imgList: [], imgFile: '', nextDisabled: false } }, mounted () { this.caseNo = this.$route.query.caseNo; this.getOtherInfor() }, methods: { goBack () { this.$router.go(-1) }, fileClick () { document.getElementById('upload_file').click() }, //选择图片 upload_filePassport () { clearTimeout(time); //首先清除计时器 time = setTimeout(() => { document.getElementById('upload_filePassport').click() }, 250) }, //获取图片 uploadChangePassport (e) { // 1. 先执行阻止操作 e.stopPropagation(); // 阻止冒泡 e.preventDefault(); // 阻止默认行为 // 2. 正确检测并打印状态(用事件属性,而非方法返回值) console.log('事件冒泡是否被阻止:', e.cancelBubble); // 标准浏览器输出 true console.log('默认行为是否被阻止:', e.defaultPrevented); // 标准浏览器输出 true // 3. 原有业务逻辑 this.uploadChange(e, 'imgiDPassport'); }, checkInfor () { if (this.imgList.imgiDPassport === undefined || this.imgList.imgiDPassport === "") { this.alert.methods.showModuleAuto('请上传付款证明') return false } return true }, loadImg (data) { let that = this if (data) { that.imageToBlob(data, function (blob) { console.log('url 转 blob'); console.log(blob); //付款证明 that.imgList.imgiDPassport = blob; }); } that.imgiDPassportUrl = data }, // image转Blob imageToBlob (src, cb) { let that = this; that.imageToCanvas(src, function (canvas) { cb(that.dataURLToBlob(that.canvasToDataURL(canvas))); }); }, imageToCanvas (src, cb) { var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = src; img.onload = function () { canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); console.log('canvas', canvas) cb(canvas); }; }, dataURLToBlob (dataurl) { console.log('dataurl', dataurl) var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }, canvasToDataURL (canvas, format, quality) { return canvas.toDataURL(format || 'image/jpeg', quality || 1.0); }, getOtherInfor () { this.bus.$emit('loading', true); this.$http.post(this.ApiUrl + '/confirmInsure/getPaymentProof', { caseNo: this.caseNo, }, { emulateJSON: true }).then(function (res) { this.bus.$emit('loading', false); if (res.data.code !== 0) { this.alert.methods.showModuleAuto(res.data.message) } else { console.log(res.data); if (res.data.data !== null) { console.log(res.data) if (res.data.data) { this.loadImg(res.data.data); } } } }, function (response) { this.bus.$emit('loading', false); console.log('请求失败啦'); }) }, submitOtherInfor () { if (this.checkInfor()) { let formData = new FormData(); formData.append("caseNo", this.caseNo) formData.append("proofFile", this.imgList.imgiDPassport, "proofFile.jpg"); this.bus.$emit('loading', true); this.nextDisabled = true this.$http.post(this.ApiUrl + '/confirmInsure/savePaymentProof', formData, { emulateJSON: true }).then(function (res) { this.bus.$emit('loading', false); if (res.data.code !== 0) { this.alert.methods.showModuleAuto(res.data.message) this.nextDisabled = false } else { let params = this.$encodeQuery(`${this.caseNo}`) this.$router.push(`/renewalDetail/${params}`); } }, function (response) { this.bus.$emit('loading', false); this.nextDisabled = false console.log('请求失败啦'); }) } }, //获取图片 uploadChange (e, imgType) { var that = this; let file = e.target.files[0]; if (file.size == 0) { return; } this.imgFile = file if (!/image\/\w+/.test(file.type)) { this.alert.methods.showModuleAuto("请选择图片"); return false; } var quality; if (file.size / 1024 < 512) { quality = 1 } else if (512 < file.size / 1024 < 1024) { quality = 0.5 } else if (1024 < file.size / 1024 < 3000) { quality = 0.2 } else if (3000 < file.size / 1024 < 5000) { quality = 0.1 } else if (5000 < file.size / 1024 < 10000) { quality = 0.06 } else if (10000 < file.size / 1024 < 20000) { quality = 0.03 } else { quality = 0.01 } this.compress(file, quality, function (base64Codes) { that.imgList.imgiDPassport = that.dataURLtoFile(base64Codes) }, imgType); console.log('that.imgList.imgiDPassport1', that.imgList.imgiDPassport) // 延迟100ms清空,避免浏览器重绘异常 setTimeout(() => { that.$refs.filePassport.value = null; }, 100); console.log('that.imgList.imgiDPassport2', that.imgList.imgiDPassport) }, canvasDataURL (path, q, fn, file) { var that = this; let img = new Image(); img.src = path; img.onload = function () { let that = this; console.log('that', that) let w = that.width, h = that.height, scale = w / h; w = 800; h = (w / scale); let quality = 0.8; //生成canvas let canvas = document.createElement('canvas'); let ctx = canvas.getContext('2d'); let anw = document.createAttribute("width"); anw.nodeValue = w; let anh = document.createAttribute("height"); anh.nodeValue = h; canvas.setAttributeNode(anw); canvas.setAttributeNode(anh); try { // 定义支持的MIME类型 const supportedMimeTypes = [ 'image/png', 'image/jpeg', 'image/gif', ]; const mimeType = supportedMimeTypes.find(type => type === file.type) || 'image/jpeg'; ctx.drawImage(that, 0, 0, w, h); quality = q; console.log('mimeType', mimeType); let base64 = canvas.toDataURL(mimeType, quality); fn(base64); } catch (e) { fn(path) } } }, compress (file, q, fn, imgType) { let ready = new FileReader(); ready.readAsDataURL(file); let that = this // 新增:捕获FileReader读取失败 ready.onerror = function (e) { console.error('FileReader读取异常:', e); that.alert.methods.showModuleAuto("图片读取失败"); }; ready.onload = function () { try { console.log('ready.onload', ready) let result = this.result; file.src = this.result // //尝试检测鸿蒙系统 // const isHarmonyOS = /harmonyos|arkweb/.test(navigator.userAgent.toLowerCase()); // if (isHarmonyOS) { // console.log('鸿蒙系统',navigator.userAgent); // // 鸿蒙系统下简化处理,不使用canvas压缩 // that.imgiDPassportUrl = result; // fn(result); // } else { // 其他系统使用原有处理 that.imgiDPassportUrl = result; console.log('that.imgiDPassportUrl', that.imgiDPassportUrl) that.canvasDataURL(result, q, fn, file); // } } catch (error) { console.error('图片压缩异常:', error); that.alert.methods.showModuleAuto("图片处理失败,请重新选择"); that.$refs.filePassport.value = null; } } // ready.readAsDataURL(file) }, dataURLtoFile (dataurl, filename) { //将base64转换为文件 let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } } } </script>查看代码,并讲解
最新发布
09-11
<template> <view class="contentAll" v-if="pageStatue==1"> <phoneHead></phoneHead> <view class="header" style="margin-top: -10rpx;"> <Headesnav :title='titleText' backText=""></Headesnav> </view> <view class="cardBox"> <view class="productInput" @click="showWarehouse=true"> <view class="productText"> <view class="left">入库仓库</view> </view> <view v-if="detailsStatus!=2" class="picker" style="margin-top: 6rpx;"> <view class="noData" v-if="warehouseIndex=='-1'"> 请选择仓库 </view> <view class="" v-else> {{warehouseList[warehouseIndex]}} </view> <uni-icons type="forward" size="16" color="#d8d8dc" style="padding-top: 6rpx;"></uni-icons> </view> <view v-else class="picker" style="margin-top: 6rpx;"> {{warehouseList[warehouseIndex]}} </view> </view> <view class="productInput" @click="showProductrRelevancy=true"> <view class="productText"> <view v-if="detailsStatus!=2" class="left productrRelevancy">经手人</view> <view v-else class="left">经手人</view> </view> <view v-if="detailsStatus!=2||shenheStatus==1" class="picker" style="margin-top: 6rpx;"> <view class="noData" v-if="productrRelevancyIndex=='-1'"> 请选择经手人 </view> <view class="" v-else> {{productrRelevancyList[productrRelevancyIndex]}} </view> <uni-icons type="forward" size="16" color="#d8d8dc" style="padding-top: 6rpx;"></uni-icons> </view> <view v-else class="picker" style="margin-top: 6rpx;"> {{productrRelevancyList[productrRelevancyIndex]}} </view> </view> <view class="productInput" @click="showTime=true"> <view class="productText"> <view class="left">业务日期</view> </view> <view v-if="detailsStatus!=2||shenheStatus==1" class="picker" style="margin-top: 6rpx;"> <view> {{defaultTime}} </view> <uni-icons type="forward" size="16" color="#d8d8dc" style="padding-top: 6rpx;"></uni-icons> </view> <view v-else class="picker" style="margin-top: 6rpx;"> {{defaultTime}} </view> </view> <view class="productInput" @click="showActionType=true"> <view class="productText"> <view class="left">操作类型</view> </view> <view v-if="detailsStatus!=2||shenheStatus==1" class="picker" style="margin-top: 6rpx;"> <view class="noData" v-if="actionTypeIndex=='-1'"> 请选择操作类型 </view> <view class="" v-else> {{actionTypeList[actionTypeIndex]}} </view> <uni-icons type="forward" size="16" color="#d8d8dc" style="padding-top: 6rpx;"></uni-icons> </view> <view v-else class="picker" style="margin-top: 6rpx;"> {{actionTypeList[actionTypeIndex]}} </view> </view> <view class="productInput"> <view class="productText"> <view class="left">备注</view> </view> <view v-if="detailsStatus!=2||shenheStatus==1" class="productImfor" style="margin-top: 6rpx;"> <input placeholder="请输入备注" v-model="query.memo" /> </view> <view v-else class="productImfor" style="margin-top: 6rpx;"> {{query.memo}} </view> </view> </view> <scroll-view :class="detailsStatus!=2||shenheStatus==1 ? 'scroll-Y' : 'scroll-Ys'" scroll-y="true"> <view class=""> <view class="" v-if="productList1.length>0"> <view class="product-card" v-for="(item,index) in productList1" :key="index"> <view class="cardTitle"> <view class="titleBoxs"> <view class="name" style="font-size: 36rpx;color: black;">{{item.Name}}</view> <view class="right" v-if="detailsStatus!=2||shenheStatus==1"> <button size="mini" type="warn" plain="true" @click="deleteList(item)">删除</button> </view> </view> </view> <view class="cardContent"> <view class="oneBox"> <view class="title">分类:</view> <view class="right"> {{item.ProductTypeName}} </view> </view> <view class="oneBox"> <view class="title">品牌:</view> <view class="right"> {{item.BrandName}} </view> </view> <view class="oneBox"> <view class="title">单位:</view> <view class="right"> {{item.StandardUnitName}} </view> </view> <view class="oneBox"> <view class="title">零售价:</view> <view class="right"> {{item.RetailPrice}} </view> </view> <view class="oneBox" style="margin-top: 10rpx;"> <view class="title">产品数量:</view> <view v-if="detailsStatus!=2||shenheStatus==1" class="priceInput"> <input placeholder="" v-model="item.productSum" type="number" @input="shuruSum($event,item)" /> </view> <view v-else class="right"> {{item.productSum}} </view> </view> <view class="oneBox" style="margin-top: 10rpx;" v-if="$store.getters.isPermission('40f127d9-5ffc-4e4f-8449-aacb182ddae4')"> <view class="title">成本价格:</view> <view v-if="detailsStatus!=2||shenheStatus==1" class="priceInput"> <input placeholder="" v-model="item.CostPrice" type="number" @input="shuruChengBenJia($event,item)" /> </view> <view v-else class="right"> {{item.CostPrice}} </view> </view> <view class="oneBox" style="margin-top: 10rpx;" v-if="$store.getters.isPermission('40f127d9-5ffc-4e4f-8449-aacb182ddae4')"> <view class="title">成本总额:</view> <view v-if="detailsStatus!=2||shenheStatus==1" class="priceInput"> <input placeholder="" v-model="item.chnegbenSumPrice" type="number" :disabled="true" /> </view> <view v-else class="right"> {{item.chnegbenSumPrice}} </view> </view> <view class="oneBox" style="margin-top: 10rpx;"> <view class="title">合计金额:</view> <view v-if="detailsStatus!=2||shenheStatus==1" class="priceInput"> <input placeholder="" v-model="item.hejiSumPrice" type="number" :disabled="true" /> </view> <view v-else class="right"> {{item.hejiSumPrice}} </view> </view> </view> </view> <view class="AllSum"> <view class="twoBox" style="color: #07c160;"> 合计数量:{{productList1.allQuatity}} </view> <view class="twoBox" style="margin-top: 8rpx; color: #2979ff;"> 合计金额:{{productList1.allPrice}} </view> <view class="twoBox" style=" color: red;" v-if="$store.getters.isPermission('40f127d9-5ffc-4e4f-8449-aacb182ddae4')"> 合计成本:{{productList1.allCostPrice}} </view> </view> </view> <view class="empty" v-else> <u-empty text="暂无产品" mode="list"></u-empty> </view> </view> </scroll-view> <!-- 删除提示 --> <view> <u-popup v-model="show1" mode="center" border-radius="14"> <view class="popupMax"> <view class="title" style="color: red;"> 请确认是否删除? </view> <view class="submit"> <view @click="show1=false" style="opacity: 0.8;">取消</view> <view style="color: #2979ff;" @click="confirmRemove">确定</view> </view> </view> </u-popup> </view> <!-- 审核提示 --> <view> <u-popup v-model="show2" mode="center" border-radius="14"> <view class="popupMax"> <view class="title" style="color: red;"> 是否入库? </view> <view class="submit"> <view @click="show2=false" style="opacity: 0.8;">取消</view> <view style="color: #2979ff;" @click="shenHeSubmit">确定</view> </view> </view> </u-popup> </view> <view v-for="(item,index) in scanList2" :key="index">{{item}}</view> <view class="scan" @click.passive="scanProduct" v-if="detailsStatus!=2||shenheStatus==1"> <view class="addText"> 扫码入库 </view> </view> <view class="zidingyixuanfu" @click.passive="showProduct" v-if="detailsStatus!=2||shenheStatus==1"> <view class="addText"> 浏览产品 </view> </view> <view class="submitAdd" v-if="shenheStatus==1"> <view class="cancel_button" @click="quxiao">返回</view> <view class="add_button" @click="show2=true">审核 </view> <view class="quxiao_button" @click="show3=true">撤销 </view> <view class="save_button" @click="baoCun">保存</view> </view> <view class="submitAdd2" v-if="shenheStatus!=5&&shenheStatus!=2&&shenheStatus!=1"> <view class="cancel_button" @click="quxiao">返回</view> <view class="save_button" @click="baoCun">保存</view> </view> <view class="submitAdd3" v-if="detailsStatus==2&&shenheStatus==2&&IsQuxiao==true"> <view class="cancel_button" @click="quxiao">返回</view> <view class="quxiao_button" @click="show4=true">撤销 </view> </view> <view class="submitAdd4" v-if="detailsStatus==2&&shenheStatus==2&&IsQuxiao==false"> <view class="cancel_button" @click="quxiao">返回</view> </view> <view class="submitAdd5" v-if="detailsStatus==2&&shenheStatus==5&&IsQuxiao==true"> <view class="cancel_button" @click="quxiao">返回</view> </view> <view> <u-popup v-model="show3" mode="center" border-radius="14"> <view class="popupMax"> <view class="title" style="color: red;"> 确认是否撤销单据? </view> <view class="submit"> <view @click="show3=false" style="opacity: 0.8;">取消</view> <view style="color: #2979ff;" @click="cheXiaoSubmit">确定</view> </view> </view> </u-popup> </view> <view> <u-popup v-model="show4" mode="center" border-radius="14"> <view class="popupMax"> <view class="title" style="color: red;"> 确认是否取消入库单据? </view> <view class="submit"> <view @click="show4=false" style="opacity: 0.8;">取消</view> <view style="color: #2979ff;" @click="quXiaoSubmit">确定</view> </view> </view> </u-popup> </view> </view> <view class="contentAll" v-if="pageStatue==2"> <phoneHead></phoneHead> <view class="customTab" style="margin-top: -10rpx;"> <view class="getBack" @click="conceal"> <image src="/static/image/zdyfh.png" mode=""></image> </view> <view class="title"> 选择产品 </view> <view class="right_submit" @click="rightClk"> {{submit_queDing}} </view> </view> <view class="productMax"> <view class="productMax-header"> <view class="brand-box"> <view class="picker"> <picker @change="brandChange" :value="brandNum" :range="brandListData"> <view class="noData" v-if="brandNum==-1" style="width: 81vw;"> 请选择品牌 </view> <view v-else style="width: 81vw;"> {{brandListData[brandNum]}} </view> </picker> </view> </view> <view class="brand-box"> <view class="picker"> <picker @change="suppliersChange" :value="suppliersNum" :range="suppliersListData"> <view class="noData" v-if="suppliersNum==-1" style="width: 81vw;"> 请选择供应商 </view> <view v-else style="width: 81vw;"> {{suppliersListData[suppliersNum]}} </view> </picker> </view> </view> <uni-search-bar bgColor="#fff" placeholder="请输入产品名称" v-model="rukuqueryKeywords"></uni-search-bar> </view> <scroll-view scroll-y="true" class="scroll-Y1 oneBox" @scrolltolower="upper"> <view class="uni-list" v-if="chukuproductList.length>0"> <checkbox-group class="gouxuan" v-for="(item1,index) in chukuproductList" :key="index" :title="item1.prductname" @click="selectProduct(item1)"> <view class="left"> <view class="dagou"> <checkbox :value="item1.item1" @click="selectProduct(item1)" :checked="item1.checked" /> </view> <view class="name"> <view class="title"> <view class="productName">{{item1.Name}}</view> </view> <view class="name-body"> <view class="block">品牌:{{item1.BrandName}}</view> <view class="L1">库存:{{item1.Quatitys}}</view> <view class="L1">单位:{{item1.StandardUnitName}}</view> </view> <view class="product-x"> <view class="block2">类别:{{item1.ProductTypeName}}</view> <view class="L2" v-if="$store.getters.isPermission('40f127d9-5ffc-4e4f-8449-aacb182ddae4')"> 成本:{{item1.CostPrice}}</view> <view class="L2">零售价:{{item1.RetailPrice}}</view> </view> </view> </view> </checkbox-group> <uni-load-more color="#3179F4" :status="status" /> </view> <view class="" v-else> <u-empty text="暂无数据" mode="list"></u-empty> </view> </scroll-view> </view> </view> <u-picker mode="selector" v-model="showWarehouse" :default-selector="[warehouseIndex]" :range="warehouseList" @confirm="warehouse"></u-picker> <u-picker mode="selector" v-model="showProductrRelevancy" :default-selector="[productrRelevancyIndex2]" :range="productrRelevancyList" @confirm="choiceProductrRelevancy"></u-picker> <u-picker mode="time" v-model="showTime" :defaultTime="defaultTime" :default-selector="[0]" :params="params" @confirm="businessTime"></u-picker> <u-picker mode="selector" v-model="showActionType" :default-selector="[actionTypeIndex]" :range="actionTypeList" @confirm="choiceActionType"></u-picker> </template> <script> import Headesnav from "@/components/headernav.vue" import phoneHead from "@/components/phoneHead/phoneHead.vue" import { EmployeeGetList, Brand_GetList, CrossWarehouses, HospitalId_Warehouse_WarehouseIn, HospitalId_Warehouse_Ruku_Save, HospitalId_Warehouse_Ruku_GetProduct, Hospital_Product_GognYingShang_List, HospitalId_Warehouse_Details, Hospital_Warehouse_Ruku_Update, HosptialId_Warehouse_Ruku_Audit, HosptialId_Warehouse_Order_CheXiao, Hospital_Warehouse_Order_QuXiao, GetProduct_GetList } from "@/api/api.js" import { ScanQRcode } from "@/api/home.js" import { WxJsSdk } from '@/api/wxapi.js' import { mapState } from 'vuex' export default { components: { Headesnav, phoneHead }, computed: { ...mapState(['currentSearchHospitalName', 'currentSearchHospitalId', 'loginUserInfo', 'companyId']) }, watch: { rukuqueryKeywords(newVal, oldVal) { this.rukuquery.keywords = newVal this.chukuproductList = [] this.rukuquery.pageIndex = 1 this.HospitalId_Warehouse_Ruku_GetProduct() } }, onLoad(e) { this.$nextTick(() => { this.$store.dispatch('loadPermissions'); }); let that = this const date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDate(); month = month > 9 ? month : '0' + month; day = day > 9 ? day : '0' + day; this.defaultTime = `${year}-${month}-${day}` this.hospitalId = this.currentSearchHospitalId this.CrossWarehouses() this.EmployeeGetList() this.HospitalId_Warehouse_WarehouseIn() this.Hospital_Product_GognYingShang_List() this.Brand_GetList() this.HospitalId_Warehouse_Ruku_GetProduct() if (e.DetailsID != undefined) { // 详情 this.titleText = '入库详情' this.detailsStatus = 2 this.shenheStatus = e.shenheStatus this.DetailsID = e.DetailsID setTimeout(function() { // 详情接口 that.HospitalId_Warehouse_Details() }, 200) } else { // 添加 } }, data() { return { showTime: false, showProductrRelevancy: false, showActionType: false, showWarehouse: false, IsQuxiao: '', DetailsID: '', titleText: '添加入库', detailsStatus: 1, shenheStatus: '', queryXiugai: "", params: { year: true, month: true, day: true, hour: false, minute: false, second: false }, query: { "houseId": '', //仓库Id "userId": '', //经手人Id "businessDate": "", //业务日期 "baseId": '', //操作原因Id "allCostPrice": '', //总成本 "allPrice": '', //总金额 "allQuatity": '', //总数量 "memo": "", "products": [] }, rukuqueryKeywords: '', status: "more", rukuquery: { "houseId": '', //仓库Id "brandId": '', //品牌Id "supplierId": '', //供应商Id "keywords": "", //关键字 "pageSize": 15, "pageIndex": 1 }, hospitalId: '', warehouseIndex: '-1', warehouseList: [], warehouseList1: [], productrRelevancyList: [], productrRelevancyListData: [], productrRelevancyIndex: '-1', productrRelevancyIndex2: 0, defaultTime: '', actionTypeList: [], actionTypeList1: [], actionTypeIndex: 0, submit_queDing: '确定', pageStatue: 1, brandNum: '-1', brandListData: [], brandListData1: [], suppliersNum: '-1', suppliersListData: [], suppliersListData1: [], chukuproductList: [], scanList: [], scanList2: [], lastGouxuan: [], yijiGouxuan: [], productList1: [], productList2: [], show1: false, show2: false, show3: false, show4: false, deleteItem: '', submitSwitch: false, detailsData: '', detailsproductList1: '', ceshiArr: '', saomaArrList: [], } }, methods: { // 详情 HospitalId_Warehouse_Details() { let that = this uni.showLoading({ title: "加载..." }) HospitalId_Warehouse_Details({ "id": that.DetailsID //列表返回Id }).then((res) => { that.detailsData = res.data for (var i = 0; i < that.detailsData.length; i++) { that.detailsData[i].ID = that.detailsData[i].KucunID } that.IsQuxiao = that.detailsData.IsQuxiao that.query.houseId = that.detailsData.HouseId for (var i = 0; i < that.warehouseList1.length; i++) { if (that.warehouseList1[i].Id == that.detailsData.HouseId) { that.warehouseIndex = i } } that.query.userId = that.detailsData.UserId for (var i = 0; i < that.productrRelevancyListData.length; i++) { if (that.productrRelevancyListData[i].EmployeeId == that.detailsData.UserId) { that.productrRelevancyIndex = i that.productrRelevancyIndex2 = i } } that.query.businessDate = that.detailsData.BusinessDate that.defaultTime = that.detailsData.BusinessDate that.query.baseId = that.detailsData.BaseId for (var i = 0; i < that.actionTypeList1.length; i++) { if (that.actionTypeList1[i].ID == that.detailsData.BaseId) { that.actionTypeIndex = i } } that.query.memo = that.detailsData.Memo for (var j = 0; j < that.detailsData.Products.length; j++) { that.detailsData.Products[j].Name = that.detailsData.Products[j].ProductName that.detailsData.Products[j].ProductTypeName = that.detailsData.Products[j].ProductType that.detailsData.Products[j].productSum = that.detailsData.Products[j].Quatity that.detailsData.Products[j].chnegbenSumPrice = that.detailsData.Products[j].AllCostPrice that.detailsData.Products[j].hejiSumPrice = that.detailsData.Products[j].AllPrice that.detailsData.Products[j].ID = that.detailsData.Products[j].ProductId } this.productList1 = that.detailsData.Products this.detailsproductList1 = that.detailsData.Products // 三个总数 let allSum = 0 for (var i = 0; i < that.detailsData.Products.length; i++) { allSum = Number(allSum) + Number(that.detailsData.Products[i].Quatity) allSum = Number(allSum).toFixed(2) } this.productList1.allQuatity = allSum this.productList1.allPrice = Number(that.detailsData.AllPrice).toFixed(2) this.productList1.allCostPrice = Number(that.detailsData.AllChengBen).toFixed(2) }).catch((err) => { }).finally(() => { uni.hideLoading() }) }, //保存 添加 baoCun() { let that = this this.query.businessDate = this.defaultTime this.query.allCostPrice = this.productList1.allCostPrice this.query.allPrice = this.productList1.allPrice this.query.allQuatity = this.productList1.allQuatity this.query.allQuatity = Number(this.query.allQuatity) this.query.products = [] for (var j = 0; j < this.productList1.length; j++) { let obj = {} obj.productId = that.productList1[j].ID obj.quantity = that.productList1[j].productSum obj.costPrice = that.productList1[j].CostPrice obj.allCostPrice = that.productList1[j].chnegbenSumPrice that.query.products.push(obj) } if (that.detailsStatus == 1) { // 添加 if (that.query.userId == '') { uni.showToast({ title: '请选择经手人', icon: 'none', duration: 1600 }) return } else if (that.query.baseId == '') { uni.showToast({ title: '请选择操作类型', icon: 'none', duration: 1600 }) return } else if (that.query.products == '') { uni.showToast({ title: '请选择入库的产品', icon: 'none', duration: 1600 }) return } for (var i = 0; i < that.productList1.length; i++) { if (that.productList1[i].productSum == 0 || that.productList1[i].productSum == '' || that .productList1[i] .productSum == undefined) { uni.showToast({ title: '产品数量不能为0', icon: 'none', duration: 2000 }) return } } if (that.submitSwitch) { return } uni.showLoading({ title: "加载..." }) that.submitSwitch = true HospitalId_Warehouse_Ruku_Save(that.query).then((res) => { if (res.code == 200) { uni.showToast({ title: res.msg, duration: 2000 }); setTimeout(function() { uni.navigateBack({ delta: 1, //返回层数,2则上上页 }) }, 2000) } else { uni.showToast({ title: res.msg, duration: 2000 }); } }).catch((err) => { }).finally(() => { uni.hideLoading() setTimeout(function() { that.submitSwitch = false }, 2000) }) } else if (that.detailsStatus == 2) { // 修改 that.queryXiugai = that.query that.queryXiugai.orderNo = that.detailsData.OrderNo uni.showLoading({ title: "加载..." }) if (that.queryXiugai.products == '') { uni.showToast({ title: '请选择入库的产品', icon: 'none', duration: 1600 }) return } for (var i = 0; i < that.productList1.length; i++) { if (that.productList1[i].productSum == 0 || that.productList1[i].productSum == '' || that .productList1[i] .productSum == undefined) { uni.showToast({ title: '产品数量不能为0', icon: 'none', duration: 2000 }) return } } Hospital_Warehouse_Ruku_Update(that.queryXiugai).then((res) => { if (res.code == 200) { uni.showToast({ title: res.msg, duration: 2000 }); setTimeout(function() { uni.navigateBack({ delta: 1, //返回层数,2则上上页 }) }, 2000) } else { uni.showToast({ title: res.msg, duration: 2000 }); } }).catch((err) => { }).finally(() => { uni.hideLoading() }) } }, // 审核 shenHeSubmit() { let that = this uni.showLoading({ title: "加载..." }) HosptialId_Warehouse_Ruku_Audit({ "orderNo": that.detailsData.OrderNo //订单号 }).then((res) => { if (res.code == 200) { uni.showToast({ title: res.msg, duration: 2000 }); that.show2 = false setTimeout(function() { uni.navigateBack({ delta: 1, //返回层数,2则上上页 }) }, 2000) } else { uni.showToast({ title: res.msg, duration: 2000 }); } }).catch((err) => { }).finally(() => { uni.hideLoading() }) }, // 撤销 cheXiaoSubmit() { let that = this uni.showLoading({ title: "加载..." }) HosptialId_Warehouse_Order_CheXiao({ "id": that.DetailsID //列表返回Id }).then((res) => { if (res.code == 200) { uni.showToast({ title: res.msg, duration: 2000 }); that.show3 = false setTimeout(function() { uni.navigateBack({ delta: 1, //返回层数,2则上上页 }) }, 2000) } else { uni.showToast({ title: res.msg, duration: 2000 }); } }).catch((err) => { }).finally(() => { uni.hideLoading() }) }, // 取消已审核的数据 quXiaoSubmit() { let that = this uni.showLoading({ title: "加载..." }) Hospital_Warehouse_Order_QuXiao({ "id": that.DetailsID, //列表返回Id "type": 2 //单据类型 1出库 2入库 }).then((res) => { if (res.code == 200) { uni.showToast({ title: res.msg, duration: 2000 }); that.show4 = false setTimeout(function() { uni.navigateBack({ delta: 1, //返回层数,2则上上页 }) }, 2000) } else { uni.showToast({ title: res.msg, duration: 2000 }); } }).catch((err) => { }).finally(() => { uni.hideLoading() }) }, // 返回上一页 quxiao() { setTimeout(function() { uni.navigateBack({ delta: 1, //返回层数,2则上上页 }) }, 20) }, // 获取入库产品列表数据 HospitalId_Warehouse_Ruku_GetProduct() { let that = this that.rukuquery.houseId = that.query.houseId HospitalId_Warehouse_Ruku_GetProduct(that.rukuquery).then((res) => { this.chukuproductList = res.data for (var i = 0; i < this.chukuproductList.length; i++) { this.chukuproductList[i].checked = false } for (var j = 0; j < that.chukuproductList.length; j++) { for (var k = 0; k < that.lastGouxuan.length; k++) { if (that.chukuproductList[j].ID == that.lastGouxuan[k].ID) { that.chukuproductList[j].checked = true } } } if (res.data.length >= that.rukuquery.pageSize) { that.status = "more" } else { that.status = "no-more" } }).catch((err) => { }) }, upper() { let that = this; if (that.status == "no-more") { return } that.status = "loading"; that.rukuquery.pageIndex++; HospitalId_Warehouse_Ruku_GetProduct(that.rukuquery).then(res => { let addArr = res.data for (var i = 0; i < addArr.length; i++) { addArr[i].checked = false; } that.chukuproductList = that.chukuproductList.concat(addArr) if (res.data.length >= that.rukuquery.pageSize) { that.status = "more" } else { that.status = "no-more" } }).catch(err => { }) }, // 门店仓库列表 CrossWarehouses() { let that = this CrossWarehouses({ // "hospitalId": this.hospitalId, "hospitalId": that.loginUserInfo.WarehouseId, 'keywords': '', }).then((res) => { this.warehouseList1 = res.data res.data.forEach(item => { this.warehouseList.push(item.Name) }) for (var i = 0; i < this.warehouseList1.length; i++) { if (that.warehouseList1[i].Id == that.loginUserInfo.WarehouseId) { that.warehouseIndex = i this.query.houseId = this.warehouseList1[i].Id } } }).catch((err) => { }) }, //入库仓库选择 warehouse(e) { this.warehouseIndex = e[0] this.query.houseId = this.warehouseList1[this.warehouseIndex].Id this.hospitalId = this.warehouseList1[this.warehouseIndex].Id }, //员工列表数据 EmployeeGetList() { let that = this EmployeeGetList({ "hospitalId": this.hospitalId, //门店id "keywords": '' //关键字查询 }).then((res) => { this.productrRelevancyListData = res.data res.data.forEach(item => { this.productrRelevancyList.push(item.EmployeeName) }) }).catch(err => {}) }, //经手人 choiceProductrRelevancy(e) { this.productrRelevancyIndex = e[0] this.productrRelevancyIndex2 = Number(this.productrRelevancyIndex) this.query.userId = this.productrRelevancyListData[this.productrRelevancyIndex].EmployeeId }, //业务日期 businessTime(e) { this.defaultTime = `${e.year}-${e.month}-${e.day}` }, // 操作类型列表 HospitalId_Warehouse_WarehouseIn() { HospitalId_Warehouse_WarehouseIn({ "type": 1 //操作类型 1入库 2院用出库 3非院用出库 }).then((res) => { this.actionTypeList1 = res.data res.data.forEach(item => { this.actionTypeList.push(item.Name) }) this.query.baseId = this.actionTypeList1[0].ID }).catch((err) => { }) }, // 操作类型选择 choiceActionType(e) { this.actionTypeIndex = e[0] this.query.baseId = this.actionTypeList1[this.actionTypeIndex].ID }, scanProduct() { let that = this WxJsSdk(that.companyId, 'scanQRCode').then(wx => { wx.scanQRCode({ needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果, scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有 success: function(res) { var result = res.resultStr.slice(7); // 当needResult 为 1 时,扫码返回的结果 uni.showLoading({ title: "加载..." }) HospitalId_Warehouse_Ruku_GetProduct({ "houseId": that.hospitalId, //仓库Id "brandId": '', //品牌Id "supplierId": '', //供应商Id "keywords": result, //关键字 "pageSize": 10, "pageIndex": 1 }).then((res) => { if (res.data.length > 0) { that.ceshiArr = res.data[0] // 合并详情已有的产品和选择的产品 // 排除已经有的产品数据 不必要再次加入 for (var m = 0; m < that.detailsproductList1.length; m++) { if (that.detailsproductList1[m].ID == that.ceshiArr .ID || that.detailsproductList1[m].KucunID == that .ceshiArr.ID) { return } } for (var i = 0; i < that.saomaArrList.length; i++) { if (that.saomaArrList[i].ID == that.ceshiArr.ID) { return } } that.saomaArrList.push(that.ceshiArr) that.productList1.push(res.data[0]) that.productList1.allQuatity = 0 that.productList1.allCostPrice = 0 that.productList1.allPrice = 0 for (var i = 0; i < that.productList1.length; i++) { // 添加一个产品数量 成本总金额 合计金额 if ('productSum' in that.productList1[i]) { // 原来就勾选了的数据不用添加字段 } else { //新勾选的数据添加一些需要的字段 that.productList1[i].productSum = 0 that.productList1[i].chnegbenSumPrice = 0 that.productList1[i].hejiSumPrice = 0 } } for (var j = 0; j < that.productList1.length; j++) { that.productList1.allQuatity = Number(that.productList1 .allQuatity) + Number(that.productList1[j] .productSum) that.productList1.allQuatity = Number(that.productList1 .allQuatity).toFixed(2) that.productList1.allCostPrice = Number(that .productList1.allCostPrice) + Number(that .productList1[j] .CostPrice) * Number(that.productList1[j] .productSum) that.productList1.allCostPrice = Number(that .productList1.allCostPrice).toFixed(2) that.productList1.allPrice = Number(that.productList1 .allPrice) + Number(that.productList1[j] .RetailPrice) * Number(that.productList1[j].productSum) that.productList1.allPrice = Number(that.productList1 .allPrice).toFixed(2) } this.productList1 = this.deduplicateById(this.productList1) } else { uni.showToast({ title: '未查询到产品', icon: 'none', duration: 2000 }); return } }).catch((err) => { }).finally(() => { uni.hideLoading() }) } }); }); }, deduplicateById(arr) { const map = new Map(); arr.forEach(item => { map.set(item.ID, item); }); return Array.from(map.values()); }, //app扫码 // #ifndef H5 scanProduct() { let that = this uni.scanCode({ success: function(res) { var result = res.result; // 当needResult 为 1 时,扫码返回的结果 uni.showLoading({ title: "加载..." }) HospitalId_Warehouse_Ruku_GetProduct({ "houseId": that.hospitalId, //仓库Id "brandId": '', //品牌Id "supplierId": '', //供应商Id "keywords": result, //关键字 "pageSize": 10, "pageIndex": 1 }).then((res) => { if (res.data.length > 0) { that.ceshiArr = res.data[0] // 合并详情已有的产品和选择的产品 // 排除已经有的产品数据 不必要再次加入 for (var m = 0; m < that.detailsproductList1.length; m++) { if (that.detailsproductList1[m].ID == that.ceshiArr.ID || that .detailsproductList1[m].KucunID == that.ceshiArr.ID) { return } } for (var i = 0; i < that.saomaArrList.length; i++) { if (that.saomaArrList[i].ID == that.ceshiArr.ID) { return } } that.saomaArrList.push(that.ceshiArr) that.productList1.push(res.data[0]) that.productList1.allQuatity = 0 that.productList1.allCostPrice = 0 that.productList1.allPrice = 0 for (var i = 0; i < that.productList1.length; i++) { // 添加一个产品数量 成本总金额 合计金额 if ('productSum' in that.productList1[i]) { // 原来就勾选了的数据不用添加字段 } else { //新勾选的数据添加一些需要的字段 that.productList1[i].productSum = 0 that.productList1[i].chnegbenSumPrice = 0 that.productList1[i].hejiSumPrice = 0 } } for (var j = 0; j < that.productList1.length; j++) { that.productList1.allQuatity = Number(that.productList1 .allQuatity) + Number(that.productList1[j] .productSum) that.productList1.allQuatity = Number(that.productList1 .allQuatity).toFixed(2) that.productList1.allCostPrice = Number(that .productList1.allCostPrice) + Number(that .productList1[j] .CostPrice) * Number(that.productList1[j] .productSum) that.productList1.allCostPrice = Number(that .productList1.allCostPrice).toFixed(2) that.productList1.allPrice = Number(that.productList1 .allPrice) + Number(that.productList1[j] .RetailPrice) * Number(that.productList1[j].productSum) that.productList1.allPrice = Number(that.productList1 .allPrice).toFixed(2) } } else { uni.showToast({ title: '未查询到产品', icon: 'none', duration: 2000 }); return } }).catch((err) => { }).finally(() => { uni.hideLoading() }) } }); }, // #endif //去选择产品 showProduct() { this.pageStatue = 2 this.chukuproductList = [] this.rukuquery.pageIndex = 1 this.HospitalId_Warehouse_Ruku_GetProduct() }, //品牌 Brand_GetList() { let that = this Brand_GetList().then(res => { this.brandListData1 = res.data res.data.forEach(item => { this.brandListData.push(item.Name) }) this.brandListData1.unshift('全部') this.brandListData.unshift('全部') }).catch(err => {}) }, //品牌选择 brandChange(e) { this.brandNum = e.detail.value if (this.brandNum == 0) { this.rukuquery.brandId = '' } else { this.rukuquery.brandId = this.brandListData1[this.brandNum].ID } this.chukuproductList = [] this.rukuquery.pageIndex = 1 this.HospitalId_Warehouse_Ruku_GetProduct() }, //供应商列表 Hospital_Product_GognYingShang_List() { Hospital_Product_GognYingShang_List({ "hospitalId": this.hospitalId, "keywords": " ", }).then((res) => { this.suppliersListData1 = res.data res.data.forEach(item => { this.suppliersListData.push(item.Name) }) this.suppliersListData.unshift('全部') this.suppliersListData1.unshift('全部') }).catch((err) => { }) }, //供应商 suppliersChange(e) { this.suppliersNum = e.detail.value if (this.suppliersNum == 0) { this.rukuquery.supplierId = '' } else { this.rukuquery.supplierId = this.suppliersListData1[this.suppliersNum].ID } this.chukuproductList = [] this.rukuquery.pageIndex = 1 this.HospitalId_Warehouse_Ruku_GetProduct() }, //自定义返回 conceal() { this.pageStatue = 1 }, //选择产品 selectProduct(e) { if (this.lastGouxuan.length > 0) { for (var m = 0; m < this.lastGouxuan.length; m++) { if (this.lastGouxuan[m].ID == e.ID) { e.checked = false this.lastGouxuan[m].checked = false this.lastGouxuan.splice(m, 1) break } else { e.checked = true } } } else { e.checked = (!e.checked) } this.lastGouxuan = [] let xuanzhongNum = 0 for (var i = 0; i < this.chukuproductList.length; i++) { if (this.chukuproductList[i].checked == true) { xuanzhongNum += 1 } } for (var i = 0; i < this.chukuproductList.length; i++) { if (this.chukuproductList[i].checked == true) { this.yijiGouxuan.push(this.chukuproductList[i]) } for (var p = 0; p < this.yijiGouxuan.length; p++) { if (this.yijiGouxuan[p].checked == false) { this.yijiGouxuan.splice(p, 1) } } } const map = new Map(); const newArr = this.yijiGouxuan.filter(v => !map.has(v.ID) && map.set(v.ID, v)); this.yijiGouxuan = newArr for (var i = 0; i < this.yijiGouxuan.length; i++) { if (this.yijiGouxuan[i].checked == true) { this.lastGouxuan.push(this.yijiGouxuan[i]) } } this.lastGouxuan = [...new Set(this.lastGouxuan)] if (this.lastGouxuan.length > 0) { this.submit_queDing = '确定' + '(' + this.lastGouxuan.length + ')' } else { this.submit_queDing = '确定' } }, //确定产品 rightClk(e) { let that = this // 合并详情已有的产品和选择的产品 // 排除已经有的产品数据 不必要再次加入 for (var m = 0; m < that.detailsproductList1.length; m++) { for (var n = 0; n < that.lastGouxuan.length; n++) { if (that.detailsproductList1[m].ID == that.lastGouxuan[n].ID) { that.lastGouxuan.splice(n, 1) } } } if (that.detailsStatus == 2) { this.productList1 = this.lastGouxuan.concat(this.detailsproductList1) } else { if (that.saomaArrList.length == 0) { this.productList1 = this.lastGouxuan } else { this.productList1 = this.lastGouxuan.concat(this.saomaArrList) } } this.productList1.allQuatity = 0 this.productList1.allCostPrice = 0 this.productList1.allPrice = 0 for (var i = 0; i < this.productList1.length; i++) { // 添加一个产品数量 成本总金额 合计金额 if ('productSum' in this.productList1[i]) { // 原来就勾选了的数据不用添加字段 } else { //新勾选的数据添加一些需要的字段 this.productList1[i].productSum = 0 this.productList1[i].chnegbenSumPrice = 0 this.productList1[i].hejiSumPrice = 0 } } for (var j = 0; j < this.productList1.length; j++) { this.productList1.allQuatity = Number(this.productList1.allQuatity) + Number(this.productList1[j] .productSum) this.productList1.allQuatity = Number(this.productList1.allQuatity).toFixed(2) this.productList1.allCostPrice = Number(this.productList1.allCostPrice) + Number(this.productList1[j] .CostPrice) * Number(this.productList1[j].productSum) this.productList1.allCostPrice = Number(this.productList1.allCostPrice).toFixed(2) this.productList1.allPrice = Number(this.productList1.allPrice) + Number(this.productList1[j] .RetailPrice) * Number(this.productList1[j].productSum) this.productList1.allPrice = Number(this.productList1.allPrice).toFixed(2) } this.pageStatue = 1 if (this.lastGouxuan.length > 0) { this.submit_queDing = '确定' + '(' + this.lastGouxuan.length + ')' } else { this.submit_queDing = '确定' } }, // 输入数量时金额全部重新计算 shuruSum(event, item) { let that = this let value = event.detail.value; if (value < 1) { value = 0; } else { const numValue = parseInt(value, 10); if (!Number.isNaN(numValue)) { value = numValue; } else { value = 1; } } event.detail.value = value this.$nextTick(() => { item.productSum = value }) // 计算之前全部赋值为0 在重新做计算 this.productList1.allQuatity = 0 this.productList1.allCostPrice = 0 this.productList1.allPrice = 0 setTimeout(function() { // 计算每个产品 单个总价 for (var j = 0; j < that.productList1.length; j++) { that.productList1[j].chnegbenSumPrice = Number(that.productList1[j].productSum) * Number( that .productList1[j].CostPrice) that.productList1[j].chnegbenSumPrice = that.productList1[j].chnegbenSumPrice.toFixed(2) that.productList1[j].hejiSumPrice = Number(that.productList1[j].productSum) * Number(that .productList1[ j].RetailPrice) that.productList1[j].hejiSumPrice = that.productList1[j].hejiSumPrice.toFixed(2) } // 计算全部总价格 for (var m = 0; m < that.productList1.length; m++) { that.productList1.allQuatity = Number(that.productList1.allQuatity) + Number(that .productList1[m] .productSum) that.productList1.allQuatity = Number(that.productList1.allQuatity).toFixed(2) that.productList1.allCostPrice = Number(that.productList1.allCostPrice) + Number(that .productList1[m] .CostPrice) * Number(that.productList1[m].productSum) that.productList1.allCostPrice = Number(that.productList1.allCostPrice).toFixed(2) that.productList1.allPrice = Number(that.productList1.allPrice) + Number(that.productList1[ m] .RetailPrice) * Number(that.productList1[m].productSum) that.productList1.allPrice = Number(that.productList1.allPrice).toFixed(2) } }, 20) }, // 输入成本价格时 重新计算金额 shuruChengBenJia(event, item) { let that = this let value = Number(event.detail.value) if (value < 0) { this.$nextTick(() => { item.CostPrice = 0 event.detail.value = 0 }) return } let decimalPart = Math.floor(value * 100) if (decimalPart != value * 100) { // 不相等就是不止二位小数 value = Number(value).toFixed(2) } // 更新数据绑定的值 event.detail.value = value this.$nextTick(() => { item.CostPrice = value }) // 计算之前全部赋值为0 在重新做计算 this.productList1.allQuatity = 0 this.productList1.allCostPrice = 0 this.productList1.allPrice = 0 // 计算每个产品 单个总价 for (var j = 0; j < this.productList1.length; j++) { that.productList1[j].chnegbenSumPrice = Number(that.productList1[j].productSum) * Number(that .productList1[j].CostPrice) that.productList1[j].chnegbenSumPrice = that.productList1[j].chnegbenSumPrice.toFixed(2) that.productList1[j].hejiSumPrice = Number(that.productList1[j].productSum) * Number(that.productList1[ j].RetailPrice) that.productList1[j].hejiSumPrice = that.productList1[j].hejiSumPrice.toFixed(2) } // 计算全部总价格 for (var m = 0; m < this.productList1.length; m++) { that.productList1.allQuatity = Number(that.productList1.allQuatity) + Number(that.productList1[m] .productSum) that.productList1.allQuatity = Number(that.productList1.allQuatity).toFixed(2) that.productList1.allCostPrice = Number(that.productList1.allCostPrice) + Number(that.productList1[m] .CostPrice) * Number(that.productList1[m].productSum) that.productList1.allCostPrice = Number(that.productList1.allCostPrice).toFixed(2) that.productList1.allPrice = Number(that.productList1.allPrice) + Number(that.productList1[m] .RetailPrice) * Number(that.productList1[m].productSum) that.productList1.allPrice = Number(that.productList1.allPrice).toFixed(2) } }, //删除产品 deleteList(e) { this.show1 = true this.deleteItem = e }, //确定删除产品 confirmRemove() { let that = this for (var j = 0; j < this.productList1.length; j++) { if (that.productList1[j].ID == that.deleteItem.ID) { that.productList1[j].productSum = 0 that.productList1[j].chnegbenSumPrice = 0 that.productList1[j].hejiSumPrice = 0 that.productList1.splice(j, 1) break } } for (var j = 0; j < this.detailsproductList1.length; j++) { if (that.detailsproductList1[j].ID == that.deleteItem.ID) { that.detailsproductList1[j].productSum = 0 that.detailsproductList1[j].chnegbenSumPrice = 0 that.detailsproductList1[j].hejiSumPrice = 0 that.detailsproductList1.splice(j, 1) break } } for (var j = 0; j < this.saomaArrList.length; j++) { if (that.saomaArrList[j].ID == that.deleteItem.ID) { that.saomaArrList[j].productSum = 0 that.saomaArrList[j].chnegbenSumPrice = 0 that.saomaArrList[j].hejiSumPrice = 0 that.saomaArrList.splice(j, 1) break } } for (var j = 0; j < this.lastGouxuan.length; j++) { if (that.lastGouxuan[j].ID == that.deleteItem.ID) { that.lastGouxuan[j].productSum = 0 that.lastGouxuan[j].chnegbenSumPrice = 0 that.lastGouxuan[j].hejiSumPrice = 0 that.lastGouxuan.splice(j, 1) break } } if (this.lastGouxuan.length > 0) { this.submit_queDing = '确定' + '(' + this.lastGouxuan.length + ')' } else { this.submit_queDing = '确定' } this.show1 = false // 计算之前全部赋值为0 在重新做计算 this.productList1.allQuatity = 0 this.productList1.allCostPrice = 0 this.productList1.allPrice = 0 // 计算全部总价格 for (var m = 0; m < this.productList1.length; m++) { that.productList1.allQuatity = Number(that.productList1.allQuatity) + Number(that.productList1[m] .productSum) that.productList1.allQuatity = Number(that.productList1.allQuatity).toFixed(2) that.productList1.allCostPrice = Number(that.productList1.allCostPrice) + Number(that.productList1[m] .CostPrice) * Number(that.productList1[m].productSum) that.productList1.allCostPrice = Number(that.productList1.allCostPrice).toFixed(2) that.productList1.allPrice = Number(that.productList1.allPrice) + Number(that.productList1[m] .RetailPrice) * Number(that.productList1[m].productSum) that.productList1.allPrice = Number(that.productList1.allPrice).toFixed(2) } }, } } </script> <style lang="scss" scoped> @import '@/publicStyle/itemManagementStyle/WarehouseList/scss/AddWarehouseEntry.scss' </style> 报Extraneous non-props attributes (DetailsID, shenheStatus) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. at <AddWarehouseEntry>错误
08-21
<template> <view> <view class="map" id="mapDiv" style="width: 100%;height: 80vh;z-index: 0;position: relative;" :prop="dataOption" :change:prop="Trenderjs.initTMap" :change:renderTrigger="Trenderjs.handleMessage" :renderTrigger="triggerCounter"> </view> </view> </template> <script> export default { data() { return { msg: '我是service层原来的msg', triggerCounter: 0, isProcessing: false, // 新增状态锁 message: null }; }, props: { dataOption: { type: String, default: '' }, }, methods: { renderjsData() { console.log('----------', this.triggerCounter); if (this.isProcessing) return; // 阻止重复触发 this.isProcessing = true; this.triggerCounter++ console.log('=============', this.triggerCounter); }, someMethodInVue(newVal) { console.log('位置', newVal); this.$emit('childEvent', newVal); this.message = newVal this.isProcessing = false; } } }; </script> <script module="Trenderjs" lang="renderjs"> var control; export default { data() { return { tk: '27657afc3318f8f2166fceba83427734', options: { lng: '104.397894', lat: '31.126855', }, iconType: "default", dataList: [], pointList: [], Tmap: null, gisDataObj: {}, gisData: {}, geocode: null, gisPointLngLat: {} } }, mounted() { if (!window.T) { console.log('00000', ); const script = document.createElement('script') script.src = 'http://api.tianditu.gov.cn/api?v=4.0&tk=' + this.tk // this.initChartsRender.bind() document.head.appendChild(script) script.onload = this.initChartsRender.bind() } else { console.log('++++', ); const { lng, lat } = this.options this.Tmap = null; console.log(this.Tmap); this.Tmap = new T.Map('mapDiv'); this.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); this.Tmap.setStyle("indigo"); //设置地图主体颜色indigo this.Tmap.disableDoubleClickZoom(); this.Tmap.disableScrollWheelZoom(); this.Tmap.disableInertia() this.Tmap.disableKeyboard() //创建对象 this.geocode = new T.Geocoder(); control = new T.Control.Zoom(); this.Tmap.addControl(control); var controlPosition = T_ANCHOR_BOTTOM_RIGHT; control.setPosition(controlPosition); // Tmap.enableDrag(); // this.setIcon(lng, lat, true, '') } }, created() { }, methods: { // 初始化地图 initTMap(newValue, oldValue) { let that = this; // 开启实时定位监听 that._watchId && plus.geolocation.clearWatch(that._watchId); // 先清除旧的监听 that._watchId = plus.geolocation.watchPosition(successCB => { let data = { lng: successCB.coords.longitude, lat: successCB.coords.latitude } console.log('实时定位:', data.lng, data.lat); that.Tmap.centerAndZoom(new T.LngLat(data.lng, data.lat), 20); var point = new T.LngLat(data.lng, data.lat); const marker = new T.Marker(point, { // icon }); that.Tmap.clearOverLays(); // 可选:每次清除旧的覆盖物 that.Tmap.addOverLay(marker); var label = new T.Label({ text: '实时定位:' + data.lng + ',' + data.lat, position: point, offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); }, err => { console.log(err); }, { provider: 'system', enableHighAccuracy: true, }); // let that = this if (newValue) { setTimeout(function() { console.log(JSON.parse(newValue)); that.gisDataObj = JSON.parse(newValue) console.log(JSON.parse(that.gisDataObj.data)); that.gisData = JSON.parse(that.gisDataObj.data) // if (that.gisData.length > 0) { // that.options = { // lng: that.pointList[0].deviceDeploymentLocation.split(',')[1], // lat: that.pointList[0].deviceDeploymentLocation.split(',')[0] // } // } else { let gisPoint = JSON.parse(that.gisData.data) that.gisPointLngLat = JSON.parse(that.gisData.data) if (that.gisData.type == 'marker') { that.options = { lng: gisPoint.lng, lat: gisPoint.lat, } } else if (that.gisData.type == 'polyline' || that.gisData.type == 'polygon') { that.options = { lng: gisPoint[0].lng, lat: gisPoint[0].lat, } } else { that.options = { lng: '104.397894', lat: '31.126855', } } const { lng, lat } = that.options that.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); if (that.gisData.type == 'marker') { var point = new T.LngLat(gisPoint.lng, gisPoint.lat); console.log(point); const marker = new T.Marker(point, { // icon }); that.Tmap.addOverLay(marker); var label = new T.Label({ text: that.gisData.name, position: point, offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); } else if (that.gisData.type == 'polyline') { let points = []; for (let i = 0; i < gisPoint.length; i++) { points.push(new T.LngLat(gisPoint[i].lng, gisPoint[i].lat)); } //创建线对象 var line = new T.Polyline(points, { color: that.gisDataObj.color, weight: 6, }); //向地图上添加线 that.Tmap.addOverLay(line); var label = new T.Label({ text: that.gisData.name, position: points[points.length - 1], offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); } else if (that.gisData.type == 'polygon') { let points = []; for (let i = 0; i < gisPoint.length; i++) { points.push(new T.LngLat(gisPoint[i].lng, gisPoint[i].lat)); } //创建线对象 var polygon = new T.Polygon(points, { color: that.gisDataObj.color, weight: 6, }); //向地图上添加线 that.Tmap.addOverLay(polygon); var label = new T.Label({ text: that.gisData.name, position: points[points.length - 1], offset: new T.Point(-40, 10) }); //创建地图文本对象 that.Tmap.addOverLay(label); } }, 1000); } }, // 若没有加载地图方法 initChartsRender() { const { lng, lat } = this.options var that = this; this.Tmap = new T.Map('mapDiv'); this.Tmap.centerAndZoom(new T.LngLat(lng, lat), 15); this.Tmap.setStyle("indigo"); //设置地图主体颜色indigo this.Tmap.disableDoubleClickZoom(); this.Tmap.disableScrollWheelZoom(); this.Tmap.disableInertia() this.Tmap.disableKeyboard() control = new T.Control.Zoom(); this.Tmap.addControl(control); var controlPosition = T_ANCHOR_BOTTOM_RIGHT; control.setPosition(controlPosition); // Tmap.enableDrag(); // this.setIcon(lng, lat, true, '') }, // 地图图标Icon setIcon(lng, lat, isClear, markerActive) { if (isClear) { // if (this.iconType == 'searchIcon') { // this.Tmap.clearOverLays() // } else { this.Tmap.removeOverLay(markerActive) // } } console.log(this.gisData); let gisPoint = JSON.parse(this.gisData.data) }, // RenderJS事件处理器 handleMessage(newVal, oldVal) { console.log(newVal, oldVal); if (newVal !== oldVal) { const center = this.Tmap.getCenter(); var lo = new T.Geolocation(); let that = this // let gisPoint = JSON.parse(this.gisData.data) const fn = function(e) { let distance = that.getDistance(e.lnglat.lat, e.lnglat.lng, that.gisPointLngLat.lat, that .gisPointLngLat.lng) that.$ownerInstance.callMethod('someMethodInVue', { lng: e.lnglat.lng, lat: e.lnglat.lat, distance: distance * 1000 }); // // if (this.getStatus() == 0) { // that.Tmap.centerAndZoom(e.lnglat, 15) // console.log('e.lnglat000', e.lnglat.lat, e.lnglat.lng); // // var marker = new T.Marker(e.lnglat); // // that.Tmap.addOverLay(marker); // // } // // if (this.getStatus() == 1) { // console.log('e.lnglat111', e.lnglat.lat, e.lnglat.lng); // that.Tmap.centerAndZoom(e.lnglat, e.level) // // var marker = new T.Marker(e.lnglat); // // that.Tmap.addOverLay(marker); // // } } lo.getCurrentPosition(fn); } }, getDistance(lat1, lng1, lat2, lng2) { console.log(lat1, lng1, lat2, lng2); const radLat1 = (lat1 * Math.PI) / 180.0 const radLat2 = (lat2 * Math.PI) / 180.0 const a = radLat1 - radLat2 const b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0 let s = 2 * Math.asin( Math.sqrt( Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2) ) ) s *= 6378.137 // EARTH_RADIUS; s = Math.round(s * 100) / 100 console.log(s); return s // 调用 return的距离单位为km } }, } </script> 在此代码进行更改,生成完整的代码
07-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@百思不如奇解

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值