The generateRandomIPAddress()
function creates an empty array ip
to store the four parts of the IP address. It then loops four times to generate a random number between 0 and 255 using the Math.random()
method and the Math.floor()
method. Each generated number is pushed into the ip
array. Finally, the function returns the joined string of the ip
array using the join()
method with a period (.
) as the separator.
we’ve added an isValidIPAddress()
method to validate the generated IP address. This method checks if the IP address has exactly 4 parts, and if each part is a valid number between 0 and 255.
If the generated IP address is valid, it is set as the value of the ipAddress
data property and displayed in the paragraph element. If the generated IP address is invalid, the generateRandomIPAddress()
method is called again recursively until a valid IP address is generated.
Vue Js Generate Random IP Address Example
<div id="app">
<button @click="generateRandomIPAddress">Generate</button>
<p v-if="ipAddress">{{ ipAddress }}</p>
<p v-else>Click "Generate" to generate a random IP address</p>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
ipAddress: "",
}
},
methods: {
generateRandomIPAddress() {
let ip = [];
for (let i = 0; i < 4; i++) {
ip.push(Math.floor(Math.random() * 256));
}
if (this.isValidIPAddress(ip)) {
this.ipAddress = ip.join(".");
} else {
this.generateRandomIPAddress();
}
},
isValidIPAddress(ip) {
if (ip.length !== 4) {
return false;
}
for (let i = 0; i < 4; i++) {
if (ip[i] < 0 || ip[i] > 255 || isNaN(ip[i])) {
return false;
}
}
return true;
},
},
});
app.mount('#app');
</script>