cwg-rich-text.vue 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <template>
  2. <rich-text :nodes="props.nodes" @itemclick="handleTap" />
  3. </template>
  4. <script setup lang="ts">
  5. import { computed, defineProps } from 'vue'
  6. const props = defineProps({
  7. nodes: {
  8. type: String,
  9. default: ''
  10. }
  11. })
  12. // 🔥 核心:保留原有 a 标签样式 + 增加 data-href 实现点击
  13. const formattedNodes = computed(() => {
  14. let html = props.nodes || ''
  15. // if (!html) return ''
  16. // // 替换 a 标签 → 保留所有原有样式,只加 data-href + cursor
  17. // html = html.replace(
  18. // /<a([^>]+)>(.*?)<\/a>/gi,
  19. // (match, attr, text) => {
  20. // return `<span${attr} data-href="${getHref(attr)}" style="cursor:pointer;">${text}</span>`
  21. // }
  22. // )
  23. return html
  24. })
  25. // 从 a 标签属性里提取 href
  26. function getHref(attr: string) {
  27. const match = attr.match(/href\s*=\s*["']([^"']+)["']/i)
  28. return match ? match[1] : ''
  29. }
  30. // 点击跳转逻辑
  31. const handleTap = (e) => {
  32. const href = e?.detail?.node?.attrs?.href
  33. if (!href) return
  34. // #ifdef H5
  35. window.open(href, '_blank')
  36. // #endif
  37. // #ifdef APP-PLUS
  38. if (href.startsWith('http')) {
  39. plus.runtime.openURL(href)
  40. } else {
  41. uni.navigateTo({ url: href })
  42. }
  43. // #endif
  44. }
  45. </script>
  46. <style scoped>
  47. /* 无需额外样式 */
  48. </style>