[TOC]
代码示例1
1. 拦截a链接变成JS代码处理
Vue3 组件中用 v-html
渲染富文本,里面可能有 <a href="xxx">
链接。问题是:
v-html
渲染的内容是「静态 HTML」,Vue 不会帮你自动绑定事件。- 所以点
<a>
默认就是直接跳转。
👉 要解决:需要在组件里用 事件代理 或者 手动绑定事件 来拦截 <a>
点击,再调用 Vue 方法。<a>
链接里可能有参数(比如 query string),点击时拦截,解析参数,用参数做逻辑处理。
<template>
<div ref="contentRef" v-html="htmlContent"></div>
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
const htmlContent = `
<p>点我看看效果:
<a href="https://example.com/page?userId=123&action=edit">自定义跳转</a>
</p>
`
const contentRef = ref<HTMLElement | null>(null)
function handleLinkClick(e: Event) {
const target = e.target as HTMLElement
if (target.tagName.toLowerCase() === 'a') {
e.preventDefault() // 阻止默认跳转
const href = (target as HTMLAnchorElement).href
if (href) {
try {
// 用 URL API 解析参数
const url = new URL(href)
const userId = url.searchParams.get('userId')
const action = url.searchParams.get('action')
console.log('拦截到链接:', href)
console.log('参数 userId:', userId)
console.log('参数 action:', action)
// TODO: 这里写自定义处理逻辑
alert(`处理参数:userId=${userId}, action=${action}`)
} catch (err) {
console.error('URL 解析失败:', err)
}
}
}
}
onMounted(() => {
contentRef.value?.addEventListener('click', handleLinkClick)
})
onBeforeUnmount(() => {
contentRef.value?.removeEventListener('click', handleLinkClick)
})
</script>