vue3-链接自动识别

73 阅读1分钟

识别超链接正则记录 -vue3 trae体验

<template>
  <div>
    <div class="linkContainer bubble">
      <template v-for="(part, index) in parts" :key="index">
        <a v-if="isUrl(part)" :href="part" target="_blank" class="link" @click="openLink(part)">{{ part }}</a>
        <span v-else>{{ part }}</span>
      </template>
    </div>
    <div
      v-if="isBubbleVisible"
      class="bubble"
      :style="{ background: 'rgb(243, 243, 243)', 'border-radius': '4px' }"
    >
      <p>您好,系统打开成功。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, onMounted, computed, watch } from 'vue'

const isBubbleVisible = ref(false)
const props = defineProps({
  dialogData: Object //传入对话结果
})
console.log('子组件', props)
const openLink = () => {
  const newTab = window.open(props.url, '_blank')
  // 检查新标签页是否成功打开
  if (newTab) {
    isBubbleVisible.value = true
  } else {
    alert('无法打开新标签页,请检查您的浏览器设置。')
  }
}

const LinkUtils = {
  // 检查是否是有效的 URL
  isValidUrl(string) {
    try {
      new URL(string)
      return true
    } catch {
      return false
    }
  }, // 从文本中提取所有 URL

  extractUrls(text) {
    const urlRegex = /\((https?:\/\/[^\s)]+)\)/;

    return text.split(urlRegex)
  } // 从 HTML 中提取所有链接
}

console.log(LinkUtils.isValidUrl('https://example.com')) // true
console.log(LinkUtils.extractUrls('访问 https://example.com 和 https://google.com'))

const str = ref('')
const parts = ref([])
onMounted(() => {
const test={
    content:{
      texts:"好的,请点击下方链接获取",
      systemUrlText:"点击打开近两个月薪酬工资单",
      systemUrl:"https://www.baidu.com"
    }
}
  parts.value = LinkUtils.extractUrls(props.dialogData.content)
  console.log('5555555555555555555', LinkUtils.extractUrls(props.dialogData.content),parts.value)

})
const isUrl = (text) => {
  const urlPattern = /^https?:\/\/[^\s]+$/
  return urlPattern.test(text)
}

watch(
  () => props,
  (newVal) => {

    console.info(newVal, '00000')
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<style scoped>
.linkContainer {
  width: 100%;
  flex: 1;
  overflow: auto;
  /* display: flex; */
  word-break: break-all;
  line-height: 1.5;
}
.bubble {
  /* background: rgb(243, 243, 243); */
  border-radius: 4px;
  margin-bottom: 10px;
  border-radius: 5px;
  padding: 10px;
  max-width: 60rem;
  min-width: 18rem;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  line-height: 1.75;
  box-sizing: border-box;
  padding-left: 1.25rem;
  padding-right: 1.25rem;
  padding-top: 0.75rem;
  padding-bottom: 0.75rem;
  border-radius: 0.375rem;
}
.link {
  color: #1890ff; /* 设置链接颜色 */
  cursor: pointer;
  text-decoration: underline;
  min-width: 100px;
}
.linkContainer :deep(.auto-link) {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}
.linkContainer :deep(.auto-link:hover) {
  color: #40a9ff;
  text-decoration: underline;
}
</style>