赞
踩
data数据:
ipAddress: { ip: "", location: "", type: "" }
methods中的方法:
- getIpAddress() { //获取ip, 位置
- let year = new Date().getFullYear();
- fetch(`https://${year}.ip138.com/`).then(x => x.text()).then(h => {
- let domParser = new DOMParser();
- let doc = domParser.parseFromString(h, "text/html");
- let text = doc?.querySelector('p')?.innerText?.trim();
- console.log(text)//您的iP地址是:[xxx.xx.xxx.xxx ] 来自:中国上海xx xx
- try {
- let ip = text.substring(text.indexOf("[") + 1, text.indexOf("]")).trim();
- this.ipAddress.ip = ip;
- let other = text.substring(text.indexOf("来自:") + 3).trim();
- let arr = other.split(" ");
- this.ipAddress.location = arr[0];
- this.ipAddress.type = arr[1];
- } catch (e) {
- console.error(e)
- }
- })
- }
mounted:dom加载完成后调用
- mounted() { //dom加载完成后执行
- this.getIpAddress();
- console.log(this.ipAddress);//{ip: 'xxx.xx.xxx.xxx', location: '中国上海xx', type: 'xx'}
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。