oa后台设置好富文本内容,在uniapp开发的微信公众号中显示,考虑直接返回内容数据太多,后端接口返回的是一个html地址,通过请求这个地址获取里面的内容来显示

注意:需要https的地址,后端需要配置跨域,https证书等

分出的显示内容的组件

<template>
  <view class="social-detail-html" v-if="detailData.htmlUrl">
    <view class="detail-html-title">服务详情</view>
    <view class="html-content">
      <rich-text :nodes="htmlContent"></rich-text>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, defineProps, computed, defineEmits } from "vue";

const props = defineProps({
  detailData: {
    type: Object,
    default: () => ({}),
  },
});

const htmlContent = ref("");

const dealStrFn = (htmlstr) => {
  let contents = htmlstr;
  let r = RegExp(/<[img]+\s+(.*?)(?<id>\w*?)[\s'"](.*?)>/g);
  let matchres = contents.match(r);
  // contents = contents.replaceAll('<g', '<section')
  // contents = contents.replaceAll('g>', 'section>')
  contents = contents.replaceAll("<g ", "<section ");
  contents = contents.replaceAll("/g>", "/section>");
  if (matchres) {
    matchres.forEach((item, index) => {
      let len = item.length;
      let _str =
        item.slice(0, len - 2) +
        ' style="width:100%;object-fit: contain;height:auto;"/>';
      contents = contents.replace(item, _str);
    });
  }
  contents = contents.replaceAll('xml:space="default"', "");
  contents = contents.replaceAll("svg", "section");
  contents = contents.replaceAll("foreignobject", "section");
  return contents;
};

const getHTMLContent = async () => {
  if (!props.detailData.htmlUrl) return;
  let urlOrigin = props.detailData.htmlUrl;
  const url = urlOrigin.replace("http", "https");
  uni.request({
    url,
    success: (res) => {
      htmlContent.value = dealStrFn(res.data);
    },
    fail: (err) => {
      console.log("请求失败", err);
    },
  });
  // .then((res) => {
  //   htmlContent.value = dealStrFn(res.data);
  // })
  // .catch((err) => {});
};

watch(
  () => props.detailData.htmlUrl,
  () => {
    getHTMLContent();
  },
  {
    immediate: true,
  }
);
</script>

<style lang="scss">
.social-detail-html {
  margin-top: 24rpx;
  padding: 24rpx 24rpx 32rpx;
  background-color: #fff;
  border-radius: 24rpx;

  .detail-html-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #1a1919;
    line-height: 44rpx;
  }

  .html-content {
    overflow: hidden;
    margin-top: 24rpx;
    background: #fff;
  }
}
</style>

当前在app端会报错:contents.replaceAll

原因:JavaScript 引擎兼容性问题

解决方案:

  1. 使用 replace+ 正则表达式替代
    通过正则表达式全局匹配(g标志)实现类似 replaceAll的效果:
this.contents = this.contents.replace(/old/g, "new");

// 注意:若替换内容包含正则特殊字符(如 ., *, ?等),需对字符串进行转义:
const oldStr = "dcs.new.com";
const escapedOldStr = oldStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
this.contents = this.contents.replace(new RegExp(escapedOldStr, 'g'), "new");
  1. 使用 split+ join替代
    适用于简单字符串替换(无正则需求):
this.contents = this.contents.split("old").join("new");
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐