← 返回学习路线

SYSTEM

前端改造

后端实战2.5 前端改造blog-dev
src/content/notes/blog-dev/前端改造.md

2.5 前端改造

2.5.1 安装依赖

cd blog-vue
npm install sockjs-client @stomp/stompjs
依赖 作用
sockjs-client WebSocket 浏览器兼容层,不支持时自动降级为长轮询
@stomp/stompjs STOMP 协议客户端,支持订阅/发布模式

2.5.2 新建 WebSocket Composable

文件: blog-vue/src/composables/useCommentWebSocket.js

import { ref, onUnmounted } from 'vue'
import SockJS from 'sockjs-client'
import { Client } from '@stomp/stompjs'

/**
 * 文章详情页评论实时推送 WebSocket Hook
 *
 * 用法:
 *   const { newComment, connected, connect, disconnect } = useCommentWebSocket(articleId)
 *   onMounted(() => connect())
 *   watch(newComment, (comment) => { comments.value.unshift(comment) })
 */
export function useCommentWebSocket(articleId) {
  const connected = ref(false)
  const newComment = ref(null)

  let stompClient = null

  const connect = () => {
    if (!articleId) return

    const socket = new SockJS('/ws/notify')
    stompClient = new Client({
      webSocketFactory: () => socket,
      reconnectDelay: 5000,           // 断开后 5 秒自动重连
      heartbeatIncoming: 10000,       // 心跳:10 秒收不到就断开
      heartbeatOutgoing: 10000,
      onConnect: () => {
        connected.value = true
        const destination = `/topic/article/${articleId}/comments`
        stompClient.subscribe(destination, (message) => {
          try {
            newComment.value = JSON.parse(message.body)
          } catch (e) {
            console.error('[WebSocket] 消息解析失败:', e)
          }
        })
      },
      onDisconnect: () => {
        connected.value = false
      },
      onStompError: (frame) => {
        console.error('[WebSocket] STOMP 错误:', frame.headers['message'])
      }
    })

    stompClient.activate()
  }

  const disconnect = () => {
    if (stompClient) {
      stompClient.deactivate()
      stompClient = null
      connected.value = false
    }
  }

  onUnmounted(() => disconnect())

  return { connected, newComment, connect, disconnect }
}

设计思路:

设计点 决策 原因
Vue 3 Composable 封装为 Hook 符合 Vue 3 Composition API 最佳实践,复用性强
连接路径 /ws/notify 相对路径 由 Vite 代理转发到后端,无需硬编码端口
reconnectDelay: 5000 自动重连 网络抖动或后端重启后自动恢复
心跳 10 秒 保活机制 及时发现死连接,避免假在线
onUnmounted 自动断开 生命周期管理 组件销毁时清理,防止内存泄漏
newComment 是 ref 响应式变量 父组件 watch 即可响应
connected 状态 暴露连接状态 前端口以显示”连接中/已连接/已断开”

2.5.3 修改 ArticleDetail.vue 集成通知

文件: blog-vue/src/views/ArticleDetail.vue

Script 改动:

// 导入新增
import { ref, onMounted, computed, watch } from 'vue'
import { useCommentWebSocket } from '../composables/useCommentWebSocket'

// 新增状态
const newCommentNotification = ref(null)
const showCommentToast = ref(false)

// 初始化 WebSocket
const { newComment, connect: connectWS } = useCommentWebSocket(route.params.id)

// 监听新评论
watch(newComment, (comment) => {
  if (comment) {
    newCommentNotification.value = comment
    showCommentToast.value = true
    setTimeout(() => { showCommentToast.value = false }, 5000)
  }
})

// onMounted 中增加
onMounted(() => {
  loadArticle()
  loadCategories()
  connectWS()
})

Template 改动: 在 <article class="article"> 内部最顶部添加 Toast:

<article v-else-if="article" class="article">
  <!-- 实时评论通知 Toast -->
  <Transition name="toast">
    <div v-if="showCommentToast && newCommentNotification" class="comment-toast">
      <div class="toast-icon">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
        </svg>
      </div>
      <div class="toast-body">
        <span class="toast-title">新评论</span>
        <span class="toast-text">{{ newCommentNotification.commentContent }}</span>
      </div>
    </div>
  </Transition>

  <header class="article-header">
    <!-- 原有内容不变 -->
  </header>
</article>

Style 改动: 在 </style> 前添加 Toast 样式:

/* 评论通知 Toast */
.comment-toast {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 14px 18px;
  margin-bottom: var(--space-6);
  background: linear-gradient(135deg, #1a2a1f, #1e3a24);
  border: 1px solid #10b981;
  border-radius: var(--radius-lg);
}

.toast-icon {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(16, 185, 129, 0.15);
  border-radius: var(--radius-full);
  color: #10b981;
}

.toast-body {
  display: flex;
  flex-direction: column;
  gap: 2px;
  overflow: hidden;
}

.toast-title {
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-semibold);
  color: #10b981;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.toast-text {
  font-size: var(--font-size-sm);
  color: #d1d5db;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 500px;
}

.toast-enter-active { animation: slideIn 0.3s ease-out; }
.toast-leave-active { animation: slideOut 0.3s ease-in; }

@keyframes slideIn {
  from { opacity: 0; transform: translateY(-12px); }
  to   { opacity: 1; transform: translateY(0); }
}
@keyframes slideOut {
  from { opacity: 1; transform: translateY(0); }
  to   { opacity: 0; transform: translateY(-12px); }
}

设计思路:

设计点 决策 原因
Toast 而非列表 轻量通知 不阻塞阅读,5 秒自动消失
Vue <Transition> 内置动画 比手动 CSS 动画更简洁,自动处理 enter/leave
绿色主题 #10b981 与项目主题色一致 视觉统一,不突兀
text-overflow: ellipsis 长文本截断 防止超长评论撑破布局
watch 监听 newComment 响应式驱动 新消息到达时自动触发,无需手动轮询

2.5.4 修改 vite.config.js 添加 WebSocket 代理

文件: blog-vue/vite.config.js

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true
      },
      '/ws': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        ws: true
      }
    }
  }
})

设计思路:

配置项 作用
/ws 代理规则 前端 5173 端口的 /ws 请求转发到后端 8080 端口
ws: true 支持 WebSocket 协议升级(HTTP → WebSocket)
changeOrigin: true 修改请求头 Host,避免后端跨域校验