Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Created June 26, 2019 23:23
Show Gist options
  • Save matthewoestreich/5353e2086c361b521aeb6e498aed70dd to your computer and use it in GitHub Desktop.
Save matthewoestreich/5353e2086c361b521aeb6e498aed70dd to your computer and use it in GitHub Desktop.
Vue - get public IP and Latitude - separate components
<div id="app">
<div>
<current-ip @ip-changed="$set(ips, 'first', $event)"></current-ip>
<current-latitude :ip="ips['first']"></current-latitude>
<hr />
<current-ip
ip="4.2.2.2"
@ip-changed="$set(ips, 'second', $event)"></current-ip>
<current-latitude :ip="ips['second']"></current-latitude>
</div>
</div>
<!-- SIMULATES TEMPLATE FOR CurrentIp -->
<template id="current-ip">
<div>
<p>Hello, your ip is <h1>{{ ipAddress }}</h1></p>
</div>
</template>
<!-- SIMULATES TEMPLATE FOR CurrentLatitude -->
<template id="current-latitude">
<div>
<p>and your latitude is <h1>{{ latitude }}</h1></p>
</div>
</template>
// Simulates a mixin
const ipHelper = {
methods: {
isIpAddress(ip) {
return /^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/.test(ip);
}
}
};
// Simulates current-ip Component
const currentIp = {
template: "#current-ip",
props: {
ip: {
type: String,
required: false,
default: null
}
},
data() {
return {
ipAddress: "...loading..."
};
},
watch: {
ipAddress() {
this.$emit("ip-changed", this.ipAddress);
}
},
methods: {
getCurrentIp() {
fetch("https://api.ipify.org?format=json")
.then(response => {
return response.json();
})
.then(res => {
this.ipAddress = res.ip;
})
.catch(err => {
this.ipAddress = "We encountered an error, check your console!";
});
}
},
mounted() {
if (!this.ip) {
this.getCurrentIp();
} else {
this.ipAddress = this.ip;
}
}
};
// Simulates current-latitude Component
const currentLatitude = {
template: "#current-latitude",
props: ["ip"],
data() {
return {
latitude: "....loading...."
};
},
watch: {
ip() {
this.getCurrentLatitude();
}
},
mixins: [ipHelper],
methods: {
getCurrentLatitude() {
if (this.isIpAddress(this.ip)) {
fetch(`https://ipapi.co/${this.ip}/json/`)
.then(response => {
return response.json();
})
.then(res => {
console.log(res);
this.latitude = res.latitude;
})
.catch(err => {
this.latitude = "We encountered an error, check your console!";
});
} else {
this.latitude = "Hmm... can't find that...";
}
}
}
};
// Main Vue app
const vueCore = {
el: "#app",
data: {
ips: {}
},
components: {
currentIp,
currentLatitude
}
};
new Vue(vueCore);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
h1 {
color: blue;
margin: 0 0 0 0 !important;
}
p {
margin: 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment