不能用过滤器直接转,因uni-app小程序禁用v-html,filters仅输出纯文本字符串,无法生成可交互的标签;需nodes数组而非html字符串,且不执行js或解析事件。

不能用过滤器直接转。uni-app 的 v-html 在小程序平台被禁用,filters 仅作用于插值表达式(如 {{ text | linkify }}),但输出仍是纯文本,无法生成可交互的 @#@#@#@#@#@#@#@#@#@0 进去,它只会当普通文本渲染,点不动,也没回调。
- Vue 2 的
filters在 Vue 3 中已被移除,uni-app 新项目多基于 Vue 3,语法不兼容 - 即使 Vue 2 项目中用了过滤器,输出的字符串也无法被
<rich-text></rich-text>正确识别为可点击节点 - 过滤器无法注入
data-属性或绑定事件处理器,而@itemclick依赖这些属性做路由分发
正确做法:用正则提取 + 构造 nodes 数组
后端返回的纯文本(如 "快看这个 https://example.com 和 @张三")必须在 JS 层解析,生成符合 <rich-text></rich-text> 规范的 nodes 数组,每个链接节点带可识别的 attrs。
- 用
urlRegex(推荐https?:\/\/[^\s]+)匹配 URL,注意排除末尾标点(如句号、逗号) - 对匹配到的链接,构造
{ name: 'a', attrs: { 'data-href': matchedUrl }, children: [{ type: 'text', text: matchedUrl }] } - 非链接文本用
{ name: 'span', children: [{ type: 'text', text: plainText }] }包裹,避免被误判为节点根 - 顺序拼接所有节点,确保
nodes是扁平一维数组,不能嵌套
示例片段:
parseLinks(text) {
const nodes = [];
let lastIndex = 0;
const urlRegex = /https?:\/\/[^\s\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]+/g;
text.replace(urlRegex, (match, index) => {
if (index > lastIndex) {
nodes.push({
name: 'span',
children: [{ type: 'text', text: text.slice(lastIndex, index) }]
});
}
nodes.push({
name: 'a',
attrs: { 'data-href': match },
children: [{ type: 'text', text: match }]
});
lastIndex = index + match.length;
});
if (lastIndex
<h3>@itemclick 里怎么安全跳转外部链接</h3>
<p><code>@itemclick</code> 触发时,必须根据平台分发跳转逻辑,不能统一用 <code>uni.navigateTo</code> —— 它对非页面路径无效,且微信小程序会直接报错。</p>
- 先通过
e.detail.nodes[e.detail.tapIndex]拿到被点击节点,再读node.attrs['data-href'] - 判断平台:
uni.getSystemInfoSync().platform返回'mp-weixin'、'h5'、'app' - 微信小程序:必须跳转到内置
<web-view></web-view>页面,且目标域名已配置业务域名 - H5:优先用
window.open(url, '_blank'),避免整页刷新;含中文需encodeURIComponent - App:调用
plus.runtime.openURL(url),不支持web-view标签 - 跳转前务必校验 URL 是否以
http或https开头,防止 XSS 或非法协议
容易被忽略的三个细节
很多开发者卡在“能解析但点不动”或“点得动但跳错”,问题往往出在这些地方:
-
<rich-text></rich-text>必须设置固定高度或min-height,否则 iOS 小程序可能不触发@itemclick - 节点中
name: 'a'的children必须是type: 'text'对象,不能是字符串,否则 H5 端渲染异常 - 微信小程序里,如果链接文本包含 emoji 或全角符号,正则可能截断,建议用
[\s\S]替代.并加u标志处理 Unicode











