In this tutorial, we provide two examples to obtain the client‘s IP address using Vue.js. In the first example, we utilize the Options API, and in the second example, we employ the Composition API. In both examples, we utilize an external API, namely, ipify to get ip address.
How to get client IP address in Vue Js?
In the code below, we utilize Vue js options API to retrieve the IP address of the local machine. We use the Axios library to make an HTTP GET request to the ipify API endpoint. In the response, we obtain the user’s IP address
Vue Js Get Ip Address(Options Api)
<div id="app">
<p>Your IP address is: {{ ipAddress }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
ipAddress: null
}
},
mounted() {
axios
.get('https://api.ipify.org?format=json')
.then(response => {
this.ipAddress = response.data.ip;
})
.catch(error => {
console.log(error);
});
}
})
</script>
Output of above example
In this example, we used the Composition API of Vue.js, i.e., Vue 3, to achieve the same results as above.
Vue 3 Get Client Ip Address (Compositions Api)
<script type="module">
const {createApp,ref,onMounted} = Vue;
createApp({
setup() {
const ipAddress = ref(null);
onMounted(() => {
axios.get('https://api.ipify.org?format=json').then(response => {
ipAddress.value = response.data.ip;
}).catch(error => {
console.error(error);
});
});
return {
ipAddress
};
}
}).mount("#app");
</script>