Browse Source

更新代码规范,readme
Signed-off-by: Caner <5658514@qq.com>

Caner 3 years ago
parent
commit
6fbd272571

+ 4 - 33
README.md

@@ -1,30 +1,5 @@
 # vue3+TS+Eslint 多入口模板
 # vue3+TS+Eslint 多入口模板
 
 
-## 注意
-```
-1. 默认安装:
-   1. aixos
-   2. js-md5
-   3. pinia
-   4. vue-router
-   5. less
-   6. naive-ui 
-2. 子页面全局interface文件/pages/*/assets/js/interfacePublic.ts
-3. 注意pinia 注册ID唯一性
-4. 子页面全局ui组件引用 /pages/*/assets/js/nativeUiPluginPublic.ts
-5. 本项目配置全局动态路由(各子页面单独添加route.ts)参考/pages/index/views/*/route.ts
-6. 多入口无法同时使用web模式
-7. 注意组件化
-```
-## use
-```
-yarn 
-yarn dev
-yarn build
-
-```
-
-
 ## 目录结构
 ## 目录结构
 ```
 ```
 | - `src`
 | - `src`
@@ -57,8 +32,7 @@ yarn build
 |   - `utils`                     全局插件
 |   - `utils`                     全局插件
 |   - `assets`                    全局静态文件
 |   - `assets`                    全局静态文件
 ```
 ```
-
-## vue3 使用setup方式,注意格式
+## 编写规范
 ```
 ```
 import { onMounted, ref, computed} from 'vue'
 import { onMounted, ref, computed} from 'vue'
 <script setup>
 <script setup>
@@ -82,11 +56,10 @@ import { onMounted, ref, computed} from 'vue'
 <template></template>
 <template></template>
 <style></style>
 <style></style>
 ```
 ```
-## 编写规范
-### typescript 脚本
+## typescript 脚本
 * 不允许的操作
 * 不允许的操作
-  * 使用 `any` 类型
-  * 使用 `JSON.parse` 等危险操作时不嵌套异常处理
+  * `any` 类型
+  * `JSON.parse` 等危险操作时不嵌套异常处理
   * 单个文件中的脚本代码总行数不允许超过`1024`行
   * 单个文件中的脚本代码总行数不允许超过`1024`行
 * 命名
 * 命名
   * 文件 小写字母命名,多个词之间以 `-`连接,不允许大写字母及驼峰式
   * 文件 小写字母命名,多个词之间以 `-`连接,不允许大写字母及驼峰式
@@ -106,8 +79,6 @@ import { onMounted, ref, computed} from 'vue'
     * 私有变量以下划线接小写字母开头的驼峰式,如 `_innerType`
     * 私有变量以下划线接小写字母开头的驼峰式,如 `_innerType`
   * 全局常量,下划线连接大写字母,如 `GROUP_TYPES`
   * 全局常量,下划线连接大写字母,如 `GROUP_TYPES`
 * 类型及注释
 * 类型及注释
-  * 所有需要在外部被调用的接口需明确定义参数及返回值类型,直接使用`typescript`类型系统即可
-  * 所有需要公共使用(即除了本模块使用,其他模块也会涉及到)的类型,主要是接口返回的数据定义类型,需要放在 `src/types` 目录中
   * 注释写法分以下几类
   * 注释写法分以下几类
   ```ts
   ```ts
   /** 这种用于简单描述函数作用 或 类成员变量用处 */
   /** 这种用于简单描述函数作用 或 类成员变量用处 */

+ 1 - 2
src/pages/index/views/test/route.ts

@@ -6,6 +6,5 @@ export default {
     authorize: true
     authorize: true
   },
   },
   component: () => import('./index.vue' as any),
   component: () => import('./index.vue' as any),
-  children: [
-  ]
+  children: []
 } as RouteRecordRaw
 } as RouteRecordRaw

+ 1 - 1
src/pages/login/main.ts

@@ -1,5 +1,5 @@
 import { createApp } from 'vue'
 import { createApp } from 'vue'
 import App from './App.vue'
 import App from './App.vue'
-import '@/utils/rem.js'
+import '@/utils/rem'
 const app = createApp(App)
 const app = createApp(App)
 app.mount('#app')
 app.mount('#app')

+ 0 - 0
src/utils/exp2File.ts → src/utils/exp-to-file.ts


+ 0 - 0
src/utils/html2File.ts → src/utils/html-tp-File.ts


+ 0 - 0
src/utils/JsFn.ts → src/utils/js-fn.ts


+ 6 - 3
src/utils/registerMenu.js → src/utils/register-menu.ts

@@ -1,8 +1,11 @@
 import { Boot } from '@wangeditor/editor'
 import { Boot } from '@wangeditor/editor'
-import {exp2pdf} from '@/utils/html2File'
+import { exp2pdf } from '@/utils/html2File'
 console.warn('此插件注册富文本自定义按钮')
 console.warn('此插件注册富文本自定义按钮')
 // 注册一个保存按钮
 // 注册一个保存按钮
 class SaveBtn {
 class SaveBtn {
+    title: string
+    iconSvg: string
+    tag: string
 
 
     constructor() {
     constructor() {
         this.title = '导出PDF'
         this.title = '导出PDF'
@@ -23,12 +26,12 @@ class SaveBtn {
     }
     }
 
 
     exec() {
     exec() {
-        exp2pdf('exportPDF', '监控量测报告'+new Date().toLocaleDateString())
+        exp2pdf('exportPDF', '监控量测报告' + new Date().toLocaleDateString())
     }
     }
 }
 }
 Boot.registerMenu({
 Boot.registerMenu({
     key: 'SaveBtn',
     key: 'SaveBtn',
     factory() {
     factory() {
-        return new SaveBtn()
+        return new SaveBtn() as any
     }
     }
 })
 })

+ 0 - 41
src/utils/resizeChart.js

@@ -1,41 +0,0 @@
-class ResizeChart {
-
-  /**
-   * 监听
-   * @param {Array | Object} charts 
-   */
-  on(charts) {
-    window.addEventListener('resize', ()=>{
-      if (Array.isArray(charts) && charts.length) {
-        for (let k = 0; k < charts.length; k++) {
-          const el = charts[k];
-          if (el.echart) el.echart.resize()
-        }
-      }else{
-        charts.resize()
-      }      
-    })
-  }
-
-  /**
-   * 移除监听
-   * @param {Array | Object} charts 
-   */
-  off(charts) {
-    window.removeEventListener('resize', ()=>{
-      if (Array.isArray(charts) && charts.length) {
-        for (let k = 0; k < charts.length; k++) {
-          const el = charts[k];
-          if (el.echart) el.echart.dispose()
-        }
-      }else{
-        charts.dispose()
-      }
-    })
-  }
-}
-
-
-
-
-export default new ResizeChart()

+ 172 - 172
src/utils/SRSWebRtcPlayer.ts → src/utils/srs-wertc-player.ts

@@ -1,173 +1,173 @@
-/**
- * srs webrtc palyer
- * auth Caner
- */
-class WebRtcPlayer {
-    private Peer: RTCPeerConnection | null
-    private TIMER: number | null
-    constructor(option: { HOST: string; TOKEN: string; UUID: string; PROFILE: number; PORT: number; DOM: HTMLVideoElement }) {
-        this.TIMER = null
-        this.Peer = null
-        this.initWebRtc(option.HOST, option.PORT, option.TOKEN, option.UUID, option.PROFILE, option.DOM).then(res => {
-            this.Peer = res
-        }).catch(() => {
-            this.Peer = null
-        })
-    }
-
-    /**
-     * 同步睡眠
-     * @param ms 毫秒
-     * @returns
-     */
-    private sleep(ms: number) { return new Promise((resolve) => { setTimeout(resolve, ms) }) }
-
-    /**
-     * 初始化webrtc
-     * @param HOST 媒体服务器地址
-     * @param TOKEN 用户token
-     * @param UUID 摄像头uuid
-     * @param PROFILE 码流
-     * @param DOM video节点
-     * @returns 
-     */
-    private async initWebRtc(HOST: string, PORT: number, TOKEN: string, UUID: string, PROFILE: number, DOM: HTMLVideoElement): Promise<RTCPeerConnection | null> {
-        try {
-            const Peer = new RTCPeerConnection()
-            Peer.addTransceiver('video', { direction: 'recvonly' })
-            const offer = await Peer.createOffer()
-            await Peer.setLocalDescription(offer)
-
-            // 监听视频=播放
-            Peer.ontrack = (event: RTCTrackEvent) => {
-                if (DOM) {
-                    const { streams } = event
-                    DOM.srcObject = streams![0]
-                    console.log('track', event)
-                }
-            }
-
-            Peer.oniceconnectionstatechange = () => {
-                const state = Peer.iceConnectionState
-                console.log('ICE状态', state)
-            }
-
-            Peer.onicegatheringstatechange = () => {
-                console.log('GatheringState: ', Peer.iceGatheringState)
-            }
-
-            Peer.onconnectionstatechange = () => {
-                const state = Peer.connectionState
-                console.log('连接状态', state)
-            }
-
-            // SDP SRS params
-            const params = {
-                api: `http://${HOST}:${PORT}/rtc/v1/play/?token=${TOKEN}&uuid=${UUID}&stream=${UUID + PROFILE}&profile=${PROFILE}`,
-                clientip: null,
-                sdp: offer.sdp,
-                streamurl: `webrtc://${HOST}/live/${UUID + PROFILE}?token=${TOKEN}&uuid=${UUID}&stream=${UUID + PROFILE}&profile=${PROFILE}`,
-                tid: Number(Math.floor(new Date().getTime() * Math.random() * 100)).toString(16).slice(0, 7)
-            }
-            console.log('params', params)
-
-            // 发送offer
-            const res = await window.fetch(params.api, {
-                method: 'POST',
-                headers: { 'Content-Type': 'application/json' },
-                body: JSON.stringify(params)
-            })
-
-            // 接收 answer
-            const { sdp } = await res.json()
-            if (sdp) await Peer.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp }))
-
-            return Peer
-        } catch (error) {
-            console.warn('webRtcInit:', error);
-            return null
-        }
-    }
-
-    /**
-     * 云台控制
-     * @param URL 
-     * @param UUID 
-     * @param TOKEN 
-     * @param command 指令:数字键盘1-9去掉5,10:焦距放大,11:焦距缩小 12:亮度,13:色彩饱和度,14:对比度,15:清晰度
-     * @param number [云台速度|焦距参数|色彩饱和度]等值  亮度值 0-100
-     * @returns 
-     */
-    public contrl(URL: string, UUID: string, TOKEN: string, command: number, number: number) {
-        if (!UUID) return
-        if (this.TIMER !== null) clearTimeout(this.TIMER)
-        this.TIMER = setTimeout(() => {
-            window.fetch(URL, {
-                method: 'POST',
-                headers: { 'Content-Type': 'application/json' },
-                body: JSON.stringify({
-                    code: 'cloudcontrol.control',
-                    token: TOKEN,
-                    body: {
-                        uuid: UUID,
-                        command,
-                        number
-                    }
-                })
-            })
-        }, 500) as unknown as number
-    }
-
-    /**
-     * 视频截图
-     * @param option 
-     * @returns base64
-     */
-    public capPhoto(DOM: HTMLVideoElement) {
-        const canvas = document.createElement('canvas')
-        canvas.width = DOM.offsetWidth
-        canvas.height = DOM.offsetHeight
-        const context = canvas.getContext('2d')
-        context?.drawImage(DOM, 0, 0, DOM.offsetWidth, DOM.offsetHeight)
-        const base64 = canvas.toDataURL('image/jpg')
-        return base64
-    }
-
-    /**
-     * 视频录像
-     * @param DOM 
-     * @param TIME ms
-     * @returns 
-     */
-    public async capVideo(DOM: HTMLVideoElement, TIME: number) {
-        const recordedBlobs = [] as any
-        const MediaStream = DOM['srcObject'] as MediaStream
-        const mediaRecorder = new MediaRecorder(MediaStream, { mimeType: 'video/webm;codecs=h264' })
-        mediaRecorder.ondataavailable = (event: { data: { size: number } }) => {
-            if (event.data && event.data.size > 0) {
-                recordedBlobs.push(event.data);
-            }
-        }
-        mediaRecorder.start()
-        await this.sleep(TIME || 1000 * 3)
-        mediaRecorder.stop()
-        return await new Promise((resolve, reject) => {
-            mediaRecorder.onstop = () => {
-                const blob = new Blob(recordedBlobs, { type: 'video/mp4' });
-                resolve(blob)
-            }
-            mediaRecorder.onerror = reject
-        })
-    }
-
-    /**
-     * 关闭webrtc
-     */
-    public async close() {
-        if (this.Peer) this.Peer.close()
-        if (this.TIMER) clearTimeout(this.TIMER)
-    }
-
-}
-
+/**
+ * srs webrtc palyer
+ * auth Caner
+ */
+class WebRtcPlayer {
+    private Peer: RTCPeerConnection | null
+    private TIMER: number | null
+    constructor(option: { HOST: string; TOKEN: string; UUID: string; PROFILE: number; PORT: number; DOM: HTMLVideoElement }) {
+        this.TIMER = null
+        this.Peer = null
+        this.initWebRtc(option.HOST, option.PORT, option.TOKEN, option.UUID, option.PROFILE, option.DOM).then(res => {
+            this.Peer = res
+        }).catch(() => {
+            this.Peer = null
+        })
+    }
+
+    /**
+     * 同步睡眠
+     * @param ms 毫秒
+     * @returns
+     */
+    private sleep(ms: number) { return new Promise((resolve) => { setTimeout(resolve, ms) }) }
+
+    /**
+     * 初始化webrtc
+     * @param HOST 媒体服务器地址
+     * @param TOKEN 用户token
+     * @param UUID 摄像头uuid
+     * @param PROFILE 码流
+     * @param DOM video节点
+     * @returns 
+     */
+    private async initWebRtc(HOST: string, PORT: number, TOKEN: string, UUID: string, PROFILE: number, DOM: HTMLVideoElement): Promise<RTCPeerConnection | null> {
+        try {
+            const Peer = new RTCPeerConnection()
+            Peer.addTransceiver('video', { direction: 'recvonly' })
+            const offer = await Peer.createOffer()
+            await Peer.setLocalDescription(offer)
+
+            // 监听视频=播放
+            Peer.ontrack = (event: RTCTrackEvent) => {
+                if (DOM) {
+                    const { streams } = event
+                    DOM.srcObject = streams![0]
+                    console.log('track', event)
+                }
+            }
+
+            Peer.oniceconnectionstatechange = () => {
+                const state = Peer.iceConnectionState
+                console.log('ICE状态', state)
+            }
+
+            Peer.onicegatheringstatechange = () => {
+                console.log('GatheringState: ', Peer.iceGatheringState)
+            }
+
+            Peer.onconnectionstatechange = () => {
+                const state = Peer.connectionState
+                console.log('连接状态', state)
+            }
+
+            // SDP SRS params
+            const params = {
+                api: `http://${HOST}:${PORT}/rtc/v1/play/?token=${TOKEN}&uuid=${UUID}&stream=${UUID + PROFILE}&profile=${PROFILE}`,
+                clientip: null,
+                sdp: offer.sdp,
+                streamurl: `webrtc://${HOST}/live/${UUID + PROFILE}?token=${TOKEN}&uuid=${UUID}&stream=${UUID + PROFILE}&profile=${PROFILE}`,
+                tid: Number(Math.floor(new Date().getTime() * Math.random() * 100)).toString(16).slice(0, 7)
+            }
+            console.log('params', params)
+
+            // 发送offer
+            const res = await window.fetch(params.api, {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json' },
+                body: JSON.stringify(params)
+            })
+
+            // 接收 answer
+            const { sdp } = await res.json()
+            if (sdp) await Peer.setRemoteDescription(new RTCSessionDescription({ type: 'answer', sdp }))
+
+            return Peer
+        } catch (error) {
+            console.warn('webRtcInit:', error);
+            return null
+        }
+    }
+
+    /**
+     * 云台控制
+     * @param URL 
+     * @param UUID 
+     * @param TOKEN 
+     * @param command 指令:数字键盘1-9去掉5,10:焦距放大,11:焦距缩小 12:亮度,13:色彩饱和度,14:对比度,15:清晰度
+     * @param number [云台速度|焦距参数|色彩饱和度]等值  亮度值 0-100
+     * @returns 
+     */
+    public contrl(URL: string, UUID: string, TOKEN: string, command: number, number: number) {
+        if (!UUID) return
+        if (this.TIMER !== null) clearTimeout(this.TIMER)
+        this.TIMER = setTimeout(() => {
+            window.fetch(URL, {
+                method: 'POST',
+                headers: { 'Content-Type': 'application/json' },
+                body: JSON.stringify({
+                    code: 'cloudcontrol.control',
+                    token: TOKEN,
+                    body: {
+                        uuid: UUID,
+                        command,
+                        number
+                    }
+                })
+            })
+        }, 500) as unknown as number
+    }
+
+    /**
+     * 视频截图
+     * @param option 
+     * @returns base64
+     */
+    public capPhoto(DOM: HTMLVideoElement) {
+        const canvas = document.createElement('canvas')
+        canvas.width = DOM.offsetWidth
+        canvas.height = DOM.offsetHeight
+        const context = canvas.getContext('2d')
+        context?.drawImage(DOM, 0, 0, DOM.offsetWidth, DOM.offsetHeight)
+        const base64 = canvas.toDataURL('image/jpg')
+        return base64
+    }
+
+    /**
+     * 视频录像
+     * @param DOM 
+     * @param TIME ms
+     * @returns 
+     */
+    public async capVideo(DOM: HTMLVideoElement, TIME: number) {
+        const recordedBlobs = [] as any
+        const MediaStream = DOM['srcObject'] as MediaStream
+        const mediaRecorder = new MediaRecorder(MediaStream, { mimeType: 'video/webm;codecs=h264' })
+        mediaRecorder.ondataavailable = (event: { data: { size: number } }) => {
+            if (event.data && event.data.size > 0) {
+                recordedBlobs.push(event.data);
+            }
+        }
+        mediaRecorder.start()
+        await this.sleep(TIME || 1000 * 3)
+        mediaRecorder.stop()
+        return await new Promise((resolve, reject) => {
+            mediaRecorder.onstop = () => {
+                const blob = new Blob(recordedBlobs, { type: 'video/mp4' });
+                resolve(blob)
+            }
+            mediaRecorder.onerror = reject
+        })
+    }
+
+    /**
+     * 关闭webrtc
+     */
+    public async close() {
+        if (this.Peer) this.Peer.close()
+        if (this.TIMER) clearTimeout(this.TIMER)
+    }
+
+}
+
 export default WebRtcPlayer
 export default WebRtcPlayer

+ 0 - 0
src/utils/userdata.ts → src/utils/user-data.ts


+ 9 - 7
src/utils/weather.js → src/utils/weather.ts

@@ -1,6 +1,8 @@
 import axios from 'axios'
 import axios from 'axios'
 import { getActivePinia } from "pinia";
 import { getActivePinia } from "pinia";
 class WeatherService {
 class WeatherService {
+  private axios
+  private icons
   constructor() {
   constructor() {
     this.axios = axios
     this.axios = axios
     /**
     /**
@@ -39,7 +41,7 @@ class WeatherService {
   }
   }
 
 
   // 保存store
   // 保存store
-  saveStore(data) {
+  saveStore(data: any) {
     const store = getActivePinia()
     const store = getActivePinia()
     if (!store) return
     if (!store) return
     const obj = store.state.value
     const obj = store.state.value
@@ -57,12 +59,12 @@ class WeatherService {
    *
    *
    */
    */
   async getCurrentCity() {
   async getCurrentCity() {
-    const { info ,adcode} = await this.axios.get('https://restapi.amap.com/v3/ip?key=76f9007ba8c4c44bb9ad757fe27acb44')
+    const { info, adcode } = await this.axios.get('https://restapi.amap.com/v3/ip?key=76f9007ba8c4c44bb9ad757fe27acb44') as any
     if (info === 'OK') {
     if (info === 'OK') {
-      const res = await this.axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?key=76f9007ba8c4c44bb9ad757fe27acb44&city=${adcode}&extensions=all`)
-      if ( res.info === 'OK') {
-        for (let j = 0; j < res.forecasts[0].casts.length; j++) {
-          const el = res.forecasts[0].casts[j]
+      const { info, forecasts } = await this.axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?key=76f9007ba8c4c44bb9ad757fe27acb44&city=${adcode}&extensions=all`) as any
+      if (info === 'OK') {
+        for (let j = 0; j < forecasts[0].casts.length; j++) {
+          const el = forecasts[0].casts[j]
           for (let k = 0; k < this.icons.length; k++) {
           for (let k = 0; k < this.icons.length; k++) {
             const es = this.icons[k]
             const es = this.icons[k]
             if (el.dayweather.indexOf(es.name) !== -1) {
             if (el.dayweather.indexOf(es.name) !== -1) {
@@ -70,7 +72,7 @@ class WeatherService {
             }
             }
           }
           }
         }
         }
-        this.saveStore(res.forecasts[0])
+        this.saveStore(forecasts[0])
       }
       }
     }
     }
   }
   }

+ 1 - 5
src/vite-env.d.ts

@@ -5,9 +5,5 @@ declare module '*.vue' {
   const component: DefineComponent<{}, {}, any>
   const component: DefineComponent<{}, {}, any>
   export default component
   export default component
 }
 }
-declare module 'js-md5'
-declare module '@/utils/*'
 
 
-/** 代指任意类型 请不要随意使用 */
-// eslint-disable-next-line no-unused-vars
-declare type Any = any
+declare module 'js-md5'