1.代码中获得ip
首先在data里添加一个ip为空
data() {
return {
ip: ''
};
}
然后在methods里面写上
getUserIP(onNewIP) {
let MyPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
let pc = new MyPeerConnection({
iceServers: []
});
let noop = () => {
};
let localIPs = {};
let ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
let iterateIP = (ip) => {
if (!localIPs[ip]) onNewIP(ip);
localIPs[ip] = true;
};
pc.createDataChannel('');
pc.createOffer().then((sdp) => {
sdp.sdp.split('\n').forEach(function (line) {
if (line.indexOf('candidate') < 0) return;
line.match(ipRegex).forEach(iterateIP);
});
pc.setLocalDescription(sdp, noop, noop);
}).catch((reason) => {
});
pc.onicecandidate = (ice) => {
if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
};
}
最后在mounted里面调用在methods里面的那个方法getUserIP()
this.getUserIP((ip) => {
this.ip = ip;
});
这样this.ip就是用户当前的ip地址了
对了,有的浏览器获取到的是IPv4地址,有的是IPv6地址
2.vue配置文件vue.config.js获取本地ip
方法一
在config/index.js 顶部添加
const os = require('os')
let localhost = ''
try {
const network = os.networkInterfaces()
localhost = network[Object.keys(network)[0]][1].address
} catch (e) {
localhost = 'localhost';
}
再找到host将其改为host:localhost即可
效果代码查看:https://github.com/dongkelun/vue-echarts-map/blob/autopip-v1/config/index.js
方法二
安装address
npm i address -D
在config/index.js
const address = require('address')
const localhost = address.ip() || 'localhost'
再找到host将其改为host:localhost即可