使用Js快速判断链接是否为外链

问题描述

在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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值