自动生成链接
最近做项目遇到了一个需求就是需要根据后台传的关键字和地址自动去生成链接,但是我的项目是服务器端渲染的,所有页面内容都是不固定的,等于是后台传什么数据我就根据他传的数据去决定渲染什么组件啊,那这根据不可能去依赖v-html,而且v-html本身就有很多的弊端啊,所以我在查看了很多自动生成链接的组件之后,决定自己封装一个生成链接的组件,下面是我的组件的内容啊
<template><span><template v-for="(part, index) in parts" :key="index"><NuxtLinkv-if="keywordLinks[part]":to="keywordLinks[part]"class="text-[var(--text-link-color-primary)] cursor-pointer"target="_blank">{{ part }}</NuxtLink><span v-else>{{ part }}</span></template></span>
</template><script setup>
const props = defineProps({text: String,keywordLinks: {type: Object,default: () => ({})}
})// 存储所有匹配:{ text: keyword, link, index, length }
const matches = []// 对每个关键词构造带单词边界的正则,查找第一次完整词匹配
for (const [keyword, link] of Object.entries(props.keywordLinks)) {// 转义关键词中的特殊字符(防止如 '.'、'+' 等破坏正则)const escapedKeyword = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')// 使用单词边界 \b,确保是完整词匹配const regex = new RegExp(`\\b${escapedKeyword}\\b`, 'i') // i 表示不区分大小写(可选)const match = regex.exec(props.text)if (match) {matches.push({text: keyword, // 原样保留关键词用于后续比对link: link,index: match.index,length: match[0].length})}
}// 按照在原文中出现的位置排序(保证顺序正确)
matches.sort((a, b) => a.index - b.index)// 构建 parts:按原始顺序切分文本
const parts = []
let lastIndex = 0matches.forEach(match => {// 添加匹配前的普通文本if (match.index > lastIndex) {parts.push(props.text.slice(lastIndex, match.index))}// 添加关键词本身(后续模板中会判断是否为链接)parts.push(match.text)lastIndex = match.index + match.length
})// 添加最后剩余的文本
if (lastIndex < props.text?.length) {parts.push(props.text.slice(lastIndex))
}
</script>
<style scoped></style>
这个组件呢会根据接受的关键词和文字去匹配,如果匹配到了就给他提出来,方便渲染的时候判断是否生成链接,他这个匹配的规则是把关键词当做一个整体去全部匹配,如果遇到了多个匹配结果支取第一个,并且英文单词不能拆开匹配,下面是一个使用的例子:
//这里只展示关键部分的代码,看得懂就行<AutoLinkText :text="text" :keywordLinks="keywordLinks"></AutoLinkText>const keywordLinks = {"perfectly responds": "https://www.baidu.com","Mobile": "https://www.baidu.com","a": "https://www.baidu.com"
}const text = "Mobile conveyor belt bridges do precisely what their name suggests. These portable conveyor systems flexibly bridge the gap between the excavation site and the bench conveyors. Their modular design makes them indispensable on-site; they increase the miners’ operating range and connect bench conveyors of different heights."
下面就是效果,蓝色部分就是添加了链接的部分
有类似需求的小伙伴可以参考一下