新增mqtt文件,订阅设备消息
This commit is contained in:
@ -6,7 +6,7 @@ VITE_APP_ENV = 'development'
|
||||
|
||||
# 开发环境
|
||||
# VITE_APP_BASE_API = 'http://47.120.79.150/backend'
|
||||
VITE_APP_BASE_API = 'http://192.168.110.54:8000'
|
||||
VITE_APP_BASE_API = 'http://192.168.2.23:8000'
|
||||
# VITE_APP_BASE_API = 'http://localhost:8000'
|
||||
|
||||
|
||||
|
@ -37,6 +37,7 @@
|
||||
"jsencrypt": "3.3.2",
|
||||
"mitt": "^3.0.1",
|
||||
"nprogress": "0.2.0",
|
||||
"paho-mqtt": "^1.1.0",
|
||||
"pinia": "3.0.2",
|
||||
"qrcode-vue3": "^1.7.1",
|
||||
"screenfull": "6.0.2",
|
||||
|
265
src/utils/mqtt.ts
Normal file
265
src/utils/mqtt.ts
Normal file
@ -0,0 +1,265 @@
|
||||
import { ref, onUnmounted } from 'vue'; // 修复:导入必要的Vue API
|
||||
import * as Paho from 'paho-mqtt';
|
||||
|
||||
// MQTT消息类型定义
|
||||
export interface MqttMessage {
|
||||
topic: string;
|
||||
payload: string | ArrayBuffer;
|
||||
qos: number;
|
||||
retained: boolean;
|
||||
time: Date;
|
||||
}
|
||||
|
||||
// 订阅选项
|
||||
export interface SubscribeOptions {
|
||||
qos: 0 | 1 | 2;
|
||||
}
|
||||
|
||||
// MQTT配置信息
|
||||
const MQTT_CONFIG = {
|
||||
// 连接地址(添加协议类型)
|
||||
protocol: 'ws', // 关键:明确协议(ws或wss)
|
||||
host: '47.120.79.150',
|
||||
port: 9083,
|
||||
// 认证信息
|
||||
username: 'admin',
|
||||
password: '#YtvpSfCNG',
|
||||
// 客户端ID(添加时间戳确保唯一性)
|
||||
clientId: `vue3-mqtt-client-${Date.now()}-${Math.random().toString(36).substring(2, 10)}`,
|
||||
// 连接选项
|
||||
cleanSession: true,
|
||||
keepAliveInterval: 60,
|
||||
reconnect: true,
|
||||
};
|
||||
|
||||
// MQTT客户端组合式API
|
||||
export function useMqtt() {
|
||||
// 客户端实例
|
||||
let client: Paho.Client | null = null;
|
||||
|
||||
// 状态管理(修复:已导入ref)
|
||||
const connected = ref(false);
|
||||
const connecting = ref(false);
|
||||
const error = ref<Error | null>(null);
|
||||
const messages = ref<MqttMessage[]>([]);
|
||||
const subscribedTopics = ref<string[]>([]);
|
||||
|
||||
// 事件回调
|
||||
const connectCallbacks: (() => void)[] = [];
|
||||
const messageCallbacks: ((message: MqttMessage) => void)[] = [];
|
||||
const errorCallbacks: ((err: Error) => void)[] = [];
|
||||
const disconnectCallbacks: (() => void)[] = [];
|
||||
|
||||
// 修复:移除无用的p0参数,connect方法不接受回调(通过onConnect注册)
|
||||
const connect = () => {
|
||||
if (connected.value || connecting.value) return;
|
||||
connecting.value = true;
|
||||
error.value = null;
|
||||
|
||||
try {
|
||||
// 创建客户端实例(添加协议参数)
|
||||
client = new Paho.Client(
|
||||
MQTT_CONFIG.host,
|
||||
MQTT_CONFIG.port,
|
||||
MQTT_CONFIG.clientId
|
||||
);
|
||||
|
||||
// 设置连接选项
|
||||
const connectOptions: Paho.ConnectOptions = {
|
||||
userName: MQTT_CONFIG.username,
|
||||
password: MQTT_CONFIG.password,
|
||||
cleanSession: MQTT_CONFIG.cleanSession,
|
||||
keepAliveInterval: MQTT_CONFIG.keepAliveInterval,
|
||||
reconnect: MQTT_CONFIG.reconnect,
|
||||
|
||||
// 连接成功回调
|
||||
onSuccess: () => {
|
||||
console.log('MQTT连接成功');
|
||||
connected.value = true;
|
||||
connecting.value = false;
|
||||
connectCallbacks.forEach(cb => cb()); // 触发所有连接成功回调
|
||||
},
|
||||
|
||||
// 连接失败回调
|
||||
onFailure: (err) => {
|
||||
console.error('MQTT连接失败:', err);
|
||||
error.value = new Error(err.errorMessage || '连接失败');
|
||||
connected.value = false;
|
||||
connecting.value = false;
|
||||
errorCallbacks.forEach(cb => cb(error.value!));
|
||||
}
|
||||
};
|
||||
|
||||
// 设置客户端回调
|
||||
client.onConnectionLost = (responseObject) => {
|
||||
if (responseObject.errorCode !== 0) {
|
||||
console.error('连接丢失:', responseObject.errorMessage);
|
||||
error.value = new Error(responseObject.errorMessage || '连接丢失');
|
||||
errorCallbacks.forEach(cb => cb(error.value!));
|
||||
}
|
||||
|
||||
connected.value = false;
|
||||
connecting.value = false;
|
||||
disconnectCallbacks.forEach(cb => cb());
|
||||
};
|
||||
|
||||
// 消息接收回调
|
||||
client.onMessageArrived = (message) => {
|
||||
const newMessage: MqttMessage = {
|
||||
topic: message.destinationName,
|
||||
payload: message.payloadString || message.payloadBytes,
|
||||
qos: message.qos,
|
||||
retained: message.retained,
|
||||
time: new Date()
|
||||
};
|
||||
|
||||
messages.value.push(newMessage);
|
||||
messageCallbacks.forEach(cb => cb(newMessage));
|
||||
};
|
||||
|
||||
// 连接服务器
|
||||
client.connect(connectOptions);
|
||||
} catch (err) {
|
||||
console.error('MQTT连接异常:', err);
|
||||
error.value = err as Error;
|
||||
connected.value = false;
|
||||
connecting.value = false;
|
||||
errorCallbacks.forEach(cb => cb(error.value!));
|
||||
}
|
||||
};
|
||||
|
||||
// 断开连接
|
||||
const disconnect = () => {
|
||||
if (!client || !connected.value) return;
|
||||
|
||||
client.disconnect();
|
||||
client = null;
|
||||
connected.value = false;
|
||||
subscribedTopics.value = [];
|
||||
disconnectCallbacks.forEach(cb => cb());
|
||||
};
|
||||
|
||||
// 订阅主题
|
||||
const subscribe = (topic: string, options: SubscribeOptions): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!client || !connected.value) {
|
||||
reject(new Error('未连接到MQTT服务器'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (subscribedTopics.value.includes(topic)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
client.subscribe(topic, {
|
||||
qos: options.qos,
|
||||
onSuccess: () => {
|
||||
console.log(`订阅主题成功: ${topic}`);
|
||||
subscribedTopics.value.push(topic);
|
||||
resolve();
|
||||
},
|
||||
onFailure: (err) => {
|
||||
console.error(`订阅主题失败: ${topic}`, err);
|
||||
reject(new Error(err.errorMessage || `订阅主题 ${topic} 失败`));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// 取消订阅
|
||||
const unsubscribe = (topic: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!client || !connected.value) {
|
||||
reject(new Error('未连接到MQTT服务器'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!subscribedTopics.value.includes(topic)) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
client.unsubscribe(topic, {
|
||||
onSuccess: () => {
|
||||
console.log(`取消订阅主题成功: ${topic}`);
|
||||
subscribedTopics.value = subscribedTopics.value.filter(t => t !== topic);
|
||||
resolve();
|
||||
},
|
||||
onFailure: (err) => {
|
||||
console.error(`取消订阅主题失败: ${topic}`, err);
|
||||
reject(new Error(err.errorMessage || `取消订阅主题 ${topic} 失败`));
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// 发布消息
|
||||
const publish = (
|
||||
topic: string,
|
||||
payload: string | ArrayBuffer,
|
||||
options: { qos: 0 | 1 | 2; retained?: boolean }
|
||||
): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!client || !connected.value) {
|
||||
reject(new Error('未连接到MQTT服务器'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!topic) {
|
||||
reject(new Error('主题不能为空'));
|
||||
return;
|
||||
}
|
||||
|
||||
const message = new Paho.Message(
|
||||
typeof payload === 'string' ? payload : payload.toString()
|
||||
);
|
||||
|
||||
message.destinationName = topic;
|
||||
message.qos = options.qos;
|
||||
message.retained = options.retained ?? false;
|
||||
|
||||
client.send(message);
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
|
||||
// 事件注册
|
||||
const onConnect = (callback: () => void) => {
|
||||
connectCallbacks.push(callback);
|
||||
};
|
||||
|
||||
const onMessage = (callback: (message: MqttMessage) => void) => {
|
||||
messageCallbacks.push(callback);
|
||||
};
|
||||
|
||||
const onError = (callback: (err: Error) => void) => {
|
||||
errorCallbacks.push(callback);
|
||||
};
|
||||
|
||||
const onDisconnect = (callback: () => void) => {
|
||||
disconnectCallbacks.push(callback);
|
||||
};
|
||||
|
||||
// 组件卸载时断开连接
|
||||
onUnmounted(() => {
|
||||
disconnect();
|
||||
});
|
||||
|
||||
return {
|
||||
connected,
|
||||
connecting,
|
||||
error,
|
||||
messages,
|
||||
subscribedTopics,
|
||||
connect,
|
||||
disconnect,
|
||||
subscribe,
|
||||
unsubscribe,
|
||||
publish,
|
||||
onConnect,
|
||||
onMessage,
|
||||
onError,
|
||||
onDisconnect
|
||||
};
|
||||
}
|
@ -125,6 +125,7 @@
|
||||
</template>
|
||||
<script setup name="DeviceControl" lang="ts">
|
||||
const route = useRoute();
|
||||
import { useMqtt } from '@/utils/mqtt';
|
||||
import api from '@/api/controlCenter/controlPanel/index'
|
||||
import { DeviceDetail, LightMode } from '@/api/controlCenter/controlPanel/types';
|
||||
import { generateShortId, getDeviceStatus } from '@/utils/function';
|
||||
@ -147,7 +148,15 @@ const fullscreenLoading = ref(false)
|
||||
const forceAlarmLoading = ref(false) //强制报警
|
||||
const sendTextLoading = ref(false)
|
||||
const lightModesLoading = ref(false)
|
||||
|
||||
const {
|
||||
connected,
|
||||
connect,
|
||||
subscribe,
|
||||
onConnect,
|
||||
onError,
|
||||
onMessage,
|
||||
disconnect
|
||||
} = useMqtt();
|
||||
// 灯光模式数据(引用导入的图片)
|
||||
const lightModes = ref<LightMode[]>([
|
||||
{
|
||||
@ -244,6 +253,7 @@ const handleModeClick = async (modeId: string) => {
|
||||
typeName: deviceDetail.value.typeName,
|
||||
});
|
||||
if (res.code === 200) {
|
||||
ElMessage.closeAll();
|
||||
proxy?.$modal.msgSuccess(res.msg);
|
||||
setActiveLightMode(modeId);
|
||||
} else {
|
||||
@ -300,7 +310,7 @@ const getList = async () => {
|
||||
targetModeId = matchedMode.id;
|
||||
}
|
||||
setActiveLightMode(targetModeId);
|
||||
const laserStatus = res.data.laserModeStatus ?? 0;
|
||||
const laserStatus = res.data.laserLightMode;
|
||||
laserMode.value.active = laserStatus === 1;
|
||||
laserMode.value.switchStatus = laserStatus === 1;
|
||||
} catch (error) {
|
||||
@ -321,6 +331,7 @@ const handleLaserClick = async () => {
|
||||
instructValue: targetStatus ? 1 : 0
|
||||
});
|
||||
if (res.code === 200) {
|
||||
ElMessage.closeAll();
|
||||
proxy?.$modal.msgSuccess(res.msg);
|
||||
laserMode.value.active = targetStatus;
|
||||
laserMode.value.switchStatus = targetStatus;
|
||||
@ -496,9 +507,118 @@ const lookMap = (row: any) => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
getList();
|
||||
const getMainLightModeLabel = (mode: any) => {
|
||||
const modeMap = {
|
||||
0: 'close', // 0 → 关闭
|
||||
1: 'strong', // 1 → 强光
|
||||
2: 'weak', // 2 → 弱光
|
||||
3: 'strobe', // 3 → 爆闪
|
||||
4: 'flood' // 4 → 泛光
|
||||
}
|
||||
return modeMap[mode] || (console.log('未知的灯光模式:', mode), '未知');
|
||||
}
|
||||
// 处理设备消息
|
||||
const handleDeviceMessage = (msg: any) => {
|
||||
try {
|
||||
// 解析设备消息(假设格式为 { state: [类型, 模式值, 亮度, 续航...] })
|
||||
const payloadObj = JSON.parse(msg.payload.toString());
|
||||
const deviceState = payloadObj.state; // 设备状态数组
|
||||
if (!Array.isArray(deviceState)) {
|
||||
return;
|
||||
}
|
||||
// 用switch处理不同的消息类型(deviceState[0])
|
||||
switch (deviceState[0]) {
|
||||
case 1:
|
||||
// 类型1灯光主键
|
||||
const lightModeId = getMainLightModeLabel(deviceState[1]); // 获取模式ID(如'strong')
|
||||
const brightness = deviceState[2]; // 亮度值
|
||||
const batteryTime = deviceState[3]; // 续航时间
|
||||
console.log('灯光模式消息:', { 模式ID: lightModeId, 亮度: brightness, 续航: batteryTime });
|
||||
// 1. 同步灯光模式状态
|
||||
if (lightModeId !== 'unknown') {
|
||||
lightModes.value.forEach(mode => {
|
||||
const isActive = mode.id === lightModeId;
|
||||
mode.active = isActive;
|
||||
mode.switchStatus = isActive;
|
||||
});
|
||||
}
|
||||
// 2.亮度
|
||||
if (brightness !== undefined) {
|
||||
deviceDetail.value.lightBrightness = brightness.toString();
|
||||
}
|
||||
// 3.续航时间
|
||||
if (batteryTime !== undefined) {
|
||||
deviceDetail.value.batteryRemainingTime = batteryTime.toString();
|
||||
}
|
||||
break;
|
||||
case 12:
|
||||
// 灯光主键
|
||||
const lightModeIdA = getMainLightModeLabel(deviceState[1]); // 获取模式ID(如'strong')
|
||||
if (lightModeIdA !== 'unknown') {
|
||||
lightModes.value.forEach(mode => {
|
||||
const isActive = mode.id === lightModeIdA;
|
||||
mode.active = isActive;
|
||||
mode.switchStatus = isActive;
|
||||
});
|
||||
}
|
||||
// 激光
|
||||
const laserValue = deviceState[2];
|
||||
// 同步激光模式状态:1=开启(true),0=关闭(false)
|
||||
laserMode.value.active = laserValue === 1;
|
||||
laserMode.value.switchStatus = laserValue === 1;
|
||||
deviceDetail.value.batteryPercentage = deviceState[3]; //电量
|
||||
deviceDetail.value.batteryRemainingTime = deviceState[5]; //续航时间
|
||||
// getList(); // 重新获取设备详情
|
||||
if (deviceDetail.value.batteryPercentage < 20) {
|
||||
ElMessage.closeAll();
|
||||
proxy?.$modal.msgWarning('电量低于20%,请及时充电');
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 其他类型消息(不处理,仅打印)
|
||||
console.log('未处理的消息类型:', deviceState[0]);
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
}
|
||||
};
|
||||
onMounted(async () => {
|
||||
await getList(); // 先获取设备信息
|
||||
// 连接mqtt
|
||||
onConnect(async () => {
|
||||
const deviceImei = deviceDetail.value.deviceImei;
|
||||
if (!deviceImei) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await subscribe(`A/${deviceImei}`, { qos: 1 });
|
||||
console.log('订阅成功');
|
||||
} catch (err) {
|
||||
console.error('订阅失败(onConnect内):', err);
|
||||
}
|
||||
});
|
||||
// 2. 注册消息接收回调(核心:处理设备发送的消息)
|
||||
onMessage((msg) => {
|
||||
console.log('收到新消息:', {
|
||||
主题: msg.topic,
|
||||
内容: msg.payload,
|
||||
时间: msg.time,
|
||||
QoS: msg.qos
|
||||
});
|
||||
// 在这里处理消息(根据实际业务逻辑)
|
||||
handleDeviceMessage(msg);
|
||||
});
|
||||
onError((err) => {
|
||||
console.error('MQTT连接失败原因:', err.message); // 关键:打印连接失败的具体原因
|
||||
});
|
||||
connect();
|
||||
});
|
||||
onUnmounted(() => {
|
||||
// 只有当连接已建立时,才执行断开操作(避免无效调用)
|
||||
if (connected.value) {
|
||||
console.log('页面离开,断开MQTT连接');
|
||||
disconnect(); // 调用断开连接方法
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
@ -800,4 +920,4 @@ onMounted(() => {
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
@ -301,8 +301,6 @@ const resetQuery = () => {
|
||||
|
||||
/** 设备控制跳转 */
|
||||
const handleControl = (row: any) => {
|
||||
console.log(row,'row1111');
|
||||
|
||||
const deviceId = row.id;
|
||||
router.push('/controlCenter/6170/' + deviceId);
|
||||
};
|
||||
|
@ -1,254 +0,0 @@
|
||||
<template>
|
||||
<div class="p-2">
|
||||
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
|
||||
<div v-show="showSearch" class="mb-[10px]">
|
||||
<el-card shadow="hover">
|
||||
<el-form ref="queryFormRef" :model="queryParams" :inline="true">
|
||||
<el-form-item label="部门id" prop="deptId">
|
||||
<el-input v-model="queryParams.deptId" placeholder="请输入部门id" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
<el-form-item label="用户id" prop="userId">
|
||||
<el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
<el-form-item label="排序号" prop="orderNum">
|
||||
<el-input v-model="queryParams.orderNum" placeholder="请输入排序号" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
<el-form-item label="key键" prop="testKey">
|
||||
<el-input v-model="queryParams.testKey" placeholder="请输入key键" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
<el-form-item label="值" prop="value">
|
||||
<el-input v-model="queryParams.value" placeholder="请输入值" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
|
||||
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</transition>
|
||||
|
||||
<el-card shadow="hover">
|
||||
<template #header>
|
||||
<el-row :gutter="10" class="mb8">
|
||||
<el-col :span="1.5">
|
||||
<el-button v-hasPermi="['demo:demo:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button v-hasPermi="['demo:demo:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button v-hasPermi="['demo:demo:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
|
||||
>删除</el-button
|
||||
>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button v-hasPermi="['demo:demo:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
|
||||
</el-col>
|
||||
<right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
|
||||
</el-row>
|
||||
</template>
|
||||
|
||||
<el-table v-loading="loading" border :data="demoList" @selection-change="handleSelectionChange">
|
||||
<el-table-column type="selection" width="55" align="center" />
|
||||
<el-table-column v-if="true" label="主键" align="center" prop="id" />
|
||||
<el-table-column label="部门id" align="center" prop="deptId" />
|
||||
<el-table-column label="用户id" align="center" prop="userId" />
|
||||
<el-table-column label="排序号" align="center" prop="orderNum" />
|
||||
<el-table-column label="key键" align="center" prop="testKey" />
|
||||
<el-table-column label="值" align="center" prop="value" />
|
||||
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
|
||||
<template #default="scope">
|
||||
<el-tooltip content="修改" placement="top">
|
||||
<el-button v-hasPermi="['demo:demo:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
|
||||
</el-tooltip>
|
||||
<el-tooltip content="删除" placement="top">
|
||||
<el-button v-hasPermi="['demo:demo:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
|
||||
</el-card>
|
||||
<!-- 添加或修改测试单对话框 -->
|
||||
<el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
|
||||
<el-form ref="demoFormRef" :model="form" :rules="rules" label-width="80px">
|
||||
<el-form-item label="部门id" prop="deptId">
|
||||
<el-input v-model="form.deptId" placeholder="请输入部门id" />
|
||||
</el-form-item>
|
||||
<el-form-item label="用户id" prop="userId">
|
||||
<el-input v-model="form.userId" placeholder="请输入用户id" />
|
||||
</el-form-item>
|
||||
<el-form-item label="排序号" prop="orderNum">
|
||||
<el-input v-model="form.orderNum" placeholder="请输入排序号" />
|
||||
</el-form-item>
|
||||
<el-form-item label="key键" prop="testKey">
|
||||
<el-input v-model="form.testKey" placeholder="请输入key键" />
|
||||
</el-form-item>
|
||||
<el-form-item label="值" prop="value">
|
||||
<el-input v-model="form.value" placeholder="请输入值" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
|
||||
<el-button @click="cancel">取 消</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup name="Demo" lang="ts">
|
||||
import { listDemo, getDemo, delDemo, addDemo, updateDemo } from '@/api/demo/demo';
|
||||
import { DemoVO, DemoQuery, DemoForm } from '@/api/demo/demo/types';
|
||||
|
||||
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
|
||||
|
||||
const demoList = ref<DemoVO[]>([]);
|
||||
const buttonLoading = ref(false);
|
||||
const loading = ref(true);
|
||||
const showSearch = ref(true);
|
||||
const ids = ref<Array<string | number>>([]);
|
||||
const single = ref(true);
|
||||
const multiple = ref(true);
|
||||
const total = ref(0);
|
||||
|
||||
const queryFormRef = ref<ElFormInstance>();
|
||||
const demoFormRef = ref<ElFormInstance>();
|
||||
|
||||
const dialog = reactive<DialogOption>({
|
||||
visible: false,
|
||||
title: ''
|
||||
});
|
||||
|
||||
const initFormData: DemoForm = {
|
||||
id: undefined,
|
||||
deptId: undefined,
|
||||
userId: undefined,
|
||||
orderNum: undefined,
|
||||
testKey: undefined,
|
||||
value: undefined
|
||||
};
|
||||
const data = reactive<PageData<DemoForm, DemoQuery>>({
|
||||
form: { ...initFormData },
|
||||
queryParams: {
|
||||
pageNum: 1,
|
||||
pageSize: 10,
|
||||
deptId: undefined,
|
||||
userId: undefined,
|
||||
orderNum: undefined,
|
||||
testKey: undefined,
|
||||
value: undefined
|
||||
},
|
||||
rules: {
|
||||
id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
|
||||
deptId: [{ required: true, message: '部门id不能为空', trigger: 'blur' }],
|
||||
userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
|
||||
orderNum: [{ required: true, message: '排序号不能为空', trigger: 'blur' }],
|
||||
testKey: [{ required: true, message: 'key键不能为空', trigger: 'blur' }],
|
||||
value: [{ required: true, message: '值不能为空', trigger: 'blur' }]
|
||||
}
|
||||
});
|
||||
|
||||
const { queryParams, form, rules } = toRefs(data);
|
||||
|
||||
/** 查询测试单列表 */
|
||||
const getList = async () => {
|
||||
loading.value = true;
|
||||
const res = await listDemo(queryParams.value);
|
||||
demoList.value = res.rows;
|
||||
total.value = res.total;
|
||||
loading.value = false;
|
||||
};
|
||||
|
||||
/** 取消按钮 */
|
||||
const cancel = () => {
|
||||
reset();
|
||||
dialog.visible = false;
|
||||
};
|
||||
|
||||
/** 表单重置 */
|
||||
const reset = () => {
|
||||
form.value = { ...initFormData };
|
||||
demoFormRef.value?.resetFields();
|
||||
};
|
||||
|
||||
/** 搜索按钮操作 */
|
||||
const handleQuery = () => {
|
||||
queryParams.value.pageNum = 1;
|
||||
getList();
|
||||
};
|
||||
|
||||
/** 重置按钮操作 */
|
||||
const resetQuery = () => {
|
||||
queryFormRef.value?.resetFields();
|
||||
handleQuery();
|
||||
};
|
||||
|
||||
/** 多选框选中数据 */
|
||||
const handleSelectionChange = (selection: DemoVO[]) => {
|
||||
ids.value = selection.map((item) => item.id);
|
||||
single.value = selection.length != 1;
|
||||
multiple.value = !selection.length;
|
||||
};
|
||||
|
||||
/** 新增按钮操作 */
|
||||
const handleAdd = () => {
|
||||
reset();
|
||||
dialog.visible = true;
|
||||
dialog.title = '添加测试单';
|
||||
};
|
||||
|
||||
/** 修改按钮操作 */
|
||||
const handleUpdate = async (row?: DemoVO) => {
|
||||
reset();
|
||||
const _id = row?.id || ids.value[0];
|
||||
const res = await getDemo(_id);
|
||||
Object.assign(form.value, res.data);
|
||||
dialog.visible = true;
|
||||
dialog.title = '修改测试单';
|
||||
};
|
||||
|
||||
/** 提交按钮 */
|
||||
const submitForm = () => {
|
||||
demoFormRef.value?.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
buttonLoading.value = true;
|
||||
if (form.value.id) {
|
||||
await updateDemo(form.value).finally(() => (buttonLoading.value = false));
|
||||
} else {
|
||||
await addDemo(form.value).finally(() => (buttonLoading.value = false));
|
||||
}
|
||||
proxy?.$modal.msgSuccess('修改成功');
|
||||
dialog.visible = false;
|
||||
await getList();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/** 删除按钮操作 */
|
||||
const handleDelete = async (row?: DemoVO) => {
|
||||
const _ids = row?.id || ids.value;
|
||||
await proxy?.$modal.confirm('是否确认删除测试单编号为"' + _ids + '"的数据项?').finally(() => (loading.value = false));
|
||||
await delDemo(_ids);
|
||||
proxy?.$modal.msgSuccess('删除成功');
|
||||
await getList();
|
||||
};
|
||||
|
||||
/** 导出按钮操作 */
|
||||
const handleExport = () => {
|
||||
proxy?.download(
|
||||
'demo/demo/export',
|
||||
{
|
||||
...queryParams.value
|
||||
},
|
||||
`demo_${new Date().getTime()}.xlsx`
|
||||
);
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
getList();
|
||||
});
|
||||
</script>
|
@ -1,259 +0,0 @@
|
||||
<template>
|
||||
<div class="p-2">
|
||||
<transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
|
||||
<div v-show="showSearch" class="mb-[10px]">
|
||||
<el-card shadow="hover">
|
||||
<el-form ref="queryFormRef" :model="queryParams" :inline="true">
|
||||
<el-form-item label="树节点名" prop="treeName">
|
||||
<el-input v-model="queryParams.treeName" placeholder="请输入树节点名" clearable @keyup.enter="handleQuery" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
|
||||
<el-button icon="Refresh" @click="resetQuery">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
</div>
|
||||
</transition>
|
||||
|
||||
<el-card shadow="hover">
|
||||
<template #header>
|
||||
<el-row :gutter="10" class="mb8">
|
||||
<el-col :span="1.5">
|
||||
<el-button v-hasPermi="['demo:tree:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
|
||||
</el-col>
|
||||
<el-col :span="1.5">
|
||||
<el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
|
||||
</el-col>
|
||||
<right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
|
||||
</el-row>
|
||||
</template>
|
||||
<el-table
|
||||
ref="treeTableRef"
|
||||
v-loading="loading"
|
||||
:data="treeList"
|
||||
row-key="id"
|
||||
border
|
||||
:default-expand-all="isExpandAll"
|
||||
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
|
||||
>
|
||||
<el-table-column label="父id" align="center" prop="parentId" />
|
||||
<el-table-column label="部门id" align="center" prop="deptId" />
|
||||
<el-table-column label="用户id" align="center" prop="userId" />
|
||||
<el-table-column label="树节点名" align="center" prop="treeName" />
|
||||
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
|
||||
<template #default="scope">
|
||||
<el-tooltip content="修改" placement="top">
|
||||
<el-button v-hasPermi="['demo:tree:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
|
||||
</el-tooltip>
|
||||
<el-tooltip content="新增" placement="top">
|
||||
<el-button v-hasPermi="['demo:tree:add']" link type="primary" icon="Plus" @click="handleAdd(scope.row)" />
|
||||
</el-tooltip>
|
||||
<el-tooltip content="删除" placement="top">
|
||||
<el-button v-hasPermi="['demo:tree:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
|
||||
</el-tooltip>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</el-card>
|
||||
<!-- 添加或修改测试树对话框 -->
|
||||
<el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
|
||||
<el-form ref="treeFormRef" :model="form" :rules="rules" label-width="80px">
|
||||
<el-form-item label="父id" prop="parentId">
|
||||
<el-tree-select
|
||||
v-model="form.parentId"
|
||||
:data="treeOptions"
|
||||
:props="{ value: 'id', label: 'treeName', children: 'children' } as any"
|
||||
value-key="id"
|
||||
placeholder="请选择父id"
|
||||
check-strictly
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="部门id" prop="deptId">
|
||||
<el-input v-model="form.deptId" placeholder="请输入部门id" />
|
||||
</el-form-item>
|
||||
<el-form-item label="用户id" prop="userId">
|
||||
<el-input v-model="form.userId" placeholder="请输入用户id" />
|
||||
</el-form-item>
|
||||
<el-form-item label="值" prop="treeName">
|
||||
<el-input v-model="form.treeName" placeholder="请输入值" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
|
||||
<el-button @click="cancel">取 消</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup name="Tree" lang="ts">
|
||||
import { listTree, getTree, delTree, addTree, updateTree } from '@/api/demo/tree';
|
||||
import { TreeVO, TreeQuery, TreeForm } from '@/api/demo/tree/types';
|
||||
|
||||
type TreeOption = {
|
||||
id: number;
|
||||
treeName: string;
|
||||
children?: TreeOption[];
|
||||
};
|
||||
|
||||
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
|
||||
|
||||
const treeList = ref<TreeVO[]>([]);
|
||||
const treeOptions = ref<TreeOption[]>([]);
|
||||
const buttonLoading = ref(false);
|
||||
const showSearch = ref(true);
|
||||
const isExpandAll = ref(true);
|
||||
const loading = ref(false);
|
||||
|
||||
const queryFormRef = ref<ElFormInstance>();
|
||||
const treeFormRef = ref<ElFormInstance>();
|
||||
const treeTableRef = ref<ElTableInstance>();
|
||||
|
||||
const dialog = reactive<DialogOption>({
|
||||
visible: false,
|
||||
title: ''
|
||||
});
|
||||
|
||||
const initFormData: TreeForm = {
|
||||
id: undefined,
|
||||
parentId: undefined,
|
||||
deptId: undefined,
|
||||
userId: undefined,
|
||||
treeName: undefined
|
||||
};
|
||||
|
||||
const data = reactive<PageData<TreeForm, TreeQuery>>({
|
||||
form: { ...initFormData },
|
||||
queryParams: {
|
||||
parentId: undefined,
|
||||
deptId: undefined,
|
||||
userId: undefined,
|
||||
treeName: undefined
|
||||
},
|
||||
rules: {
|
||||
id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
|
||||
parentId: [{ required: true, message: '父id不能为空', trigger: 'blur' }],
|
||||
deptId: [{ required: true, message: '部门id不能为空', trigger: 'blur' }],
|
||||
userId: [{ required: true, message: '用户id不能为空', trigger: 'blur' }],
|
||||
treeName: [{ required: true, message: '值不能为空', trigger: 'blur' }]
|
||||
}
|
||||
});
|
||||
|
||||
const { queryParams, form, rules } = toRefs(data);
|
||||
|
||||
/** 查询测试树列表 */
|
||||
const getList = async () => {
|
||||
loading.value = true;
|
||||
const res = await listTree(queryParams.value);
|
||||
const data = proxy?.handleTree<TreeVO>(res.data, 'id', 'parentId');
|
||||
if (data) {
|
||||
treeList.value = data;
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/** 查询测试树下拉树结构 */
|
||||
const getTreeselect = async () => {
|
||||
const res = await listTree();
|
||||
treeOptions.value = [];
|
||||
const data: TreeOption = { id: 0, treeName: '顶级节点', children: [] };
|
||||
data.children = proxy?.handleTree<TreeOption>(res.data, 'id', 'parentId');
|
||||
treeOptions.value.push(data);
|
||||
};
|
||||
|
||||
// 取消按钮
|
||||
const cancel = () => {
|
||||
reset();
|
||||
dialog.visible = false;
|
||||
};
|
||||
|
||||
// 表单重置
|
||||
const reset = () => {
|
||||
form.value = { ...initFormData };
|
||||
treeFormRef.value?.resetFields();
|
||||
};
|
||||
|
||||
/** 搜索按钮操作 */
|
||||
const handleQuery = () => {
|
||||
getList();
|
||||
};
|
||||
|
||||
/** 重置按钮操作 */
|
||||
const resetQuery = () => {
|
||||
queryFormRef.value?.resetFields();
|
||||
handleQuery();
|
||||
};
|
||||
|
||||
/** 新增按钮操作 */
|
||||
const handleAdd = (row?: TreeVO) => {
|
||||
reset();
|
||||
getTreeselect();
|
||||
if (row && row.id) {
|
||||
form.value.parentId = row.id;
|
||||
} else {
|
||||
form.value.parentId = 0;
|
||||
}
|
||||
dialog.visible = true;
|
||||
dialog.title = '添加测试树';
|
||||
};
|
||||
|
||||
/** 展开/折叠操作 */
|
||||
const handleToggleExpandAll = () => {
|
||||
isExpandAll.value = !isExpandAll.value;
|
||||
toggleExpandAll(treeList.value, isExpandAll.value);
|
||||
};
|
||||
|
||||
/** 展开/折叠操作 */
|
||||
const toggleExpandAll = (data: TreeVO[], status: boolean) => {
|
||||
data.forEach((item) => {
|
||||
treeTableRef.value?.toggleRowExpansion(item, status);
|
||||
if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
|
||||
});
|
||||
};
|
||||
|
||||
/** 修改按钮操作 */
|
||||
const handleUpdate = async (row: TreeVO) => {
|
||||
reset();
|
||||
await getTreeselect();
|
||||
if (row) {
|
||||
form.value.parentId = row.id;
|
||||
}
|
||||
const res = await getTree(row.id);
|
||||
Object.assign(form.value, res.data);
|
||||
dialog.visible = true;
|
||||
dialog.title = '修改测试树';
|
||||
};
|
||||
|
||||
/** 提交按钮 */
|
||||
const submitForm = () => {
|
||||
treeFormRef.value?.validate(async (valid: boolean) => {
|
||||
if (valid) {
|
||||
buttonLoading.value = true;
|
||||
if (form.value.id) {
|
||||
await updateTree(form.value).finally(() => (buttonLoading.value = false));
|
||||
} else {
|
||||
await addTree(form.value).finally(() => (buttonLoading.value = false));
|
||||
}
|
||||
proxy?.$modal.msgSuccess('操作成功');
|
||||
dialog.visible = false;
|
||||
await getList();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/** 删除按钮操作 */
|
||||
const handleDelete = async (row: TreeVO) => {
|
||||
await proxy?.$modal.confirm('是否确认删除测试树编号为"' + row.id + '"的数据项?');
|
||||
loading.value = true;
|
||||
await delTree(row.id).finally(() => (loading.value = false));
|
||||
await getList();
|
||||
proxy?.$modal.msgSuccess('删除成功');
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
getList();
|
||||
});
|
||||
</script>
|
Reference in New Issue
Block a user