data() {
return {
ipAddress: { ip: "", location: "", type: "" },
}
},
mounted() {
this.getIpAddress();
console.log(this.ipAddress);//{ip: 'xxx.xx.xxx.xxx', location: '中国上海xx', type: 'xx'}
},
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)
}
})
},
}