# uni-demo **Repository Path**: kris-Q/uni-demo ## Basic Information - **Project Name**: uni-demo - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2025-02-05 - **Last Updated**: 2025-04-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 0、流程 ``` JS 发请求: sendMessageWithPromise({action, sql}) ↓ 生成 requestId → 存入 Map → 等待 ↓ 发送到 uni-app ↓ uni-app 处理完后,带 requestId 回传 ↓ receiveMessageFromApp 找到回调 resolve ↓ Promise 被 resolve,.then 收到结果 ``` # 1、main.js ```js import * as uni from './js/uni.webview'// 直接引入 import { initUniBridge } from './js/uniBridge'; // 给所有组件的 this 注入 uni Vue.prototype.uni = uni // 初始化 uniBridge 通信机制 initUniBridge(uni); ``` # 2、HelloWord.vue ```vue ``` # 3、导入zip目录 zip名字:业务系统的拼音首字母,里面文件 ``` dist |---index.html |--js/css config.json ``` 解压后:例:生产系统 ``` scxt |--dist |---index.html |---js/css |--config.json ``` config.json文件格式 ```json { "name": "生产评价", "dbName": "scpj", "secretLevel": "非密", "version": "1.0" } ``` # urlBridgr.js ```js if (!window._uniBridgeListeners) { window._uniBridgeListeners = new Map(); } const DEFAULT_TIMEOUT = 5000; // 初始化方法,绑定全局接收器 export function initUniBridge(uni) { window.uni = uni; window.receiveMessageFromApp = function (msg) { const data = typeof msg === 'string' ? JSON.parse(msg) : msg; const requestId = data.requestId; if (requestId && window._uniBridgeListeners.has(requestId)) { const cb = window._uniBridgeListeners.get(requestId); cb(data.data); window._uniBridgeListeners.delete(requestId); } else { console.warn('未找到 requestId 对应回调:', requestId, msg); } }; } // 核心发送方法 export function sendMessageWithPromise({ action, sql }) { const requestId = `${action}-${Date.now()}-${Math.random()}`; const payload = { action, sql, dbName: 'main', requestId }; return new Promise((resolve, reject) => { const timeout = setTimeout(() => { window._uniBridgeListeners.delete(requestId); reject(new Error('请求超时')); }, DEFAULT_TIMEOUT); window._uniBridgeListeners.set(requestId, (data) => { clearTimeout(timeout); resolve(data); }); if (window.uni && window.uni.webView) { window.uni.webView.postMessage({ data: payload }); } else { clearTimeout(timeout); reject(new Error('uni.webView 未定义')); } }); } // 快捷方法封装 export const createTableSql = (sql) => sendMessageWithPromise({ action: 'createSql', sql }); export const selectSql = (sql) => sendMessageWithPromise({ action: 'selectSql', sql }); export const addSql = (sql) => sendMessageWithPromise({ action: 'addSql', sql }); export const deleteSql = (sql) => sendMessageWithPromise({ action: 'deleteSql', sql }); export const updateSql = (sql) => sendMessageWithPromise({ action: 'updateSql', sql }); ```