vue 的 reactive 用于精准响应式管理多路视频流的网格布局结构、视频状态和交互行为,通过 reactive 封装 layout 配置、同步更新状态、绑定 vue-grid-layout 实现实时稳定更新。

用 Vue 的 reactive 维护多路视频流监控画面的网格布局,关键不是“存视频流”,而是精准响应式地管理布局结构 + 视频状态 + 交互行为。它解决的是:当用户拖拽、缩放、启停某一路画面时,整个网格如何实时、稳定、可预测地更新。
下面分三块讲清楚怎么做:
网格布局结构用 reactive 封装成可响应式对象
不要用普通数组或对象,而是用 reactive 包裹整个布局配置。每一路视频对应一个网格项(Grid Item),包含位置、尺寸、是否启用、RTSP 地址、连接状态等。
import { reactive } from 'vue'
const videoLayout = reactive({
items: [
{ i: 'cam1', x: 0, y: 0, w: 3, h: 2, url: 'rtsp://192.168.1.101:554/stream1', enabled: true, status: 'connecting' },
{ i: 'cam2', x: 3, y: 0, w: 3, h: 2, url: 'rtsp://192.168.1.102:554/stream1', enabled: true, status: 'playing' },
{ i: 'cam3', x: 0, y: 2, w: 2, h: 2, url: 'rtsp://192.168.1.103:554/stream1', enabled: false, status: 'offline' },
{ i: 'cam4', x: 2, y: 2, w: 4, h: 2, url: 'rtsp://192.168.1.104:554/stream1', enabled: true, status: 'buffering' }
]
})
这样,任何对 videoLayout.items[i].enabled 或 videoLayout.items[i].status 的修改,都会自动触发 <grid-item></grid-item> 重渲染,且不影响其他项。
视频状态变更需同步更新 reactive 数据,而非仅 DOM 控制
比如点击“暂停 cam2”按钮,不能只调 videoEl.pause(),必须同时更新 reactive 状态:
使用 `@ainative/vue-sdk` 为 Vue 3 应用添加 AI 聊天功能。适用于以下场景:(1) 安装 `@ainative/vue-sdk`,(2) 在 Vue 组件中使用 `useChat` 组合式函数,(3) 提供……
const toggleCam = (id) => {
const item = videoLayout.items.find(i => i.i === id)
if (!item) return
item.enabled = !item.enabled
item.status = item.enabled ? 'connecting' : 'paused'
// 这里再触发实际的流启停逻辑(如调用 webrtc-streamer API / 操作 video 元素)
if (item.enabled) {
startStream(item.url, item.i) // 自定义启动函数
} else {
stopStream(item.i)
}
}
这样,UI(比如按钮文字、状态徽标)和底层行为完全一致,避免“界面上显示已启用,但实际没拉流”的不一致问题。
布局变更(拖拽/缩放)直接写入 reactive,由 vue-grid-layout 自动同步
vue-grid-layout 支持 .sync 修饰符绑定 layout,它的 layout 属性本身就是 reactive 的载体:
<grid-layout v-model:layout="videoLayout.items" :col-num="12" :row-height="150" :is-draggable="true" :is-resizable="true" :margin="[10, 10]"><grid-item v-for="item in videoLayout.items" :key="item.i" :i="item.i" :x="item.x" :y="item.y" :w="item.w" :h="item.h"><div class="video-card">
<video :src="item.enabled ? item.url : ''" :autoplay="item.enabled" muted class="stream-player"></video><div class="status-badge">{{ item.status }}</div>
</div>
</grid-item></grid-layout>
只要 videoLayout.items 是 reactive 的,拖拽结束时 vue-grid-layout 内部会自动更新数组中对应项的 x/y/w/h,无需手动 commit 或 emit —— 这正是 reactive 和 .sync 协同的价值。
- 所有布局变动、开关动作、状态反馈都落在同一个响应式源头上
- 不需要额外的 store 或事件总线做中间同步
- 调试时直接看
videoLayout对象就能知道当前全局面板状态
不复杂但容易忽略。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










