From 812135c5bb6efc9e31edcfa0a11af5598b506ab6 Mon Sep 17 00:00:00 2001
From: xingyy <64720302+Concur-max@users.noreply.github.com>
Date: Thu, 27 Feb 2025 16:25:31 +0800
Subject: [PATCH] =?UTF-8?q?refactor(app):=20=E9=87=8D=E6=9E=84=E5=BA=94?=
=?UTF-8?q?=E7=94=A8=E5=88=9D=E5=A7=8B=E5=8C=96=E5=92=8C=E9=AA=A8=E6=9E=B6?=
=?UTF-8?q?=E5=B1=8F=E9=80=BB=E8=BE=91?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 移除了不必要的 preload 脚本- 优化了 i18n 和 websocket 插件的实现- 简化了 app.vue 中的逻辑
- 新增了独立的骨架屏组件
---
app/app.vue | 44 +-----
app/components/app-skeleton/index.vue | 194 ++++++++++++++++++++++++++
app/plugins/i18n.ts | 10 --
app/plugins/websocket.ts | 117 ----------------
app/utils/format.js | 44 ------
app/utils/preload.ts | 10 --
nuxt.config.js | 6 -
7 files changed, 200 insertions(+), 225 deletions(-)
create mode 100644 app/components/app-skeleton/index.vue
delete mode 100644 app/plugins/websocket.ts
delete mode 100644 app/utils/format.js
delete mode 100644 app/utils/preload.ts
diff --git a/app/app.vue b/app/app.vue
index 7da29f2..1612250 100644
--- a/app/app.vue
+++ b/app/app.vue
@@ -1,55 +1,23 @@
-
-
+
diff --git a/app/components/app-skeleton/index.vue b/app/components/app-skeleton/index.vue
new file mode 100644
index 0000000..05f1dfc
--- /dev/null
+++ b/app/components/app-skeleton/index.vue
@@ -0,0 +1,194 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/plugins/i18n.ts b/app/plugins/i18n.ts
index 1eb3555..2745562 100644
--- a/app/plugins/i18n.ts
+++ b/app/plugins/i18n.ts
@@ -38,15 +38,5 @@ export default defineNuxtPlugin(() => {
const systemLang = getSystemLanguage()
setLocale(systemLang as TypeLocale)
Locale.use(systemLang)
-
- // 监听语言变化,当语言变化时,如果有活跃的 WebSocket 连接,则重新连接
- watch(() => i18n.locale.value, (newLocale) => {
- // 如果 WebSocket 插件已加载并且有活跃连接
- if (nuxtApp.$ws) {
- // 使用 refreshConnection 方法刷新 WebSocket 连接
- console.log('语言已更改为:', newLocale, '正在更新 WebSocket 连接')
- nuxtApp.$ws.refreshConnection()
- }
- })
}
})
diff --git a/app/plugins/websocket.ts b/app/plugins/websocket.ts
deleted file mode 100644
index 5551c18..0000000
--- a/app/plugins/websocket.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-import {authStore} from "@/stores/auth";
-
-export default defineNuxtPlugin(() => {
- const config = useRuntimeConfig()
- const { token } = authStore()
- const i18n = useNuxtApp().$i18n
-
- const ws = reactive({
- instance: null as WebSocket | null,
- isConnected: false,
- currentPath: '', // 保存当前连接的路径
- currentData: null as Record | null, // 保存当前连接的数据
-
- // 修改 connect 方法接收路径和数据对象
- connect(path: string, data?: Record) {
- // 保存当前连接的路径和数据,以便后续重连使用
- this.currentPath = path
- this.currentData = data || null
-
- if (this.instance?.readyState === WebSocket.OPEN) {
- this.instance.close()
- }
-
- // 构建查询字符串
- const queryString =data
- ? '?' + Object.entries({
- token: token.value,
- 'accept-language': i18n.locale.value, // 添加当前语言作为 accept-language
- ...data
- })
- .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
- .join('&')
- : '?' + Object.entries({
- token: token.value,
- 'accept-language': i18n.locale.value // 即使没有其他数据,也添加语言
- })
- .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
- .join('&')
-
- // 构建完整的 WebSocket URL
- const wsUrl = `${config.public.NUXT_PUBLIC_SOCKET_URL}${path}${queryString}`
- this.instance = new WebSocket(wsUrl)
-
- this.instance.onopen = () => {
- this.isConnected = true
- console.log('WebSocket 已连接')
- }
-
- this.instance.onclose = () => {
- this.isConnected = false
- console.log('WebSocket 已断开')
- /* this.reconnect(path, data)*/
- }
-
- this.instance.onerror = (error) => {
- console.error('WebSocket 错误:', error)
- }
-
- this.instance.onmessage = (event) => {
- try {
- const data = JSON.parse(event.data)
- this.handleMessage(data)
- } catch (error) {
- console.error('消息解析错误:', error)
- }
- }
- },
-
- // 更新重连方法以支持数据对象
- reconnect(path?: string, data?: Record) {
- setTimeout(() => {
- console.log('尝试重新连接...')
- // 如果提供了新的路径和数据,则使用新的;否则使用保存的当前路径和数据
- this.connect(path || this.currentPath, data || this.currentData || undefined)
- }, 3000)
- },
-
- // 使用当前保存的路径和数据重新连接
- refreshConnection() {
- if (this.currentPath) {
- console.log('刷新 WebSocket 连接,使用当前语言:', i18n.locale.value)
- this.connect(this.currentPath, this.currentData || undefined)
- return true
- }
- return false // 如果没有当前连接信息,返回 false
- },
-
- // 发送消息
- send(data: any) {
- if (this.instance?.readyState === WebSocket.OPEN) {
- this.instance.send(JSON.stringify(data))
- } else {
- console.warn('WebSocket 未连接,无法发送消息')
- }
- },
-
- // 关闭连接
- disconnect() {
- if (this.instance) {
- this.instance.close()
- this.instance = null
- }
- },
-
- // 消息处理
- handleMessage(data: any) {
- // 触发自定义事件,让组件可以监听
- window.dispatchEvent(new CustomEvent('ws-message', { detail: data }))
- }
- })
-
- return {
- provide: {
- ws
- }
- }
-})
\ No newline at end of file
diff --git a/app/utils/format.js b/app/utils/format.js
deleted file mode 100644
index c4ee7b2..0000000
--- a/app/utils/format.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * 格式化价格
- * @param {number} price - 价格数值
- * @param {string} currency - 货币符号,默认为 ¥
- * @returns {string} 格式化后的价格字符串
- */
-export const formatPrice = (price, currency = '¥') => {
- if (price == null || isNaN(price)) return `${currency}0`
-
- // 将价格转换为数字
- const numPrice = Number(price)
-
- // 处理小数点,保留两位小数
- const formattedPrice = numPrice.toFixed(2)
-
- // 添加千位分隔符
- const parts = formattedPrice.toString().split('.')
- parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
-
- return `${currency}${parts.join('.')}`
-}
-
-/**
- * 格式化数字
- * @param {number} num - 需要格式化的数字
- * @returns {string} 格式化后的数字字符串
- */
-export const formatNumber = (num) => {
- if (num == null || isNaN(num)) return '0'
-
- return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
-}
-
-/**
- * 格式化百分比
- * @param {number} value - 需要格式化的值
- * @param {number} decimals - 小数位数,默认为 2
- * @returns {string} 格式化后的百分比字符串
- */
-export const formatPercent = (value, decimals = 2) => {
- if (value == null || isNaN(value)) return '0%'
-
- return `${(Number(value) * 100).toFixed(decimals)}%`
-}
\ No newline at end of file
diff --git a/app/utils/preload.ts b/app/utils/preload.ts
deleted file mode 100644
index 87b3057..0000000
--- a/app/utils/preload.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export default function preload() {
- return `
- ;(function() {
- const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
- const setting = localStorage.getItem('nuxt-color-mode') || 'auto';
- if (setting === 'dark' || (prefersDark && setting !== 'light'))
- document.documentElement.classList.toggle('van-theme-dark', true);
- })()
- `
-}
diff --git a/nuxt.config.js b/nuxt.config.js
index ea63f3c..e144652 100644
--- a/nuxt.config.js
+++ b/nuxt.config.js
@@ -1,7 +1,5 @@
import dotenv from 'dotenv'
import process from 'node:process'
-import preload from './app/utils/preload'
-import skeletonPreload from './app/utils/skeleton-preload'
import { currentLocales } from './i18n/i18n'
const envFile = process.env.ENV_FILE || '.env.test'
dotenv.config({ path: `./env/${envFile}` })
@@ -81,10 +79,6 @@ export default defineNuxtConfig({
{ name: 'theme-color', media: '(prefers-color-scheme: light)', content: '#ffffff' },
{ name: 'theme-color', media: '(prefers-color-scheme: dark)', content: '#222222' },
],
- script: [
- { innerHTML: skeletonPreload(), type: 'text/javascript', tagPosition: 'head' },
- { innerHTML: preload(), type: 'text/javascript', tagPosition: 'head' },
- ],
},
},
nitro: {