使用Js快速判断链接是否为外链
问题描述在vue中实现一个跳转功能,点击跳转到某个链接,当这个链接是该项目以外的链接时(也称外链),会报错,使用的方式是this.$router.push()报错截图如下所示:原因分析在项目中使用this.$router.(*)是不能实现跳转的,会报错,如果要跳转外链的话使用window.location.href.解决方案<template>```<div @click="to
·
问题描述
在vue中实现一个跳转功能,点击跳转到某个链接,当这个链接是该项目以外的链接时(也称外链),会报错,使用的方式是
this.$router.push()
报错截图如下所示:
原因分析
在项目中使用this.$router.(*)是不能实现跳转的,会报错,如果要跳转外链的话使用window.location.href
.
解决方案
<template>```
<div @click="toUrl">点击跳转</div>
</template>
、、、
methods: {
toUrl() {
//此处是传过来的地址 可以自己输入各种格式的地址进行检测
let url = "https://www.baidu.come";
//最快速的判断方法就是判断链接的协议 http/https
if (url.indexOf('https://') === 0 || url.indexOf('http://') === 0) {
window.location.href = url;
} else {
this.$router.push({
path: 'url',
});
}
}
}
}
获取Url
// 获取当前路径:
const getParamByUrl = (() => {
return new URL(location.href)
})
// url
// hash: ""
// host: "127.0.0.1:5500"
// hostname: "127.0.0.1"
// href: "http://127.0.0.1:5500/14-getUrl.html"
// origin: "http://127.0.0.1:5500"
// password: ""
// pathname: "/14-getUrl.html"
// port: "5500"
// protocol: "http:"
// search: ""
// searchParams: URLSearchParams {}
// username: ""
// [[Prototype]]: URL
console.log('host', getParamByUrl().host); // host 127.0.0.1:5500
console.log('port', getParamByUrl().port); // port 5500
更多推荐
已为社区贡献1条内容
所有评论(0)