Vue.js is extremely powerful when it comes to quick dynamic style binding. And therefore, you can generate a random RGB color using Vue.js without using any 3rd party library or tool. I’ve personally used it on numerous occasions and find it really useful.
Most of the RGB color generates you’ll find online are prone to invalid color generation at some point. Either invalid RGB color value, or too short color length (like #FFF instead of #FFFFFF for white). While this is not a problem for most of the cases but in case your server isn’t made to handle such situations, it can create a havoc. To prevent that, here I’m showing a way to generate unique, random, valid, 7 digit RGB color codes only.
<template>
<div id="app">
<div :style="{ backgroundColor: randomColor }" class="np-color-preview">
NightProgrammer.com
</div>
<button @click="getRandomColor" class="np-btn">
Generate random color
</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
randomColor: "#ff0000",
};
},
methods: {
getRandomColor() {
this.randomColor = this.generateRandomHexColor();
},
generateRandomHexColor() {
const randomColor =
"#" + Math.floor(Math.random() * 16777215).toString(16);
if (randomColor.length !== 7) {
return this.generateRandomHexColor();
} else {
return randomColor;
}
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.np-color-preview {
height: 200px;
width: 200px;
padding: 6px;
border-radius: 4px;
color: #fff;
}
.np-btn {
margin-top: 12px;
background: #eee;
border: 0px;
padding: 6px 10px;
border-radius: 4px;
background: rgb(0, 70, 201);
color: #fff;
cursor: pointer;
}
</style>
Code language: HTML, XML (xml)
In the code above, whenever you click on “Generate random color”, the getRandomColor method gets invoked. It then calls the generateRandomHexColor method and returns a valid RGB color. It’s worth noting that the method generateRandomHexColor won’t return a value if it’s not 7 digits in length. This is prevented by the if check on line 27. This is because there’s a slight chance of not getting a 7 digits color, in such case it’ll recursively call the method until you get one.
You can find a working version of the above code from my repos below: