具体代码
<template> <div class="ip">{{ Ip }}</div> </template> <script> export default { data() { return { Ip: "", }; }, methods: { // 获取ip地址 get(url, cb) { var httpRequest = new XMLHttpRequest(); httpRequest.open("GET", url, true); httpRequest.send(); httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var json = httpRequest.responseText; cb(json); } }; }, }, mounted() { // 调用接口获取ip地址 this.get("https://api.ipify.org/?format=json", (data) => { data = JSON.parse(data); this.Ip = data.ip; console.log("IP地址为", data.ip); }); }, }; </script> <style lang="scss" scoped></style>