onSubmit="return validate(this)"

博客介绍了表单验证功能,onSubmit=\return validate(this)\可验证表单,validate()函数返回true时表单提交,反之则不提交,this代表当前表单对象。还提及函数有function和sub两种定义方式,前者有返回值,用return语句返回,后者无返回值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

onSubmit="return validate(this)"

是一个验证表单的功能。

当validate()这个函数返回值是true的时候,表单提交,反之则不提交。
而this是一个参数,代表的当前表单对象~~~~。
函数有两种定义方式function 和sub。function声明的函数有返回值,用return语句返回这个值;而sub声明的函数没有返回值。

Component({ properties: { show: { type: Boolean, value: false }, title: { type: String, value: '表单标题' }, config: { type: Array, value: [] }, formData: { type: Object, value: {} }, modalName: { type: String, value: '' }, initData: { type: null, value: null, observer: function (newVal) { newVal && this.processInitData(newVal) } } }, data: { parentParams: {}, tempData: {}, errors: {}, processedConfig: [], loading: false }, observers: { 'show, modalName'(show, modalName) { show && modalName && this.loadModalConfig(modalName) } }, methods: { // 加载弹窗配置 async loadModalConfig(modalName) { this.setData({ loading: true }) try { let config = getModalConfig(modalName) if (!config) throw new Error(`未找到弹窗配置: ${modalName}`) // 处理前置逻辑 config = await this.processBeforeShow(config) this.setData({ processedConfig: config, loading: false }) } catch (error) { console.error('加载失败:', error) this.setData({ loading: false }) this.triggerEvent('error', { error }) } }, // 处理前置逻辑 async processBeforeShow(config) { const initData=this.properties.initData let processedConfig = []; if (initData) { if (Array.isArray(initData)) { // 处理数组类型 processedConfig.config = config.config.map((item, index) => index < initData.length ? { ...item, ...initData[index] } // 正确合并属性 : { ...item } // 超出部分保留原配置 ); return processedConfig; } else if (typeof initData === "object") { // 处理对象类型 processedConfig.config = config.config.map(configItem => { const key = configItem.field; return initData.hasOwnProperty(key) ? { ...configItem, ...initData[key] } // 直接属性访问 : { ...configItem }; }); return processedConfig; } } if (typeof config.beforeShow === 'function') { beforeData= await config.beforeShow() processedConfig.config = config.config.map(configItem => { const key = configItem.title; return beforeData.hasOwnProperty(key) ? { ...configItem, ...beforeData[key] } // 直接属性访问 : { ...configItem }; }); return processedConfig; } return config }, // 表单验证 validateForm() { const errors = {} this.data.processedConfig.config.forEach(section => { section.forEach(item => { if (item.verify && !this.data.formData[item.field]) { if(!item.verify(item.field)) errors[item.field] = item.errorMessage || `${item.title}必填` } }) }) return errors }, // 提交处理 async submitForm() { if (this.data.loading) return // 验证表单 const errors = this.validateForm() if (Object.keys(errors).length) { return this.setData({ errors }) } if(this.data.processedConfig.onSubmit){ this.data.processedConfig.onSubmit() this.setData({ loading: true }) this.closeModal() return; } try { this.setData({ loading: true }) // 触发提交事件 this.triggerEvent('submit', this.data.formData) this.closeModal() } finally { this.setData({ loading: false }) } }, // 关闭弹窗 closeModal() { this.setData({ show: false, processedConfig: [] }) this.triggerEvent('close') }, // 输入处理 handleInput(e) { const field = e.currentTarget.dataset.field const value = e.detail.value || e.detail this.setData({ [`formData.${field}`]: value, [`errors.${field}`]: '' }) this.data.processedConfig.config.forEach(section => { section.forEach(item => { if (item.onChange && !this.data.formData[item.field]) { item.onChange(item.field) } }) }) this.triggerEvent('change', { field, value }) } } })
最新发布
08-04
<template> <div> <el-dialog :title="!dataForm.id ? '指令生成' : '修改'" :close-on-click-modal="false" v-dialogDrag :visible.sync="visible" id="myOrder"> <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px" style="margin-top: -0.275rem;background-color: #fff;border: 0px solid #DCDFE6;"> <!-- 升级类型 1-BMS升级 2-Tracker通讯板升级 --> <el-form-item label="升级类型" size="mini" prop="type"> <el-radio-group v-model="dataForm.type" :disabled="dataForm.id ? 'disabled' : null"> <el-radio :label="1">BMS升级</el-radio> <el-radio :label="2">Tracker通讯板升级</el-radio> <!-- <el-radio :label="2">参数设置</el-radio> --> </el-radio-group> </el-form-item> <el-form-item label="项目" prop="projectParameter"> <el-select v-model="dataForm.projectParameter" placeholder="请选择项目" @change="blurSelect" style="width:6rem" clearable> <el-option v-for="item in projectIds" :key="item.value" :label="item.label" :value="item.value"> </el-option> </el-select> </el-form-item> <el-form-item label="项目名称" prop="projectRef"> <el-input v-model="dataForm.projectRef" placeholder="项目简称" style="width:6rem" readonly></el-input> </el-form-item> <el-form-item label="升级模式" size="mini" prop="orderType"> <el-radio-group v-model="dataForm.orderType" :disabled="dataForm.id ? 'disabled' : null"> <el-radio :label="1" @change="typeChange(1)">指定设备升级</el-radio> <el-radio :label="0" @change="typeChange(0)">所有设备升级</el-radio> </el-radio-group> </el-form-item> <el-form-item label="设备导入" v-if="showotaall"> <!-- <el-button v-if="isAuth('maya:myotarequest:batchUpgrade')" type="success" @click="otaBatchUpgradeHandle()" :disabled="dataListSelections.length != 2">批量升级</el-button> --> <el-button type="success" @click="otaBatchUpgradeHandle()" >Excel导入</el-button> </el-form-item> <el-form-item label="设备编号" prop="deviceCodes" v-if="showotaall"> <!-- <el-input v-model="dataForm.deviceCodes" placeholder="设备编号。多个用“;”隔开,如下224042102999025;411219000005615;411219000005617"></el-input> --> <el-autocomplete style="width:10rem" size="normal" v-model="dataForm.deviceCodes" :popper-append-to-body="false" :fetch-suggestions="querySearchAsync" @select="handleSelect" placeholder="请输入设备编号。多个用“;”隔开,如下224042102999025;411219000005615;411219000005617"> </el-autocomplete> </el-form-item> <el-form-item label="Topic" prop="topic"> <el-select v-model="dataForm.topic" placeholder="请选择topic" style="width:6rem" > <el-option v-for="item in topics" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" > </el-option> </el-select> </el-form-item> <!-- <el-form-item label="通讯方式" prop="communicationMode"> <el-input v-model="dataForm.communicationMode" placeholder="通讯方式 0:暂无 1:串口 2:can 3:i2c"></el-input> </el-form-item> --> <!-- <el-form-item label="通讯类型" size="mini" prop="communicationMode"> <el-radio-group v-model="dataForm.communicationMode" :disabled="dataForm.id ? 'disabled' : null"> <el-radio :label="1">串口</el-radio> <el-radio :label="2">can</el-radio> <el-radio :label="3">i2c</el-radio> </el-radio-group> </el-form-item> --> <!-- <el-form-item label="can通讯的帧id" prop="frameIdCan"> <el-input v-model="dataForm.frameIdCan" placeholder="can通讯的帧id"></el-input> </el-form-item> <el-form-item label="通讯数据" prop="payload"> <el-input v-model="dataForm.payload" placeholder="通讯的数据"></el-input> </el-form-item> --> <!-- <el-form-item label="升级固件地址" prop="url"> <el-input v-model="dataForm.url" placeholder="升级时的固件地址"></el-input> </el-form-item> --> <!-- <el-form-item label="*固件地址" prop="url" v-if="showota"> --> <el-form-item label="*固件地址" prop="url"> <el-select v-model="dataForm.url" placeholder="升级固件地址" style="width:10rem"> <el-option v-for="item in uploadurls" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled" > </el-option> </el-select> </el-form-item> <el-form-item label="硬件版本" prop="hardwareversion"> <el-input v-model="dataForm.hardwareversion" placeholder="要升级的目标电池硬件版本" style="width:6rem;padding-left:0.0rem;"></el-input> <br/><span style="color:blue;font-size:13px">✸ 可不填写,若指定要升级的目标电池硬件版本,填写请在前面请带上“V”,如V1.00,V1.02</span> </el-form-item> <el-form-item label="*软件版本" prop="softwareversion"> <el-input v-model="dataForm.softwareversion" placeholder="当前升级的固件的软件版本" style="width:6rem"></el-input> </el-form-item> <el-form-item label="是否执行" size="mini" prop="todoNow"> <el-radio-group v-model="dataForm.todoNow"> <el-radio :label="0">等待</el-radio> <el-radio :label="1">立即执行</el-radio> </el-radio-group> </el-form-item> <!-- <el-form-item label="固件MD5" prop="md5"> <el-input v-model="dataForm.md5" placeholder="固件MD5"></el-input> </el-form-item> <el-form-item label="固件大小" prop="size"> <el-input v-model="dataForm.size" placeholder="固件大小"></el-input> </el-form-item> <el-form-item label="配置是否处理 " prop="handled"> <el-input v-model="dataForm.handled" placeholder="配置是否处理 1:已处理 0:待处理"></el-input> </el-form-item> <el-form-item label="是否立即执行" prop="todoNow"> <el-input v-model="dataForm.todoNow" placeholder="是否立即执行 0:等待执行 1:立即执行"></el-input> </el-form-item>--> <!-- <el-form-item label="是否执行" size="mini" prop="todoNow"> <el-radio-group v-model="dataForm.todoNow"> <el-radio :label="0">等待</el-radio> <el-radio :label="1">执行</el-radio> </el-radio-group> </el-form-item> --> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="visible = false">取消</el-button> <el-button type="primary" @click="dataFormSubmit()">生成指令</el-button> </span> </el-dialog> <!-- 弹窗, Excel导入--> <ota-batch-upgrade v-if="otaBatchUpgradeVisible" ref="otaBatchUpgrade" @refreshDataList="onSubmit(1)"></ota-batch-upgrade> </div> </template> <script> import OtaBatchUpgrade from './myotabatchupgrade' export default { data () { return { visible: false, showotaall: true, otaBatchUpgradeVisible: false, projectIds:[], uploadurls:[], topics: [{ value: '/{productKey}/{deviceId}/maya7026/ota/upgrade/push', label: '固件升级(ota/upgrade/push)' } // , { // value: '/{productKey}/{deviceId}/upgradebox/{projectRef}/property/get', // label: '电池数据获取(property/get)' // } ], dataForm: { id: 0, type: 1, orderType: 1, projectParameter: '', deviceCodes: '', projectRef: '', topic: '', // communicationMode: 1, // frameIdCan: '', payload: '', url: '', hardwareversion: '', softwareversion: '', md5: '', size: '', handled: '', todoNow: 0, createTime: '', updateTime: '' }, dataRule: { type: [ { required: true, message: '升级类型 1-BMS升级 2-Tracker通讯板升级 不能为空', trigger: 'blur' } ], orderType: [ { required: true, message: '升级模式勾选 不能为空', trigger: 'blur' } ], projectParameter: [ { required: true, message: '不能为空', trigger: 'blur' } ], // deviceCodes: [ // { required: true, message: '设备编号不能为空', trigger: 'blur' } // ], // projectRef: [ // { required: true, message: '项目简称(用于topic)不能为空', trigger: 'blur' } // ], topic: [ { required: true, message: 'mqtt发送主题,如:battery/{batteryCode}/down/upgrade不能为空', trigger: 'blur' } ], // communicationMode: [ // { required: true, message: '通讯方式 0:暂无 1:串口 2:can 3:i2c不能为空', trigger: 'blur' } // ], // frameIdCan: [ // { required: true, message: 'can通讯的帧id不能为空', trigger: 'blur' } // ], // payload: [ // { required: true, message: '通讯的数据不能为空', trigger: 'blur' } // ], // url: [ // { required: true, message: '升级时的固件地址不能为空', trigger: 'blur' } // ], // md5: [ // { required: true, message: '固件MD5不能为空', trigger: 'blur' } // ], // size: [ // { required: true, message: '固件大小不能为空', trigger: 'blur' } // ], // handled: [ // { required: true, message: '配置是否处理 1:已处理 0:待处理不能为空', trigger: 'blur' } // ], todoNow: [ { required: true, message: '是否立即执行 0:等待执行 1:立即执行不能为空', trigger: 'blur' } ], // createTime: [ // { required: true, message: '不能为空', trigger: 'blur' } // ], // updateTime: [ // { required: true, message: '更新时间不能为空', trigger: 'blur' } // ] } } }, components: { OtaBatchUpgrade, }, methods: { typeChange(val){ // alert('packageChange') if(val=='1'){ // 指定电池升级,打开电池编号输入框 this.showotaall = true }else if(val=='0'){ // ota升级项目下所有电池 this.showotaall = false } }, // el-select失去焦点必填校验 blurSelect() { var project_name = this.dataForm.projectParameter.substring(this.dataForm.projectParameter.lastIndexOf("::")+2) this.$set(this.dataForm,'projectRef', project_name) }, querySearchAsync(queryString, cb) { clearTimeout(1000); var results = [] // alert('queryString='+queryString) if (queryString == '') { cb(results); } else { //掉接口需要的参数 this.$http({ url: this.$http.adornUrl('/mqtt/mqtttriad/getDeviceIds'), method: 'get', params: this.$http.adornParams({ 'deviceId': queryString, 'projectParameter': this.dataForm.projectParameter }) }).then(({data}) => { if (data && data.code === 0) { // alert(data.data.length) var result = data.data //循环放到一个远程搜索需要的数组 for (let i = 0; i < result.length; i++) { const element = result[i]; // alert(element) results.push({ value: element, id: i }) } cb(results); } else { console.log('没有数据的显示') results = [] cb(results); } }) } }, //点击出现搜索后点击的每一项 handleSelect(item) { this.id = item.id this.name = item.value }, init (id) { this.dataForm.id = id || 0 this.showotaall = true this.visible = true this.$nextTick(() => { this.$refs['dataForm'].resetFields() if (this.dataForm.id) { this.$http({ url: this.$http.adornUrl(`/maya/myotarequest/info/${this.dataForm.id}`), method: 'get', params: this.$http.adornParams() }).then(({data}) => { if (data && data.code === 0) { this.projectIds = data.data.projectMenus.projectIds this.uploadurls = data.data.OtaUrlMenus.uploads const socitem = data.data.mqttSends this.dataForm.type = socitem.type this.dataForm.projectParameter = socitem.projectParameter this.dataForm.deviceCodes = socitem.deviceCodes this.dataForm.projectRef = socitem.projectRef this.dataForm.topic = socitem.topic // this.dataForm.communicationMode = socitem.communicationMode // this.dataForm.frameIdCan = socitem.frameIdCan // this.dataForm.payload = socitem.payload this.dataForm.url = socitem.url this.dataForm.md5 = socitem.md5 this.dataForm.size = socitem.size this.dataForm.handled = socitem.handled this.dataForm.todoNow = socitem.todoNow this.dataForm.createTime = socitem.createTime this.dataForm.updateTime = socitem.updateTime } }) }else{ this.$http({ url: this.$http.adornUrl(`/maya/myotarequest/getOtaAndProjectMenus`), method: 'get', params: this.$http.adornParams() }).then(({data}) => { if (data && data.code === 0) { this.projectIds = data.data.projectMenus.projectIds this.uploadurls = data.data.OtaUrlMenus.uploads } }) } }) }, /** * 设备导入弹窗触发方法 */ otaBatchUpgradeHandle(){ this.otaBatchUpgradeVisible=true this.$nextTick(()=>{ this.$refs.otaBatchUpgrade.init() }) }, // 表单提交 dataFormSubmit () { if(this.dataForm.orderType==='1' || this.dataForm.orderType===1){ if(this.dataForm.deviceCodes === '' || this.dataForm.deviceCodes === undefined || this.dataForm.deviceCodes === null){ this.$message.warning('选择指定电池升级的,设备编号不能为空!') return } } // if(this.dataForm.type==='0' || this.dataForm.type===0){ if(this.dataForm.url === '' || this.dataForm.url === undefined || this.dataForm.url === null){ this.$message.warning('升级固件地址不能为空!') return } // if(this.dataForm.hardwareversion === '' || this.dataForm.hardwareversion === undefined || this.dataForm.hardwareversion === null){ // this.$message.warning('升级硬件版本不能为空!') // return // } if(this.dataForm.softwareversion === '' || this.dataForm.softwareversion === undefined || this.dataForm.softwareversion === null){ this.$message.warning('升级软件版本不能为空!') return } // } this.$refs['dataForm'].validate((valid) => { if (valid) { this.$http({ url: this.$http.adornUrl(`/maya/myotarequest/create`), method: 'post', data: this.$http.adornData({ 'id': this.dataForm.id || undefined, 'type': this.dataForm.type, 'orderType': this.dataForm.orderType, 'projectParameter': this.dataForm.projectParameter, 'deviceCodes': this.dataForm.deviceCodes, 'projectRef': this.dataForm.projectRef, 'topic': this.dataForm.topic, // 'communicationMode': this.dataForm.communicationMode, // 'frameIdCan': this.dataForm.frameIdCan, // 'payload': this.dataForm.payload, 'url': this.dataForm.url, 'hardwareversion': this.dataForm.hardwareversion, 'softwareversion': this.dataForm.softwareversion, 'md5': this.dataForm.md5, 'size': this.dataForm.size, 'handled': this.dataForm.handled, 'todoNow': this.dataForm.todoNow, 'createTime': this.dataForm.createTime, 'updateTime': this.dataForm.updateTime }) }).then(({data}) => { if (data && data.code === 0) { this.$message({ message: '操作成功', type: 'success', duration: 1500, onClose: () => { this.visible = false this.$emit('refreshDataList') // this.$emit('refreshDataList', this.dataForm.type,this.dataForm.communicationMode,this.dataForm.deviceCodes); } }) } else { this.$message.error(data.msg) } }) } }) } } } </script> <style> #myOrder element.style { width: 150px; } </style>父组件是这样的
07-12
<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
<think>根据用户查询,用户想检查表单ID是否不为空的条件判断。用户提到了"this.form.idnotequalnullconditioncheck"。分析用户需求:1.用户希望在表单操作中进行条件判断2.判断条件是表单的id属性不为null3.使用场景可能是表单验证或表单提交前的检查参考提供的引用:-引用[1]中提到条件包装在"trigger"函数中,但这与SQL子查询相关,不直接适用-引用[2]是前端的模糊效果代码,虽在网页表单场景但无关条件判断-引用[3]讨论JordanForm,不相关-引用[4]关于选项组和套接字选项,也不相关因此主要基于web开发常见实践回答。在JavaScript中进行表单字段验证的典型方法:解决方案:1.使用简单的条件语句检查`this.form.id`不为null2.注意:`this.form.id`表示表单元素的id属性,但更常见的验证对象是表单字段值3.用户意图可能是验证表单中某个字段(如名为"id"的字段)的值不为空假设是标准HTML表单验证场景:-表单元素通常通过`document.getElementById`或`this.form.fieldName`访问-检查字段值非空常用:`if(field.value)`或`if(field.value!==null&&field.value!=='')`代码示例:```javascript//在表单提交事件处理函数中functionvalidateForm(form){//检查ID字段不为空if(form.id.value){//非空时的处理returntrue;}else{alert("ID不能为空!");returnfalse;//阻止表单提交}}//在HTML中:<formonsubmit="returnvalidateForm(this)">```注意:-`form.id.value`若对应input字段,空值时可能是空字符串而非null,所以检查空字符串更常见-精确的条件检查:`if(form.id.value!==null&&form.id.value!=='')`或简写`if(form.id.value!=null&&form.id.value.length>0)`用户可能误解引用内容,但根据其原始查询,应直接回答表单验证问题。</think> 根据您的需求,需要检查表单字段ID是否非空的条件判断。以下是推荐实现方案,结合引用[2]中的前端技术思路: ### 条件判断实现方案 ```html <script> function validateForm() { // 检查表单ID是否非空(严格不等于null且不等于空字符串) if (this.form.id !== null && this.form.id.value.trim() !== '') { // 符合条件时执行操作 console.log("ID校验通过"); return true; } else { // 不符合条件时处理(可添加引用[2]的模糊效果) alert("ID不能为空!"); this.form.id.focus(); // 聚焦到字段 return false; } } </script> <!-- 在表单中使用示例 --> <form onsubmit="return validateForm.call(this)"> <input type="text" id="id" name="id"> <button type="submit">提交</button> </form> ``` ### 关键说明: 1. **双重验证**: - `this.form.id !== null` 检查DOM对象是否存在(避免空指针错误) - `value.trim() !== ''` 验证输入内容非空 - 使用`call(this)`确保`this`指向当前表单[^2] 2. **防御性编程**: ```javascript // 安全访问嵌套属性 if (this?.form?.id?.value?.trim() !== '') ``` 3. **扩展功能**(参考引用[2]交互): ```javascript // 添加失焦验证 document.getElementById("id").addEventListener("blur", function() { if(this.value.trim() === '') alert("ID不能为空"); }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值