vue|video 的 this.$refs 使用上遇到問題

我的數據有五筆
第 1、2、5 是視頻
3、4 都是照片

template

<div 
          @mouseleave="handleLeave(item, index)"
          @mouseenter="handleEnter(item, index)">
<video
            ref="workCardVideo"
            muted
            playsinline>
            <source 
              :src="item.src" 
              type="video/mp4">
          </video>
</div>

method

handleEnter(item, index) {
      if (item.src.includes('.mp4'))
        this.handleItemVideo(false, 'play', index)
    },
    handleLeave(item, index) {
      if (item.src.includes('.mp4'))
        this.handleItemVideo(false, 'pause', index)
    },
    handleItemVideo(all, type, index) {
      if (type === 'pause')
        this.$refs.workCardVideo[index].pause()
      if (type === 'play')
        this.$refs.workCardVideo[index].play()
    },

遇到了個問題
由於並不是每個item.src都是視頻
所以鼠標移動到第五個區塊時會出現錯誤

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'play' of undefined"
[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'pause' of undefined"

因為實際上 <video> 的 index 只有到 2
但我實際上給this.$refs的 index 是 4
所以出現這錯誤
想了老半天
請問這能怎麼解決?

阅读 3.3k
2 个回答

给渲染成照片的标签也加 ref = "workCardVideo",总而言之,确保每个 index 都有对应的workCardVideo

如果仅仅是想不报错,可以采用如下处理,即在相应处理前验证有效性

handleItemVideo(all, type, index) {
      if (type === 'pause' && this.$refs.workCardVideo[index] && this.$refs.workCardVideo[index].pause )
        this.$refs.workCardVideo[index].pause()
      if (type === 'play' && this.$refs.workCardVideo[index] && this.$refs.workCardVideo[index].play )
        this.$refs.workCardVideo[index].play()
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题