Nuxt.js中SMS链接被识别为Nuxt路由问题求助
解决Nuxt中SMS链接被路由拦截的问题
问题核心是Nuxt默认会拦截所有<a>标签的点击事件,将其当作内部路由处理,导致原生SMS协议链接无法唤起系统短信应用,反而触发“路由未找到”错误。以下是针对性解决方法:
方法一:添加target="_blank"属性
直接给<a>标签加上target="_blank"和rel="noopener noreferrer",让Nuxt识别为外部链接,不进行路由拦截:
<a href="sms:+12223334444?body=hello%20world%21" target="_blank" rel="noopener noreferrer">Send SMS</a>
移动端点击后会直接唤起短信应用,不会打开新窗口,这个方法简单高效。
方法二:自定义指令拦截点击事件(适配Nuxt 2/3)
如果不想用target="_blank",可以通过自定义指令让浏览器原生处理SMS链接:
Nuxt 3 实现
- 在项目
plugins目录下创建external-protocols.js文件,内容如下:
export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.directive('native-link', { mounted(el) { el.addEventListener('click', (e) => { const href = el.getAttribute('href') // 匹配sms、tel、mailto等原生协议 if (href?.startsWith('sms:') || href?.startsWith('tel:') || href?.startsWith('mailto:')) { e.preventDefault() window.location.href = href } }) } }) })
- 在模板中使用该指令:
<a href="sms:+12223334444?body=hello%20world%21" v-native-link>Send SMS</a>
Nuxt 2 实现
- 在
nuxt.config.js中添加全局指令配置:
export default { plugins: ['~/plugins/external-protocols.js'] }
- 创建
plugins/external-protocols.js:
export default ({ app }) => { app.directive('native-link', { bind(el) { el.addEventListener('click', (e) => { const href = el.getAttribute('href') if (href?.startsWith('sms:')) { e.preventDefault() window.location.href = href } }) } }) }
- 模板中使用方式和Nuxt 3一致。
方法三:手动触发链接跳转
给<a>标签添加点击事件,手动调用window.location.href跳转:
<a href="sms:+12223334444?body=hello%20world%21" @click.prevent="openSMS">Send SMS</a>
在组件中实现对应方法:
// Nuxt 2 methods: { openSMS(e) { window.location.href = e.currentTarget.href } } // Nuxt 3(使用<script setup>) const openSMS = (e) => { window.location.href = e.currentTarget.href }
额外提示
- iOS系统中,SMS链接的
body参数需要用&分隔(而非?),可以做兼容处理:const getSMSUrl = (phone, body) => { const encodedBody = encodeURIComponent(body) return /iPad|iPhone|iPod/.test(navigator.userAgent) ? `sms:${phone}&body=${encodedBody}` : `sms:${phone}?body=${encodedBody}` }
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

