uniapp 使用v-html不显示video问题

12 阅读1分钟

Uniapp 打包到微信小程序时 v-html 不显示 video 可能是由于微信小程序对 v-html 的安全限制, 因此简单回显富文本时可考虑拆分富文本重新组装渲染.

以下为使用样例:

<view class="activity-desc" v-for="(item, index) in needArticleList" :key="index">
    <view v-if="item.type == 'rich-text'" v-html="item.value" class='content'></view>
    <video v-if="item.type == 'video' && item.value" :src="item.value" frameborder="0"
      style="width:100%;object-fit: fill;"></video>
</view>
    function getVideo(data) {
      let videoList = [];
      let needArticleList = [];
      let tempContent = data;

      while (tempContent.length > 0) {
        // 查找 video 标签开始位置
        let videoStart = tempContent.indexOf('<video');

        if (videoStart === -1) {
          // 没有找到更多 video 标签,将剩余内容作为富文本
          if (tempContent.trim() !== '') {
            needArticleList.push({
              type: 'rich-text',
              value: tempContent
            });
          }
          break;
        }

        // 处理 video 标签之前的内容(富文本)
        if (videoStart > 0) {
          let beforeVideo = tempContent.substring(0, videoStart);
          if (beforeVideo.trim() !== '') {
            needArticleList.push({
              type: 'rich-text',
              value: beforeVideo
            });
          }
        }

        // 查找 video 标签结束位置
        let videoEnd = tempContent.indexOf('</video>', videoStart);
        if (videoEnd === -1) {
          // 如果没有找到闭合标签,将剩余内容作为富文本
          if (tempContent.trim() !== '') {
            needArticleList.push({
              type: 'rich-text',
              value: tempContent
            });
          }
          break;
        }

        // 提取完整的 video 标签(包含闭合标签和内部的 source 标签)
        let fullVideoTag = tempContent.substring(videoStart, videoEnd + 8); // 8 是 '</video>'.length

        // 从 video 标签中提取 src(优先从 source 标签提取)
        let srcValue = this.extractVideoSrcFromSource(fullVideoTag);
        if (!srcValue) {
          // 如果没有从 source 标签找到,尝试从 video 标签本身提取
          srcValue = this.extractVideoSrcFromVideo(fullVideoTag);
        }

        if (srcValue) {
          videoList.push(srcValue);
          needArticleList.push({
            type: 'video',
            value: srcValue
          });
        } else {
          // 如果提取src失败,将整个video标签作为富文本处理
          needArticleList.push({
            type: 'rich-text',
            value: fullVideoTag
          });
        }

        // 移动到下一个内容
        tempContent = tempContent.substring(videoEnd + 8);
      }

      return needArticleList;
    }