vue实现视频id
Vue 实现视频 ID 管理
在 Vue 中管理视频 ID 通常涉及动态绑定、状态管理和 API 调用。以下是几种常见场景的实现方法:
通过 props 传递视频 ID
父组件向子组件传递视频 ID,适合静态或简单场景:
<!-- 父组件 -->
<template>
<VideoPlayer :videoId="currentVideoId" />
</template>
<script>
export default {
data() {
return {
currentVideoId: 'abc123'
}
}
}
</script>
<!-- 子组件 -->
<script>
export default {
props: ['videoId']
}
</script>
使用 Vuex 集中管理状态
适合跨组件共享视频 ID 的复杂应用:
// store.js
export default new Vuex.Store({
state: {
currentVideoId: null
},
mutations: {
setVideoId(state, id) {
state.currentVideoId = id
}
}
})
动态路由参数
在 vue-router 中通过 URL 传递视频 ID:
// router.js
{
path: '/video/:id',
component: VideoDetail
}
<!-- 视频详情组件 -->
<script>
export default {
computed: {
videoId() {
return this.$route.params.id
}
}
}
</script>
结合 API 获取视频数据
从后端接口获取视频 ID 及相关数据:
methods: {
async fetchVideo() {
const response = await axios.get('/api/videos')
this.videoList = response.data // 包含视频ID数组
}
}
本地存储持久化
使用 localStorage 保存最近播放的视频 ID:
methods: {
saveRecentVideo(id) {
localStorage.setItem('lastVideoId', id)
},
getRecentVideo() {
return localStorage.getItem('lastVideoId')
}
}
注意事项
- 视频 ID 应进行验证处理,防止注入攻击
- 对于敏感视频 ID 应考虑加密处理
- 在组件销毁时清除不必要的视频 ID 引用
- 使用唯一标识符区分不同来源的视频 ID







