- CSDN文库",
"datePublished": "2025-07-19",
"keywords": "
",
"description": "文章浏览阅读6次。这是一个Vue单文件组件(SFC),包含了一个地图展示和交互的功能。主要功能包括:地图配置、模态框显示、实时视频播放、点位管理、报警处理等。代码结构包括模板、脚本和样式三部分。 模板部分(template): - 包含地图配置组件(mapConfigs) - 模态框组件(myModal)用于显示设备详情或报警信息"
}
首页<template>
<div class="map-content">
<mapConfigs></mapConfigs>
<myModal :modalVisible.sync="showModal" :isWarning="isWarning" :isArea="isArea" :resouceInfo="resouceInfo" @cancel="cancel" :hostDetailList="hostDetailList" :systemDetailList="systemDetailList"></myModal>
<realPlayer :isShow="showVideoModal" :resouceInfo="resouceInfo" @cancel="cancel" :hostDetailList="hostDetailList"></realPlayer>
<btnComponent :curBitmapMakerList="curBitmapMakerList" :map="map" :markerResourceFlooterIcon="markerResourceFlooterIcon" :fireControlLayerArr="fireControlLayerArr" :selectNode="selectNode" :mapState="mapStatePreparation"></btnComponent>
</div>
</template>
<script>
import mapConfigs from "@/components/scfComponents/emapComponentsV1_4_0/mapConfigBase";
// import factory from "./factory";
import layers from './layers';
import {mapApi} from "EvoEmap"
import {nofifyClient} from '@/common/js/client'
// 点位悬浮点击
import popup from "./mixin/popup";
// 添加点位到地图
import indexAddMakeToMap from "./mixin/indexAddMakeToMap";
// 报警点位循环变换 类
import keyMakerLoopClass from "./classFunction/keyMakerLoopClass";
// 创建报警队列中心 类
import evenQueueFunctionClass from "./classFunction/evenQueueFunctionClass";
// 热区 设备点位 数据组装 类
import waitAllMakeInfoDoneHandleClass from "./classFunction/waitAllMakeInfoDoneHandleClass";
// 添加 图层方法
import addNewLayerFunction from "./classFunction/addNewLayerFunction";
// 清除feature 方法
import clearAllLayersFunction from "./classFunction/clearAllLayersFunction";
// diff 对比点位信息
import diffMakerInfo from "./classFunction/diffMakerInfo";
import btnComponent from "./components/buttonComponent";
import myModal from "./components/myModal";
import realPlayer from "@/components/scfComponents/videoPlayers/realPlayer";
export default {
mixins: [popup, indexAddMakeToMap],
props: {
curWarningMarker: {
type: Object,
default: () => ({})
},
isWarningDialog: {
type: Boolean,
default: false
},
showTree: {
type: Boolean,
default: true
},
selectNode: {
type: Object,
default: () => {
return {};
}
},
pollingMarker: {
type: String,
default: () => '',
},
},
components: {
mapConfigs,
myModal,
realPlayer,
btnComponent
},
data() {
return {
map: null,
curBitmap: null,
refsEmap: null,
resouceInfo: {},
allLayers: layers,
markerResourceList:[], //所有的点位资源
allLayersArr: [],//集成测试的所有图层
markerResourceFlooterIcon: [], //底部展示的点位资源
// 其它消防设备
fireControlLayerArr:[{
layerCode: 'fireControlLayer'
}], // 和消防相关的点位资源
// 记录所有的 点位
allMarkerLayers:[
{layerCode: 'hotareaLayer'},
{layerCode: 'videoLayer'},
{layerCode: 'fireControlLayer'},
],
curBitmapMakerList: {},
statusObj:{
1: 'alarm',
2: 'offline',
3: 'shield',
4: 'fault',
5: 'nomal',
},
mapStatePreparation:{}, // 监控地图状态
keyMakerLoop:{},
waitAllMakeInfoDone:{},
addNewLayer: addNewLayerFunction,
clearAllLayers: clearAllLayersFunction,
evenQueueClass: {},// ------------ 90175 ----报警逻辑 ---
diffMakerInfo: new diffMakerInfo(), // 对比点位信息
propMark: 'dataWall'
}
},
watch: {
dataWallMap(newVal, old) {
console.log("dataWallMap change ", newVal)
this.map = newVal
// 监控地图状态
this.setMapStatePreparation(0)
// 开始挂载点位的 事件
this.getMarkerLayers()
// 开始挂载点位的 事件
this.customizeMapFunction()
},
curBitmapObj(newVal, old) {
this.curBitmap = newVal
},
refsEmapObj(newVal, old) {
this.refsEmap = newVal
},
// 组织切换
selectNode: {
deep: true,
immediate: false,
handler(val, oldVal) {
let data = {id: null}
if(oldVal){
data = oldVal
}
if(val.id && val.id !== data.id) {
this.$store.commit("setOrgTreeNode", val);
// 监控地图状态
this.setMapStatePreparation(6)
}
},
},
pollingMarker: {
deep: true,
immediate: true,
handler(newVal) {
// 90175 每一分钟 刷新一次当前图标的 状态信息 用于 更新坐标的报警状态
// console.log("pollingMarker ==newVal==",newVal);
if(newVal && Object.keys(this.curBitmapMakerList).length){
// 监控地图状态
this.setMapStatePreparation(5)
}
},
},
// 地图点击事件回调
mapEventCallbackData: {
deep: false,
immediate: false,
handler(newVal, oldVal) {
console.log("mapEventCallbackData val ==", newVal);
var {type, event, features} = newVal
this.resouceInfo.clickType = ''
if(type == 'dblclick' && features) {
// 获取点位对象
let feature = features[0]
// 如果是聚合点位
if(feature.isClusterFeature && feature.size === 1) {
feature = feature.getProperties().features[0]
}
// 获取点位对象信息
let markerInfo = feature.getMarkerInfo()
console.log("markerInfo ==", markerInfo);
if(( ["fireControlLayer", "fireControlLayerAlarm", "fireControlLayerFault"].includes(markerInfo.layerCode)) && !markerInfo.channelType) {
console.log('打开设备详情');
this.isArea = false;
this.showModal = true;
this.resouceInfo = markerInfo.info;
this.resouceInfo.clickType = type
}
// 热区下钻
if (markerInfo.layerCode === "hotareaLayerAlarm") {
console.log('热区下钻 hotareaLayerAlarm', markerInfo);
if (markerInfo.id) {
mapApi.BitmapApi.getBitmapInfo(markerInfo.id).then(data => {
if (!data.isMain && !data.picId) {
this.$message.warning(this.$t('emap.tips.no-picture-info'))
return false
}
this.map.vuexCommit('EMAP_SET_CENTERMAP_ID', {id: markerInfo.id})
})
}
}
}
},
},
// ---------------- 90175 ------------ 未来需要 在报警处理后 或者设备状态改变后 设备的报警及时的消失 -----------
mapConfigWarningInfo(val) {
// console.log('mapConfigWarningInfo == ', val);
// if (!this.showTree) {
// return;
// }
// 报警逻辑
// this.evenQueueFunction(val)
this.evenQueueClass.evenQueueFunction(val)
},
// 获取推送的故障
pushFaultData: {
deep: true,
immediate: false,
handler(newVal) {
// console.log("pushFaultData ==", newVal);
// this.evenQueueFunction(newVal.data)
// 接收故障
this.evenQueueClass.evenQueueFunction(newVal.data)
},
},
},
computed: {
...Vuex.mapState({
// 90175 ---
dataWallMap: store => store.dataWallMap,
pushFaultData: store => store.alarm.pushFaultData,
mapConfigWarningInfo: store => store.mapConfigWarningInfo,
curBitmapObj: store => store.curBitmapObj,
refsEmapObj: store => store.refsEmapObj,
mapEventCallbackData: store => store.mapEventCallbackData,
// --- end---
}),
},
methods: {
/**
* 关闭弹窗的函数
* @param {*}
*/
cancel() {
this.showModal = false;
this.showVideoModal = false;
},
/**
* 监听到地图的信息的变化 开始执行点位的 操作 ----
*/
customizeMapFunction(){
var emap = this.map
// 混入 的 popup 的 方法 用于悬浮
this.setMapEvent(emap.map, emap);
},
// ---------------- 90175 第一步清楚地图 添加图层 ----------------
/**
*
* 1、 获取地图的图层
*
*/
// 获取地图的图层
getMarkerLayers() {
mapApi.ConfigApi.getMarkerLayers().then(res => {
if (typeof res !== 'undefined' && res.length > 0) {
// 该图层分类要在哪种地图类型下展示 mapType : -1 都不显示(GPS类设备), 0-GIS地图下,1-光栅图下,2-都显示
let curMapMode = this.map.mapConfig.gisMode // "1": 光栅地图, "0": gis地图, "3":三维地图
// console.log(`当前的地图类型: ${curMapMode}`)
let list = null
var fireControlLayerArr = this.fireControlLayerArr.map(item => {
return item.layerCode
})
if(!this.markerResourceFlooterIcon.length){
let markerResourceFlooterIcon = []
// console.log('fireControlLayerArr', ['hotareaLayer', 'videoLayer', ...fireControlLayerArr]);
if(curMapMode == "1" || curMapMode == "0" ) {
list = res.filter((item) => {
item.active = true
return item.mapType < 3 && item.mapType !== -1 && ['hotareaLayer', 'videoLayer', ...fireControlLayerArr].indexOf(item.layerCode)> -1
})
this.allLayersArr = res.filter((item) => {
item.active = true
return ['hotareaLayer', 'videoLayer', ...fireControlLayerArr].indexOf(item.layerCode) == -1
})
markerResourceFlooterIcon = res.filter((item) => {
item.active = true
return item.mapType < 3 && item.mapType !== -1 && ['hotareaLayer', 'videoLayer', 'fireControlLayer'].indexOf(item.layerCode)> -1
})
}
this.markerResourceFlooterIcon = []
let layerCode2index = {
'fireControlLayer': 0,
'videoLayer': 1,
'hotareaLayer': 2
}
markerResourceFlooterIcon.forEach(element => {
this.markerResourceFlooterIcon[layerCode2index[element.layerCode]] = element
});
this.markerResourceList = list
}
this.waitAllMakeInfoDoneHandle()
}
})
},
/**
* 整理数据并将marke 放置到地图上
*/
waitAllMakeInfoDoneHandle(){
this.curBitmapMakerList = {}
this.waitAllMakeInfoDone.waitAllMakeInfoDoneHandle(this.markerResourceList, this.map, this.selectNode, (res) => {
if(localStorage.getItem("showConsole")){
console.log('this.waitAllMakeInfoDone waitAllMakeInfoDoneHandle');
}
this.curBitmapMakerList = res
this.setMapStatePreparation(3)
})
},
// ----------------- end --------------
/**
* 记录 地图 状态
* @param {*} state 状态值
*
* 0 dataWallMap 地图创建完成
* 1 addMarkeToMap 已将点位放在地图上
* 2 addNewLayer 已将图层放在地图上
* 3 waitAllMakeInfoDoneHandle 数据处理完成 放置图标之前
* 4 changeLayerOfFeature 完成图层切换后
* 5 pollingMarker 接受到 一分钟的轮询
* 6 selectNode 组织树切换
* 7 收到推送后处理信息 将 curBitmapMakerList 内部的点位的info 改变
*/
setMapStatePreparation(state){
this.mapStatePreparation = {
time: new Date().getTime(),
state: state
}
this.setInfomation(state)
},
setInfomation(state){
if(localStorage.getItem("showConsole")){
console.log('setMapStatePreparation==', state);
}
if(state === 0) {
// 添加新的图层
// this.addNewLayer()
this.addNewLayer(this.allLayers, this.map, (res) => {
this.allMarkerLayers = res
// 监控地图状态
this.setMapStatePreparation(2)
})
this.keyMakerLoop.setMap(this.map) // 给报警循环传值地图
this.evenQueueClass.setMap(this.map) // 给报警推送处理传值地图
this.diffMakerInfo.setMap(this.map) // 给报对比点位信息传值地图
// mixin
this.setShunt(false) // 切换地图重新判定
this.diffMakerInfo.initBitmapMakerList() //初始化数据
}
if(state === 1){
}
if(state === 2){
// 给报警队列中心传值
this.evenQueueClass.setAllMarkerLayers(this.allMarkerLayers)
}
if(state === 3){
// mixin 中的方法 添加点位到地图上
this.shuntInfo()
}
if(state == 4){
// 完成图层切换后 setMapStatePreparation 设置 1 用去去掉 点位的 名称
this.setMapStatePreparation(1)
}
if(state === 5){
// 第一版本逻辑是清除所有的 图层上的点位 但是 性能测试不通过,所以进行了 精准更新 diff 方法
// this.clearAllLayers(this.allMarkerLayers, this.map, () => {
// this.waitAllMakeInfoDoneHandle()
// })
this.waitAllMakeInfoDoneHandle()
// if(this.pollingMarker.flag){
// this.waitAllMakeInfoDoneHandle()
// }
}
if(state === 7){
// 这时点位信息发生了改变 这时就要即使赋值给 diff
// 将最新的点位信息 传给 diff 类 setOldBitmapMakerList
this.diffMakerInfo.setOldBitmapMakerList(this.curBitmapMakerList)
this.setMapStatePreparation(1)
}
}
// ------end --
},
created() {
// 开始循环
this.keyMakerLoop = new keyMakerLoopClass()
// console.log("this.keyMakerLoop ==", this.keyMakerLoop);
this.keyMakerLoop.setAlarmMakerLoop()
// 创建报警队列中心
this.evenQueueClass = new evenQueueFunctionClass()
this.evenQueueClass.setMapStatePreparationFun(this.setMapStatePreparation)
// console.log("this.evenQueueClass =", this.evenQueueClass);
// 获取图层 上的所有点位
this.waitAllMakeInfoDone = new waitAllMakeInfoDoneHandleClass()
// console.log("this.waitAllMakeInfoDone ==", this.waitAllMakeInfoDone);
// 对比点位信息
// console.log('this.diffMakerInfo ==', this.diffMakerInfo);
this.diffMakerInfo.setMapStatePreparationFun(this.setMapStatePreparation)
}
}
</script>
<style lang="less">
@import './mapControl.less';
@import "./emap.less";
.map-content{
.page{
display: none;
}
}
</style>
<think>这是一个Vue单文件组件(SFC),包含了一个地图展示和交互的功能。主要功能包括:地图配置、模态框显示、实时视频播放、点位管理、报警处理等。代码结构包括模板、脚本和样式三部分。
模板部分(template):
- 包含地图配置组件(mapConfigs)
- 模态框组件(myModal)用于显示设备详情或报警信息
- 实时播放器组件(realPlayer)用于播放视频
- 按钮组件(btnComponent)用于地图操作按钮
脚本部分(script):
- 导入多个模块和类,包括地图配置、图层管理、报警处理等
- 使用mixins来复用点位悬浮点击、添加点位到地图等功能
- 定义了数据属性,如地图实例、当前点位、资源信息等
- 使用Vuex状态管理,通过computed属性获取状态
- 使用watch监听状态变化,如地图实例、当前点位、轮询标记、报警信息等
- 方法包括关闭弹窗、自定义地图功能、获取图层、处理点位数据、设置地图状态等
样式部分(style):
- 引入外部less文件
主要功能点:
1. 地图初始化与配置
2. 图层管理:添加、清除图层
3. 点位管理:获取点位数据、更新点位状态、添加点位到地图
4. 报警处理:接收报警推送,更新点位状态,循环报警点位
5. 交互功能:点击点位显示详情,双击点位下钻或播放视频
代码中使用了多个自定义类来处理复杂逻辑:
- keyMakerLoopClass: 处理报警点位的循环变换
- evenQueueFunctionClass: 报警事件队列处理
- waitAllMakeInfoDoneHandleClass: 热区设备点位数据组装
- addNewLayerFunction: 添加新图层
- clearAllLayersFunction: 清除所有图层
- diffMakerInfo: 点位信息差异对比
接下来,我将对代码进行详细解释,并针对一些关键部分进行说明。
由于代码较长,我将重点放在关键方法和逻辑上。</think>这个 Vue 组件是一个复杂的地图管理系统,集成了地图展示、点位管理、报警处理、视频监控等功能。下面我将详细解析核心功能并提供优化建议:
### 核心功能解析
1. **地图管理**
- 使用 `mapApi` 控制地图
- 图层管理(热区层、视频层、消防设备层)
- 点位状态管理(正常/报警/离线/故障)
2. **报警系统**
- 实时接收推送报警 (`pushFaultData`)
- 报警队列处理 (`evenQueueFunctionClass`)
- 报警点位循环闪烁 (`keyMakerLoopClass`)
3. **点位管理**
- 动态加载点位 (`waitAllMakeInfoDoneHandleClass`)
- 点位状态更新 (`diffMakerInfo`)
- 点位交互(点击/悬浮)
4. **组件通信**
- Vuex 状态管理
- 父子组件通信 (props/events)
- Mixins 复用逻辑
### 关键代码优化建议
```javascript
// 优化后的图层过滤逻辑
getMarkerLayers() {
mapApi.ConfigApi.getMarkerLayers().then(res => {
if (!res?.length) return;
const curMapMode = this.map.mapConfig.gisMode;
const targetLayers = ['hotareaLayer', 'videoLayer', ...this.fireControlLayerArr.map(i => i.layerCode)];
// 使用Map优化图层索引
const layerMap = new Map([
['fireControlLayer', 0],
['videoLayer', 1],
['hotareaLayer', 2]
]);
this.markerResourceList = res.filter(item =>
item.mapType < 3 &&
item.mapType !== -1 &&
targetLayers.includes(item.layerCode)
);
// 优化排序逻辑
this.markerResourceFlooterIcon = this.markerResourceList
.filter(item => ['fireControlLayer', 'videoLayer', 'hotareaLayer'].includes(item.layerCode))
.sort((a, b) => layerMap.get(a.layerCode) - layerMap.get(b.layerCode));
});
}
```
### 状态管理优化
```javascript
// 使用常量管理状态类型
const MAP_STATES = {
INITIALIZED: 0, // 地图初始化完成
LAYERS_ADDED: 2, // 图层添加完成
DATA_READY: 3, // 点位数据准备就绪
POLLING_UPDATE: 5, // 轮询更新
ORG_CHANGED: 6, // 组织切换
PUSH_UPDATE: 7 // 推送更新
};
// 修改状态设置方法
setMapStatePreparation(state) {
this.mapStatePreparation = {
time: Date.now(),
state,
stateName: Object.keys(MAP_STATES).find(k => MAP_STATES[k] === state)
};
// 添加状态处理
const stateHandlers = {
[MAP_STATES.INITIALIZED]: () => {
this.addNewLayer(this.allLayers, this.map);
this.keyMakerLoop.setMap(this.map);
this.evenQueueClass.setMap(this.map);
},
[MAP_STATES.DATA_READY]: () => {
this.shuntInfo();
}
};
stateHandlers[state]?.();
}
```
### 报警处理优化建议
```javascript
// 在evenQueueFunctionClass中添加防抖处理
class evenQueueFunctionClass {
constructor() {
this.alarmQueue = [];
this.processing = false;
this.debounceTimer = null;
}
evenQueueFunction(alarm) {
this.alarmQueue.push(alarm);
// 使用防抖优化高频报警
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => {
this.processQueue();
}, 300);
}
processQueue() {
if (this.processing || !this.alarmQueue.length) return;
this.processing = true;
const currentAlarm = this.alarmQueue.shift();
// 实际处理逻辑...
this.processing = false;
this.processQueue(); // 处理下一个
}
}
```
### 性能优化建议
1. **点位渲染优化**
```javascript
// 使用Web Worker处理大数据量点位计算
initWebWorker() {
this.pointWorker = new Worker('@/workers/pointProcessor.js');
this.pointWorker.onmessage = (e) => {
this.curBitmapMakerList = e.data;
this.setMapStatePreparation(3);
};
}
// 调用方式
this.pointWorker.postMessage({
resources: this.markerResourceList,
node: this.selectNode
});
```
2. **内存管理**
```javascript
beforeDestroy() {
// 清理事件监听
this.map.off('dblclick');
// 清理Worker
if (this.pointWorker) this.pointWorker.terminate();
// 释放图层资源
this.clearAllLayers(this.allMarkerLayers);
}
```
### 组件改进建议
```vue
<!-- 添加加载状态提示 -->
<template>
<div class="map-content">
<div v-if="loading" class="map-loading">
<i class="el-icon-loading"></i>
{{ $t('common.loading') }}
</div>
<!-- ...原有内容... -->
</div>
</template>
<script>
// 添加加载状态管理
data() {
return {
loading: true,
loadSteps: {
layers: false,
points: false,
events: false
}
}
},
watch: {
loadSteps: {
deep: true,
handler(steps) {
if (steps.layers && steps.points && steps.events) {
this.loading = false;
}
}
}
}
</script>
```
相关推荐

<template>
<view>
<view class="home-back" @click="backHome">
返回首页
</view>
<view class="">
<u-list>
<u-list-item class="yuyue" v-for="item in yuyueList" :key="item.id">
<u-cell>
<template #label>
<view class="shoufei-lable">
预约时间:{{fetchDate(item.createtime) }}
</view>
<view class="shoufei-lable">
预计到达时间:{{fetchDate(item.arriveTime)}}
</view>
<view class="shoufei-lable">
送货总量:{{item.sendAmonut}}
</view>
<view class="shoufei-lable">
供应商:{{item.sName}}
</view>
<view class="shoufei-lable">
车牌号:{{item.carNo}}
</view>
<view class="shoufei-lable">
货源地:{{item.huoyuandiName}}
</view>
<view>
<view class="lable-one">预约图片:</view>
<image class="yuyeu-img" v-for="itemImg in item.pictureUrl.slice(0, -1).split(',')"
:src=" 'http://' + itemImg" mode="">
</image>
</view>
</template>
</u-cell>
<u-cell>
<template #value>
<view class="yuyue-but">
<button class="but-one" type="default"
@click="changeDel(item.id, item.weightStatus)">删除</button>
<button class="but-two" type="default" @click="changeWeigh(item.id)">过磅二维码</button>
</view>
</template>
</u-cell>
</u-list-item>
</u-list>
</view>
<view class="yuyue-popup">
<u-popup :show="yuyueshow" mode="center">
<view class="" style="width: 66vw; margin: 0 auto;">
<uqrcode ref="uqrcode" canvas-id="qrcode" :value="QRvalue" :options="{ margin: 10 }" :size="size">
</uqrcode>
</view>
<u-button class="close-Qr" @click="yuyueshow = false">关闭过磅二维码</u-button>
</u-popup>
</view>
</view>
</template>
<script>
import dayjs from 'dayjs'
import api from '@/api/api.js';
export default {
data() {
return {
yuyueshow: false,
size: 240,
QRvalue: "",
pagenum: 1, //加载页
pageSize: '2',
isFinished: false,
status: 'loading',
yuyueList: [],
}
},
onLoad(option) {
this.fetchYuyueInfo()
},
onReachBottom() {
alert(111)
if (this.isFinished) return
// this.status = "nomore"
this.pagenum = this.pagenum + 1
this.fetchYuyueInfo()
},
methods: {
fetchDate(times) {
return dayjs(times).format('YYYY-MM-DD')
},
async fetchYuyueInfo() {
const data = await api.getYuyueInfo({
iDisplayStart: this.pagenum,
iDisplayLength: this.pageSize
})
console.log(data);
if (this.pagenum === 1) {
this.yuyueList = data.data
// this.status = "nomore"
console.log(this.pagenum);
} else {
this.yuyueList = [...this.yuyueList, ...data.data]
}
console.log(this.yuyueList.length)
console.log(data.total)
if (this.yuyueList.length >= data.total) {
this.isFinished = true
}
console.log(this.pagenum, this.yuyueList);
},
changeDel(delid, statu) {
console.log("删除");
if (statu === 0) {
uni.showModal({
title: '提示',
content: '是否删除此条信息',
success: async (res) => {
if (res.confirm) {
const data = await api.getYuyueInfoDel({
Id: delid
})
uni.$u.toast(data.message)
this.fetchYuyueInfo()
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
} else {
uni.$u.toast("此条数据不可删除!")
}
},
changeWeigh(Id) {
this.QRvalue = ${Id};
this.yuyueshow = true
},
backHome() {
uni.reLaunch({
url: '/pages/index/index'
});
},
}
}
</script>
<style lang="scss" scoped>
.home-back {
width: 230rpx;
height: 60rpx;
margin: 5rpx 40rpx;
text-align: center;
line-height: 60rpx;
border-radius: 50px;
font-weight: bold;
color: #66cc1c;
background: #fff;
}
.yuyue {
width: 95vw;
margin: 10rpx auto;
border-radius: 8rpx;
background: #fff;
.shoufei-lable {
display: flex;
justify-content: space-evenly;
align-items: center;
margin: 10rpx 0;
font-size: 32rpx;
color: #82848a;
.lable-one {
flex: 1;
}
.lable-two {
flex: 1;
}
}
.yuyue-but {
display: flex;
justify-content: center;
align-items: center;
.but-one {
width: 130rpx;
height: 75rpx;
line-height: 75rpx;
font-size: 30rpx;
color: #fff;
margin-right: 20rpx;
background: #f56c6c;
}
.but-two {
width: 240rpx;
height: 75rpx;
line-height: 75rpx;
font-size: 35rpx;
color: #fff;
background: #66cccc;
}
}
.yuyue-popup {
width: 550rpx;
height: 550rpx;
border-radius: 10rpx;
}
.yuyeu-img {
width: 305rpx;
height: 230rpx;
margin: 10rpx auto;
margin-right: 18rpx;
}
}
:v-deep .uni-file-picker__container[data-v-bdfc07e0] {
width: 240rpx;
}
.close-Qr {
box-sizing: border-box;
margin: 20rpx;
width: 66vw;
background: #66cccc;
color: #fff;
}
</style> 以上代码onReachBottom() 只执行一次

// pages/bancai/bancai.js
const app = getApp();
Page({
data: {
bancais: [],
filteredBancais: [],
searchText: '',
sortState: {
column: null,
direction: 'asc'
},
currentBancai: null,
currentKucun: null,
showDetailModal: false,
showEditModal: false,
stockInput: 0,
noteInput: '',
viewMode: 'orders',
relatedOrders: [],
relatedProducts: []
},
onLoad: function(options) {
if (!app.globalData.dataManager) {
// 如果数据管理器未初始化,等待初始化完成
const checkDataManager = () => {
if (app.globalData.dataManager) {
this.loadBancaiData();
} else {
setTimeout(checkDataManager, 100);
}
};
checkDataManager();
return;
}
this.loadBancaiData();
},
onShow: function() {
if (app.globalData.dataManager) {
this.loadBancaiData();
}
},
/**
* 加载板材数据并合并库存信息
* 将全局数据中的板材列表与库存数据进行关联,为每个板材对象添加库存数量和库存ID字段
* 结果会同时更新到页面的bancais和filteredBancais数据中
*/
loadBancaiData: function() {
const dataManager = app.globalData.dataManager;
const bancaisWithStock = dataManager.data.bancais.map(bancai => {
const kucun = dataManager.data.kucuns.find(k => k.bancai && k.bancai.id === bancai.id);
return {
...bancai,
stock: kucun ? kucun.shuliang : 0,
kucunId: kucun ? kucun.id : null
};
});
console.log(bancaisWithStock)
this.setData({
bancais: bancaisWithStock,
filteredBancais: bancaisWithStock
});
},
/**
* 处理搜索输入事件
* @param {Object} e - 事件对象,包含输入值(e.detail.value)
* @description 将搜索文本转为小写并更新到data,然后触发板材筛选
*/
onSearch: function(e) {
this.setData({ searchText: e.detail.value.toLowerCase() });
this.filterBancais();
},
/**
* 确认搜索 - 触发板材筛选操作
*/
confirmSearch: function() {
this.filterBancais();
},
/**
* 过滤并排序板材数据
* 根据搜索文本筛选板材列表,并按指定列和方向排序
* @function filterBancais
* @description
* - 当有搜索文本时,会匹配板材的材质、木皮1、木皮2、厚度和库存信息
* - 无搜索文本时返回所有板材
* - 最后调用sortBancais方法进行排序
* @returns {void} 通过setData更新filteredBancais数据
*/
filterBancais: function() {
const { bancais, searchText, sortState } = this.data;
const filteredBancais = searchText ? bancais.filter(b => {
const searchStr = ${b.caizhi?.name || ''} ${b.mupi1?.name || ''} ${b.mupi2?.name || ''} ${b.houdu} ${b.stock}.toLowerCase();
return searchStr.includes(searchText.toLowerCase());
}) : bancais;
const sortedBancais = this.sortBancais(filteredBancais, sortState.column, sortState.direction);
this.setData({ filteredBancais: sortedBancais });
},
/**
* 对板材数组进行排序
* @param {Array} bancais - 要排序的板材数组
* @param {string} column - 排序字段(id/caizhi/mupi1/mupi2/houdu/stock)
* @param {string} direction - 排序方向(asc/desc)
* @returns {Array} 排序后的新数组
*/
sortBancais: function(bancais, column, direction) {
return [...bancais].sort((a, b) => {
let valA, valB;
switch(column) {
case 'id': valA = a.id; valB = b.id; break;
case 'caizhi': valA = a.caizhi?.name || ''; valB = b.caizhi?.name || ''; break;
case 'mupi1': valA = a.mupi1?.name || ''; valB = b.mupi1?.name || ''; break;
case 'mupi2': valA = a.mupi2?.name || ''; valB = b.mupi2?.name || ''; break;
case 'houdu': valA = parseFloat(a.houdu); valB = parseFloat(b.houdu); break;
case 'stock': valA = a.stock; valB = b.stock; break;
/**
* 处理排序点击事件
* @param {Object} e - 事件对象
* @param {string} e.currentTarget.dataset.column - 点击列的标识
* @description 根据点击的列切换排序状态(升序/降序),并触发数据过滤
*/
default: return 0;
}
const comparison = typeof valA === 'string' ? valA.localeCompare(valB) : valA - valB;
return direction === 'asc' ? comparison : -comparison;
});
},
/**
* 处理排序点击事件
* @param {Object} e - 事件对象
* @param {string} e.currentTarget.dataset.column - 当前点击列的标识
* @description 根据点击的列切换排序状态(升序/降序),并触发数据过滤
*/
onSortTap: function(e) {
const column = e.currentTarget.dataset.column;
const { sortState } = this.data;
if (sortState.column === column) {
sortState.direction = sortState.direction === 'asc' ? 'desc' : 'asc';
} else {
sortState.column = column;
sortState.direction = 'asc';
}
this.setData({ sortState });
this.filterBancais();
},
onEditTap: function(e) {
const bancaiId = e.currentTarget.dataset.id;
const bancai = this.data.bancais.find(b => b.id === bancaiId);
const dataManager = app.globalData.dataManager;
const kucun = dataManager.data.kucuns.find(k => k.bancai && k.bancai.id === bancaiId);
if (bancai && kucun) {
this.setData({
currentBancai: bancai,
currentKucun: kucun,
stockInput: kucun.shuliang,
noteInput: '',
showEditModal: true
});
} else {
wx.showToast({ title: '找不到板材或库存记录', icon: 'none' });
}
},
saveStock: function() {
const { currentBancai, currentKucun, stockInput, noteInput } = this.data;
const dataManager = app.globalData.dataManager;
if (!currentBancai || !currentKucun) {
wx.showToast({ title: '无效的板材或库存记录', icon: 'none' });
return;
}
const newStock = parseInt(stockInput) || 0;
const note = noteInput.trim();
const oldStock = currentKucun.shuliang;
const changeAmount = newStock - oldStock;
if (changeAmount === 0) {
wx.showToast({ title: '库存数量未变化', icon: 'none' });
return;
}
dataManager.updateEntity('kucun', { id: currentKucun.id, shuliang: newStock })
.then(() => {
const jinhuoData = {
shuliang: changeAmount,
date: new Date().toISOString(),
user: { id: wx.getStorageSync("userId") },
text: note || 手动调整库存: ${oldStock} → ${newStock},
theTypeOfOperation: 3,
kucun: { id: currentKucun.id }
};
return dataManager.addEntity('jinhuo', jinhuoData);
})
.then(() => {
this.setData({ showEditModal: false });
this.loadBancaiData();
wx.showToast({ title: '库存更新成功', icon: 'success' });
})
.catch(error => {
console.error('库存更新失败:', error);
wx.showToast({ title: error.message || '库存更新失败', icon: 'none' });
});
},
onDetailTap: function(e) {
const bancaiId = e.currentTarget.dataset.id;
const bancai = this.data.bancais.find(b => b.id === bancaiId);
const dataManager = app.globalData.dataManager;
if (bancai) {
const kucun = dataManager.data.kucuns.find(k => k.bancai && k.bancai.id === bancai.id);
const relatedOrders = this.getRelatedOrders(bancai.id);
const relatedProducts = this.getRelatedProducts(bancai.id);
this.setData({
currentBancai: bancai,
currentKucun: kucun,
relatedOrders,
relatedProducts,
viewMode: 'orders',
showDetailModal: true
});
}
},
getRelatedOrders: function(bancaiId) {
const dataManager = app.globalData.dataManager;
const orderMap = new Map();
dataManager.data.dingdan_bancais.forEach(db => {
if (db.bancai && db.bancai.id === bancaiId && db.dingdan) {
const order = db.dingdan;
const key = order.id;
if (!orderMap.has(key)) {
orderMap.set(key, {
id: order.id,
number: order.number,
xiadan: order.xiadan,
jiaohuo: order.jiaohuo,
products: new Set(),
quantity: 0,
components: new Set()
});
}
const entry = orderMap.get(key);
entry.quantity += db.shuliang;
if (db.chanpin && db.chanpin.bianhao) entry.products.add(db.chanpin.bianhao);
if (db.zujian && db.zujian.name) entry.components.add(db.zujian.name);
}
});
return Array.from(orderMap.values()).map(entry => ({
...entry,
products: Array.from(entry.products).join(', '),
components: Array.from(entry.components).join(', '),
xiadanFormatted: entry.xiadan ? new Date(entry.xiadan).toLocaleDateString() : '无日期',
jiaohuoFormatted: entry.jiaohuo ? new Date(entry.jiaohuo).toLocaleDateString() : '无日期'
}));
},
getRelatedProducts: function(bancaiId) {
const dataManager = app.globalData.dataManager;
const products = [];
dataManager.data.chanpin_zujians.forEach(cz => {
if (cz.bancai && cz.bancai.id === bancaiId && cz.chanpin && cz.zujian) {
let productEntry = products.find(p => p.product.id === cz.chanpin.id);
if (!productEntry) {
productEntry = { product: cz.chanpin, components: [] };
products.push(productEntry);
}
if (!productEntry.components.some(c => c.id === cz.zujian.id)) {
productEntry.components.push(cz.zujian);
}
}
});
dataManager.data.dingdan_bancais.forEach(db => {
if (db.bancai && db.bancai.id === bancaiId && db.chanpin && !products.some(p => p.product.id === db.chanpin.id)) {
products.push({ product: db.chanpin, components: [] });
}
});
products.forEach(item => {
if (item.components && item.components.length > 0) {
const componentNames = [];
for (let i = 0; i < item.components.length; i++) {
if (item.components[i] && item.components[i].name) {
componentNames.push(item.components[i].name);
}
}
item.componentsText = componentNames.join(', ');
} else {
item.componentsText = '';
}
});
return products;
},
onStockInput: function(e) {
this.setData({ stockInput: e.detail.value });
},
onNoteInput: function(e) {
this.setData({ noteInput: e.detail.value });
},
closeEditModal: function() {
this.setData({ showEditModal: false });
},
closeDetailModal: function() {
this.setData({ showDetailModal: false });
},
toggleViewMode: function() {
this.setData({ viewMode: this.data.viewMode === 'orders' ? 'products' : 'orders' });
},
onDeleteTap: function(e) {
const bancaiId = e.currentTarget.dataset.id;
const bancai = this.data.bancais.find(b => b.id === bancaiId);
if (!bancai) {
wx.showToast({ title: '找不到板材记录', icon: 'none' });
return;
}
wx.showModal({
title: '确认删除',
content: 确定要删除这个板材吗?\n材质: ${bancai.caizhi?.name || ''}\n厚度: ${bancai.houdu}mm,
success: (res) => {
if (res.confirm) {
const dataManager = app.globalData.dataManager;
const relatedOrders = this.getRelatedOrders(bancaiId);
const relatedProducts = this.getRelatedProducts(bancaiId);
if (relatedOrders.length > 0 || relatedProducts.length > 0) {
wx.showModal({
title: '无法删除',
content: 该板材有${relatedOrders.length}个关联订单和${relatedProducts.length}个关联产品,无法删除。,
showCancel: false
});
return;
}
const kucun = dataManager.data.kucuns.find(k => k.bancai && k.bancai.id === bancaiId);
if (kucun) {
dataManager.deleteEntity('kucun', kucun.id)
.then(() => dataManager.deleteEntity('bancai', bancaiId))
.then(() => {
this.loadBancaiData();
wx.showToast({ title: '删除成功', icon: 'success' });
})
.catch(error => {
console.error('删除失败:', error);
wx.showToast({ title: error.message || '删除失败', icon: 'none' });
});
} else {
dataManager.deleteEntity('bancai', bancaiId)
.then(() => {
this.loadBancaiData();
wx.showToast({ title: '删除成功', icon: 'success' });
})
.catch(error => {
console.error('删除失败:', error);
wx.showToast({ title: error.message || '删除失败', icon: 'none' });
});
}
}
}
});
},
onPullDownRefresh: function() {
if (app.globalData.dataManager) {
app.globalData.dataManager.syncData()
.then(() => {
this.loadBancaiData();
wx.stopPullDownRefresh();
})
.catch(error => {
console.error('同步数据失败:', error);
this.loadBancaiData();
wx.stopPullDownRefresh();
});
} else {
wx.stopPullDownRefresh();
}
}
});---------------------
<view class="container">
<view class="header">
<view class="search-box">
<input class="search-input" placeholder="搜索板材..." bindinput="onSearch" value="{{searchText}}" confirm-type="search" bindconfirm="confirmSearch" />
<button class="search-btn" bindtap="confirmSearch">搜索</button>
</view>
</view>
<view class="table-container">
<view class="table-header">
<view class="th" data-column="caizhi" bindtap="onSortTap">
材质
<text wx:if="{{sortState.column === 'caizhi'}}" class="sort-indicator">{{sortState.direction === 'asc' ? '↑' : '↓'}}</text>
</view>
<view class="th" data-column="mupi1" bindtap="onSortTap">
木皮1
<text wx:if="{{sortState.column === 'mupi1'}}" class="sort-indicator">{{sortState.direction === 'asc' ? '↑' : '↓'}}</text>
</view>
<view class="th" data-column="mupi2" bindtap="onSortTap">
木皮2
<text wx:if="{{sortState.column === 'mupi2'}}" class="sort-indicator">{{sortState.direction === 'asc' ? '↑' : '↓'}}</text>
</view>
<view class="th" data-column="houdu" bindtap="onSortTap">
厚度
<text wx:if="{{sortState.column === 'houdu'}}" class="sort-indicator">{{sortState.direction === 'asc' ? '↑' : '↓'}}</text>
</view>
<view class="th" data-column="stock" bindtap="onSortTap">
库存
<text wx:if="{{sortState.column === 'stock'}}" class="sort-indicator">{{sortState.direction === 'asc' ? '↑' : '↓'}}</text>
</view>
<view class="th">操作</view>
</view>
<scroll-view scroll-y="true" class="table-body">
<block wx:if="{{filteredBancais.length > 0}}">
<view class="tr" wx:for="{{filteredBancais}}" wx:key="id">
<view class="td">{{item.caizhi.name || ''}}</view>
<view class="td">{{item.mupi1 ? (item.mupi1.name + (item.mupi1.you ? '(油)' : '')) : ''}}</view>
<view class="td">{{item.mupi2 ? (item.mupi2.name + (item.mupi2.you ? '(油)' : '')) : ''}}</view>
<view class="td">{{item.houdu}}mm</view>
<view class="td">{{item.stock}}</view>
<view class="td actions">
<button class="btn btn-info" bindtap="onDetailTap" data-id="{{item.id}}">详情</button>
<button class="btn btn-warning" bindtap="onEditTap" data-id="{{item.id}}">编辑</button>
<button class="btn btn-danger" bindtap="onDeleteTap" data-id="{{item.id}}">删除</button>
</view>
</view>
</block>
<view wx:else class="empty-tip">暂无板材数据</view>
</scroll-view>
</view>
<view class="modal" wx:if="{{showEditModal}}">
<view class="modal-mask" bindtap="closeEditModal"></view>
<view class="modal-content">
<view class="modal-header">
<text class="modal-title">编辑板材库存</text>
<text class="modal-close" bindtap="closeEditModal">×</text>
</view>
<view class="modal-body">
<view class="form-item">
<text class="label">材质:</text>
<text class="value">{{currentBancai.caizhi.name || ''}}</text>
</view>
<view class="form-item">
<text class="label">木皮1:</text>
<text class="value">{{currentBancai.mupi1 ? (currentBancai.mupi1.name + (currentBancai.mupi1.you ? '(油)' : '')) : ''}}</text>
</view>
<view class="form-item">
<text class="label">木皮2:</text>
<text class="value">{{currentBancai.mupi2 ? (currentBancai.mupi2.name + (currentBancai.mupi2.you ? '(油)' : '')) : ''}}</text>
</view>
<view class="form-item">
<text class="label">厚度:</text>
<text class="value">{{currentBancai.houdu}}mm</text>
</view>
<view class="form-item">
<text class="label">库存数量:</text>
<input class="input" type="number" value="{{stockInput}}" bindinput="onStockInput" />
</view>
<view class="form-item">
<text class="label">备注:</text>
<textarea class="textarea" value="{{noteInput}}" bindinput="onNoteInput" placeholder="输入库存调整原因"></textarea>
</view>
</view>
<view class="modal-footer">
<button class="btn btn-secondary" bindtap="closeEditModal">取消</button>
<button class="btn btn-primary" bindtap="saveStock">保存</button>
</view>
</view>
</view>
<view class="modal" wx:if="{{showDetailModal}}">
<view class="modal-mask" bindtap="closeDetailModal"></view>
<view class="modal-content detail-modal">
<view class="modal-header">
<text class="modal-title">板材详情</text>
<text class="modal-close" bindtap="closeDetailModal">×</text>
</view>
<view class="modal-body">
<view class="detail-section">
<view class="detail-item">
<text class="label">ID:</text>
<text class="value">{{currentBancai.id}}</text>
</view>
<view class="detail-item">
<text class="label">材质:</text>
<text class="value">{{currentBancai.caizhi.name || '无'}}</text>
</view>
<view class="detail-item">
<text class="label">木皮1:</text>
<text class="value">{{currentBancai.mupi1 ? (currentBancai.mupi1.name + (currentBancai.mupi1.you ? '(油)' : '')) : '无'}}</text>
</view>
<view class="detail-item">
<text class="label">木皮2:</text>
<text class="value">{{currentBancai.mupi2 ? (currentBancai.mupi2.name + (currentBancai.mupi2.you ? '(油)' : '')) : '无'}}</text>
</view>
<view class="detail-item">
<text class="label">厚度:</text>
<text class="value">{{currentBancai.houdu}}mm</text>
</view>
<view class="detail-item">
<text class="label">库存:</text>
<text class="value">{{currentKucun ? currentKucun.shuliang : 0}}</text>
</view>
</view>
<view class="view-toggle">
<view class="view-title">
{{viewMode === 'orders' ? '相关订单' : '相关产品'}}
({{viewMode === 'orders' ? relatedOrders.length : relatedProducts.length}})
</view>
<button class="btn btn-toggle" bindtap="toggleViewMode">
查看{{viewMode === 'orders' ? '相关产品' : '相关订单'}}
</button>
</view>
<view class="view-container" wx:if="{{viewMode === 'orders'}}">
<view class="sub-table" wx:if="{{relatedOrders.length > 0}}">
<view class="sub-table-header">
<view class="sub-th">订单编号</view>
<view class="sub-th">下单日期</view>
<view class="sub-th">产品</view>
<view class="sub-th">数量</view>
<view class="sub-th">交货日期</view>
</view>
<scroll-view scroll-y="true" class="sub-table-body">
<view class="sub-tr" wx:for="{{relatedOrders}}" wx:key="id">
<view class="sub-td">{{item.number || '无编号'}}</view>
<view class="sub-td">{{item.xiadanFormatted}}</view>
<view class="sub-td">{{item.products || '无产品'}}</view>
<view class="sub-td">{{item.quantity}}</view>
<view class="sub-td">{{item.jiaohuoFormatted}}</view>
</view>
</scroll-view>
</view>
<view wx:else class="empty-tip">暂无关联订单</view>
</view>
<view class="view-container" wx:if="{{viewMode === 'products'}}">
<view class="sub-table" wx:if="{{relatedProducts.length > 0}}">
<view class="sub-table-header">
<view class="sub-th">产品编号</view>
<view class="sub-th">产品名称</view>
<view class="sub-th">组件</view>
</view>
<scroll-view scroll-y="true" class="sub-table-body">
<view class="sub-tr" wx:for="{{relatedProducts}}" wx:key="index">
<view class="sub-td">{{item.product.bianhao || '无编号'}}</view>
<view class="sub-td">{{item.product.name || '无名称'}}</view>
<view class="sub-td">
{{item.componentsText || '无组件信息'}}
</view>
</view>
</scroll-view>
</view>
<view wx:else class="empty-tip">暂无关联产品</view>
</view>
</view>
<view class="modal-footer">
<button class="btn btn-primary" bindtap="closeDetailModal">关闭</button>
</view>
</view>
</view>
</view>---------------- console.log(bancaisWithStock)输出有35个数据,但页面一行数据没有

<template>
<myModal :params="{ title: '编辑流量计' }" :visible="visible" @submit="submit" @cancel="handleCancel">
<template v-slot:header>
</template>
<template v-slot:body>
<a-form-model
ref="baseInfoForm"
:model="formData"
:rules="rules"
:label-col="{ span: 8 }"
:wrapper-col="{ span: 16 }"
>
{{ $t('基础信息') }}
<a-row>
<a-col :span="12">
<a-form-model-item :label="$t('探测器名称')" prop="detectorName">
<a-input v-model="formData.detectorName" disabled />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('探测器编号')" prop="uniqueCode">
<a-input v-model="formData.uniqueCode" disabled />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('流量计编号')" prop="meterCode">
<a-input v-model="formData.meterCode" disabled />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('接入时间')" prop="rate">
<a-date-picker
v-model="formData.rate"
show-time
format="YYYY-MM-DD HH:mm:ss"
:placeholder="$t('请选择接入时间')"
/>
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('归属')" prop="belonging">
<a-input v-model="formData.belonging" disabled />
</a-form-model-item>
</a-col>
</a-row>
{{ $t('子流量计列表') }}
<a-button class="mgr10" type="primary" @click="onAdd">{{ $t('新增') }}</a-button>
<a-popconfirm
:title="$t('是否确认删除?')"
:ok-text="$t('确定')"
:cancel-text="$t('取消')"
:visible="popconfirmVisible"
@visibleChange="popconfirmVisibleChange"
@confirm="onDeleteAll"
>
<a-button>{{ $t('删除') }}</a-button>
</a-popconfirm>
<a-table
:dataSource="tableData"
:rowSelection="rowSelection"
rowKey="id"
:columns="columns"
:pagination="false"
size="small"
>
<template slot="meterCode" slot-scope="text, record, index">
<template v-if="text">{{ text }}</template>
<template v-else>
<a-select
v-model="tableData[index].meterCode"
:filterOption="filterOption"
@change="value => changeMemterCode(value, index)"
:placeholder="$t('请选择')"
showSearch
:allowClear="false"
>
<a-select-option
v-for="item in disabledOptions"
:key="item.id"
:value="item.meterCode"
:title="item.meterCode"
:disabled="item.disabled"
>
{{ item.meterCode }}
</a-select-option>
</a-select>
</template>
</template>
<template slot="action" slot-scope="text, record">
<a-popconfirm
placement="topRight"
:title="$t('是否确认删除?')"
:ok-text="$t('确定')"
:cancel-text="$t('取消')"
@confirm="onDelete(record)"
>
</a-popconfirm>
</template>
</a-table>
</a-form-model>
</template>
</myModal>
</template>
<script>
import factory from '../factory';
import myModal from '@/components/scfComponents/modalComponents/modal.vue';
export default {
components: { myModal },
data() {
return {
visible: false,
formData: {},
rules: {
taskName: [
{ required: true, message: '请输入任务名称', trigger: 'blur' },
// { pattern: reg.name, message: this.$t('仅允许输入汉字、字母、数字与_-.@字符') },
],
},
columns: [
{
title: this.$t('序号'),
key: 'index',
dataIndex: 'index',
customRender: (text, record, index) => ${index + 1},
},
{
title: this.$t('子电表编号'),
dataIndex: 'meterCode',
key: 'meterCode',
scopedSlots: { customRender: 'meterCode' },
},
{
title: this.$t('操作'),
key: 'action',
width: 150,
dataIndex: 'action',
scopedSlots: { customRender: 'action' },
},
],
popconfirmVisible: false,
meterOptions: [],
selectedRowKeys: [],
selectedRows: [],
tableData: [],
};
},
computed: {
disabledOptions() {
const usedCodes = this.tableData.map(item => item.meterCode).filter(code => code);
return this.meterOptions.map(option => ({
...option,
disabled: usedCodes.includes(option.meterCode),
}));
},
rowSelection() {
return {
selectedRowKeys: this.selectedRowKeys,
onChange: (selectedRowKeys, selectedRows) => {
this.selectedRowKeys = selectedRowKeys;
this.selectedRows = selectedRows;
},
};
},
},
methods: {
// 获取子电表列表
getChildMeterList(detectorCode) {
let params = {
detectorCodes: [detectorCode],
page: 1,
pageSize: 99999,
};
factory.getChildMeterList(params).then(res => {
if (res.success) {
this.meterOptions = res.data.pageData || [];
}
});
},
showModal(record) {
this.getChildMeterList(record.detectorCode);
this.visible = true;
},
filterOption(input, option) {
return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
},
changeMemterCode(value, index) {
const selectedOption = this.meterOptions.find(el => el.meterCode === value);
if (selectedOption) {
this.$set(this.tableData, index, {
...this.tableData[index],
detectorCode: selectedOption.detectorCode,
meterCode: value,
});
}
// let checkOption = this.meterOptions.find(el => el.meterCode === value);
// this.tableData.forEach(item => {
// if (item.meterCode === checkOption.meterCode) {
// item.detectorCode = checkOption.detectorCode;
// }
// });
// let selectedItems = this.tableData.map(item => item.meterCode).filter(el => el !== null && el !== '');
// this.meterOptions.forEach(el => {
// if (selectedItems.includes(el.meterCode)) {
// el.disabled = true;
// }
// });
},
// 批量删除提示框
popconfirmVisibleChange(visible) {
if (visible && !this.selectedRowKeys.length) {
this.popconfirmVisible = false;
this.$message.destroy();
this.$message.warning(this.$t('请选择要删除的信息'));
} else {
this.popconfirmVisible = visible;
}
},
// 新增
onAdd() {
let isNull = this.tableData.filter(e => e.meterCode === null || e.meterCode === '');
if (isNull.length) {
this.$message.destroy();
return this.$message.warning(this.$t('请选择子电表编号'));
}
this.tableData.push({ id: Math.random().toString().split('.')[1], meterCode: null });
},
onDeleteAll() {
if (this.selectedRows.length === 0) {
this.$message.destroy();
return this.$message.warning(this.$t('请选择子电表'));
}
this.tableData = this.tableData.filter(item => !this.selectedRowKeys.includes(item.id));
// 清空选中状态
this.selectedRowKeys = [];
this.selectedRows = [];
// let codes = this.selectedRows.map(item => item.id);
// this.tableData = this.tableData.filter(el => !codes.includes(el.id));
// let selectedItems = this.selectedRows.map(item => item.meterCode).filter(el => el !== null && el !== '');
// this.meterOptions.forEach(el => {
// if (selectedItems.includes(el.meterCode)) {
// el.disabled = false;
// }
// });
},
// 单个删除
onDelete(record) {
this.tableData = this.tableData.filter(item => item.id !== record.id);
// this.tableData = this.tableData.filter(item => item.id !== record.id);
// if (record.meterCode) {
// this.meterOptions.forEach(el => {
// if (record.meterCode.indexOf(el.meterCode) !== -1) {
// el.disabled = false;
// }
// });
// }
},
submit() {
this.visible = false;
},
handleCancel() {
this.visible = false;
},
},
};
</script>
<style lang="less" scoped>
.edit-flow-meter-box {
width: 100%;
height: 100%;
.table-title-box {
width: 100%;
display: flex;
margin-bottom: 10px;
align-items: center;
justify-content: space-between;
}
}
</style> 代码评审

能不能在代码中帮我增加动态申请蓝牙权限的相关代码,在打开蓝牙适配器的时候,增加蓝牙权限的动态申请功能;这是源代码<template>
<view>
<view class="uni-list">
<canvas :id="canvasId" :canvas-id="canvasId" type="2d"
:style="{ width: labelWidth + 'px', height: labelHeight + 'px' }"
style="position: fixed; left: -999999rpx; top: -999999rpx" />
<view class="uni-list-cell">
<view class="uni-list-cell-left">打印机:</view>
<view class="uni-list-cell-db">
<view class="uni-input">{{ deviceList[deviceIndex].name }}</view>
</view>
</view>
</view>
<view class="uni-padding-wrap uni-common-mt">
<button type="primary" @click="startDiscovery">开始搜索打印机</button>
<button type="primary" @click="stopDiscovery">停止搜索打印机</button>
<button type="primary" @click="openPrinter">打开打印机</button>
<button type="primary" @click="closePrinter">关闭打印机</button>
<button type="primary" plain="true" @click="onPrintTest">打印测试</button>
</view>
<view style="text-align: center; padding: 10px">
<view style="margin: 10px; border: solid lightgray 1px">
<image v-for="item in previewList" :src="item.value" :key="item.key" class="image" mode="widthFix"
style="margin: 10rpx; border: dashed lightgray 1px" />
</view>
</view>
</view>
</template>
<script>
import {
LPAPIFactory,
LPA_Result,
LPAUtils
} from "@/uni_modules/dothan-lpapi-ble/js_sdk/index.js";
//
export default {
data() {
return {
canvasId: "lpapi-ble-uni1",
labelWidth: 960,
labelHeight: 960,
deviceList: [{
name: "未检测到打印机"
}],
deviceIndex: 0,
isAppPlus: false,
isWeiXin: false,
isLark: false,
isAlipay: false,
isDingTalk: false,
/**
* 图片预览列表
* @type {{value: string; key: string;}[]}
***/
previewList: [],
threshold: 128,
};
},
onLoad() {
consol

<template>
<myModal :params="{ title: '编辑流量计' }" :visible="visible" @submit="submit" @cancel="handleCancel">
<template v-slot:header>
</template>
<template v-slot:body>
<a-form-model
ref="baseInfoForm"
:model="formData"
:rules="rules"
:label-col="{ span: 8 }"
:wrapper-col="{ span: 16 }"
>
{{ $t('基础信息') }}
<a-row>
<a-col :span="12">
<a-form-model-item :label="$t('探测器名称')" prop="detectorName">
<a-input v-model="formData.detectorName" disabled />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('探测器编号')" prop="uniqueCode">
<a-input v-model="formData.uniqueCode" disabled />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('流量计编号')" prop="meterCode">
<a-input v-model="formData.meterCode" disabled />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('接入时间')" prop="rate">
<a-input v-model.trim="formData.rate" :placeholder="$t('请输入')" :allowClear="false" />
</a-form-model-item>
</a-col>
<a-col :span="12">
<a-form-model-item :label="$t('归属')" prop="rate">
<a-input v-model="formData.uniqueCode" disabled />
</a-form-model-item>
</a-col>
</a-row>
{{ $t('子流量计列表') }}
<a-button class="mgr10" type="primary" @click="onAdd">{{ $t('新增') }}</a-button>
<a-popconfirm
:title="$t('是否确认删除?')"
:ok-text="$t('确定')"
:cancel-text="$t('取消')"
:visible="popconfirmVisible"
@visibleChange="popconfirmVisibleChange"
@confirm="onDeleteAll"
>
<a-button>{{ $t('删除') }}</a-button>
</a-popconfirm>
<a-table
:dataSource="tableData"
:rowSelection="rowSelection"
rowKey="id"
:columns="columns"
:pagination="false"
size="small"
>
<template slot="meterCode" slot-scope="text, record, index">
<template v-if="text">{{ text }}</template>
<template v-else>
<a-select
v-model="tableData[index].meterCode"
:filterOption="filterOption"
@change="changeMemterCode"
:placeholder="$t('请选择')"
showSearch
:allowClear="false"
>
<a-select-option
v-for="item in meterOptions"
:key="item.id"
:value="item.meterCode"
:title="item.meterCode"
:disabled="item.disabled"
>
{{ item.meterCode }}
</a-select-option>
</a-select>
</template>
</template>
<template slot="action" slot-scope="text, record">
<a-popconfirm
placement="topRight"
:title="$t('是否确认删除?')"
:ok-text="$t('确定')"
:cancel-text="$t('取消')"
@confirm="onDelete(record)"
>
</a-popconfirm>
</template>
</a-table>
</a-form-model>
</template>
</myModal>
</template>
<script>
import factory from '../factory';
import myModal from '@/components/scfComponents/modalComponents/modal.vue';
export default {
components: { myModal },
data() {
return {
visible: false,
formData: {},
rules: {
taskName: [
{ required: true, message: '请输入任务名称', trigger: 'blur' },
// { pattern: reg.name, message: this.$t('仅允许输入汉字、字母、数字与_-.@字符') },
],
},
columns: [
{
title: this.$t('序号'),
key: 'index',
dataIndex: 'index',
customRender: (text, record, index) => ${index + 1},
},
{
title: this.$t('子电表编号'),
dataIndex: 'meterCode',
key: 'meterCode',
scopedSlots: { customRender: 'meterCode' },
},
{
title: this.$t('操作'),
key: 'action',
width: 150,
dataIndex: 'action',
scopedSlots: { customRender: 'action' },
},
],
popconfirmVisible: false,
meterOptions: [],
selectedRowKeys: [],
selectedRows: [],
tableData: [],
};
},
computed: {
rowSelection() {
return {
onChange: this.rowSelectionChange,
};
},
},
methods: {
// 获取子电表列表
getChildMeterList(detectorCode) {
let params = {
detectorCodes: [detectorCode],
page: 1,
pageSize: 99999,
};
factory.getChildMeterList(params).then(res => {
if (res.success) {
this.meterOptions = res.data.pageData.map(item => ({ ...item, disabled: false })) || [];
}
});
},
showModal() {
this.getChildMeterList(record.detectorCode);
this.visible = true;
},
filterOption(input, option) {
return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
},
changeMemterCode(value) {
let checkOption = this.meterOptions.find(el => el.meterCode === value);
this.tableData.forEach(item => {
if (item.meterCode === checkOption.meterCode) {
item.detectorCode = checkOption.detectorCode;
}
});
let selectedItems = this.tableData.map(item => item.meterCode).filter(el => el !== null && el !== '');
this.meterOptions.forEach(el => {
if (selectedItems.includes(el.meterCode)) {
el.disabled = true;
}
});
},
// 全选/单选
rowSelectionChange(selectedRowKeys, selectedRows) {
this.selectedRowKeys = selectedRowKeys;
this.selectedRows = selectedRows;
},
// 批量删除提示框
popconfirmVisibleChange(visible) {
if (visible && !this.selectedRowKeys.length) {
this.popconfirmVisible = false;
this.$message.destroy();
this.$message.warning(this.$t('请选择要删除的信息'));
} else {
this.popconfirmVisible = visible;
}
},
// 新增
onAdd() {
let isNull = this.tableData.filter(e => e.meterCode === null || e.meterCode === '');
if (isNull.length) return this.$message.warning(this.$t('请选择子电表编号'));
this.tableData.push({ id: Math.random().toString().split('.')[1], meterCode: null });
},
onDeleteAll() {
if (this.selectedRows.length === 0) {
return this.$message.warning(this.$t('请选择子电表'));
}
let codes = this.selectedRows.map(item => item.id);
this.tableData = this.tableData.filter(el => !codes.includes(el.id));
let selectedItems = this.selectedRows.map(item => item.meterCode).filter(el => el !== null && el !== '');
this.meterOptions.forEach(el => {
if (selectedItems.includes(el.meterCode)) {
el.disabled = false;
}
});
},
// 单个删除
onDelete(record) {
this.tableData = this.tableData.filter(item => item.id !== record.id);
if (record.meterCode) {
this.meterOptions.forEach(el => {
if (record.meterCode.indexOf(el.meterCode) !== -1) {
el.disabled = false;
}
});
}
},
submit() {
this.visible = false;
},
handleCancel() {
this.visible = false;
},
},
};
</script>
<style lang="less" scoped>
.edit-flow-meter-box {
width: 100%;
height: 100%;
.table-title-box {
width: 100%;
display: flex;
margin-bottom: 10px;
align-items: center;
justify-content: space-between;
}
}代码评审
</style>