index.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <template>
  2. <view class="container main">
  3. <view class="one">
  4. <rich-text :nodes="formatRichText(config.agreement)"></rich-text>
  5. </view>
  6. </view>
  7. </template>
  8. <script>
  9. export default {
  10. components: {},
  11. data() {
  12. return {
  13. config: {},
  14. }
  15. },
  16. onLoad: async function(e) {
  17. const that = this;
  18. that.searchConfig();
  19. },
  20. methods: {
  21. searchConfig() {
  22. const that = this;
  23. try {
  24. const res = uni.getStorageSync('config');
  25. if (res) that.$set(that, `config`, res);
  26. } catch (e) {}
  27. },
  28. // 处理富文本
  29. formatRichText(html) {
  30. if (html) {
  31. html = html.replace(/<table[^>]*>/gi, match => {
  32. // 如果已有 style 属性,替换为新的样式;如果没有,添加新的 style 属性
  33. return match.replace(/style="[^"]+"/gi, `style="border-collapse: collapse; width: 100%;"`)
  34. .replace(/<table/gi, `<table style="border-collapse: collapse; width: 100%;"`);
  35. });
  36. html = html.replace(/<th[^>]*>/gi, match => {
  37. // 如果已有 style 属性,替换为新的样式;如果没有,添加新的 style 属性
  38. return match.replace(/style="[^"]+"/gi,
  39. `style="border: 1px solid #ddd; padding: 8px; background-color: #f2f2f2;"`)
  40. .replace(/<table/gi,
  41. `<table style="border: 1px solid #ddd; padding: 8px; background-color: #f2f2f2;"`);
  42. });
  43. html = html.replace(/<td[^>]*>/gi, match => {
  44. // 如果已有 style 属性,替换为新的样式;如果没有,添加新的 style 属性
  45. return match.replace(/style="[^"]+"/gi,
  46. `style="border: 1px solid #ddd; padding: 8px;"`)
  47. .replace(/<table/gi,
  48. `<table style="border: 1px solid #ddd; padding: 8px;"`);
  49. });
  50. // 富文本内容格式化
  51. return html && html.replace(/<img[^>]*>/gi, function(match, capture) {
  52. // 查找所有的 img 元素
  53. return match.replace(/style=".*"/gi, '').replace(/style='.*'/gi,
  54. '')
  55. // 删除找到的所有 img 元素中的 style 属性
  56. }).replace(/\<img/gi, '<img style="width:100%;"') // 对 img 元素增加 style 属性,并设置宽度为 100%
  57. }
  58. },
  59. }
  60. }
  61. </script>
  62. <style lang="scss" scoped>
  63. .main {
  64. .one {
  65. padding: 2vw 4vw;
  66. .rich-img {
  67. width: 100% !important;
  68. display: block;
  69. }
  70. }
  71. }
  72. </style>