index.vue 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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,
  34. `style="border-collapse: collapse; width: 100%;text-align: center;"`)
  35. .replace(/<table/gi,
  36. `<table style="border-collapse: collapse; width: 100%;text-align: center;"`);
  37. });
  38. html = html.replace(/<th[^>]*>/gi, match => {
  39. // 如果已有 style 属性,替换为新的样式;如果没有,添加新的 style 属性
  40. return match.replace(/style="[^"]+"/gi,
  41. `style="border: 1px solid #ddd; padding: 8px; background-color: #f2f2f2;text-align: center;"`
  42. )
  43. .replace(/<table/gi,
  44. `<table style="border: 1px solid #ddd; padding: 8px; background-color: #f2f2f2;text-align: center;"`
  45. );
  46. });
  47. html = html.replace(/<td[^>]*>/gi, match => {
  48. // 如果已有 style 属性,替换为新的样式;如果没有,添加新的 style 属性
  49. return match.replace(/style="[^"]+"/gi,
  50. `style="border: 1px solid #ddd; padding: 8px;text-align: center;"`)
  51. .replace(/<table/gi,
  52. `<table style="border: 1px solid #ddd; padding: 8px;text-align: center;"`);
  53. });
  54. // 富文本内容格式化
  55. return html && html.replace(/<img[^>]*>/gi, function(match, capture) {
  56. // 查找所有的 img 元素
  57. return match.replace(/style=".*"/gi, '').replace(/style='.*'/gi,
  58. '')
  59. // 删除找到的所有 img 元素中的 style 属性
  60. }).replace(/\<img/gi, '<img style="width:100%;"') // 对 img 元素增加 style 属性,并设置宽度为 100%
  61. }
  62. },
  63. }
  64. }
  65. </script>
  66. <style lang="scss" scoped>
  67. .main {
  68. .one {
  69. padding: 2vw 4vw;
  70. .rich-img {
  71. width: 100% !important;
  72. display: block;
  73. }
  74. }
  75. }
  76. </style>