HighlightNumberText.vue 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <template>
  2. <view class="content-container">
  3. <span v-for="(part, index) in formattedContent" :key="index"
  4. @click="handleClick(part)"
  5. :class="{'highlight-number': part.isNumber, 'phone-number': part.isPhone}">
  6. {{ part.text }}
  7. </span>
  8. </view>
  9. </template>
  10. <script>
  11. export default {
  12. name: 'HighlightNumber',
  13. props: {
  14. content: {
  15. type: String,
  16. required: true
  17. }
  18. },
  19. computed: {
  20. formattedContent() {
  21. const phoneRegex = /(1[3-9]\d{9})/g;
  22. const numberRegex = /(\d+)/g;
  23. let text = this.content;
  24. let result = [];
  25. let match;
  26. // Step 1: 提取手机号
  27. while ((match = phoneRegex.exec(text)) !== null) {
  28. if (match.index > 0) {
  29. const before = text.slice(0, match.index);
  30. result.push(...this.splitAndPush(before, false, false));
  31. }
  32. result.push({ text: match[0], isNumber: true, isPhone: true });
  33. text = text.slice(match.index + match[0].length);
  34. }
  35. // Step 2: 提取普通数字
  36. while ((match = numberRegex.exec(text)) !== null) {
  37. if (match.index > 0) {
  38. const before = text.slice(0, match.index);
  39. result.push(...this.splitAndPush(before, false, false));
  40. }
  41. result.push({ text: match[0], isNumber: true });
  42. text = text.slice(match.index + match[0].length);
  43. }
  44. // Step 3: 添加剩余文本
  45. if (text.length > 0) {
  46. result.push(...this.splitAndPush(text, false, false));
  47. }
  48. return result;
  49. }
  50. },
  51. methods: {
  52. splitAndPush(str, isNumber = false, isPhone = false) {
  53. return str.split('').map(char => ({ text: char, isNumber, isPhone }));
  54. },
  55. handleClick(part) {
  56. if (part.isPhone) {
  57. this.$emit('phone-click', { phoneNumber: part.text });
  58. } else if (part.isNumber) {
  59. this.$emit('number-click', { number: part.text });
  60. }
  61. }
  62. }
  63. };
  64. </script>
  65. <style scoped>
  66. .highlight-number {
  67. color: #ff5722;
  68. font-weight: bold;
  69. }
  70. .phone-number {
  71. color: #007AFF;
  72. text-decoration: underline;
  73. }
  74. </style>