There are plenty of color pickers available for Vue 2. However, when it comes to Vue 3, choices are a bit limited because it is not as old yet.
Fortunately, with Vue 3’s growing user base and more and more people migrating to Vue 3 from 2, we see more options coming up. Here in this example, we’ll have a look at how we can add a color picker to our Vue 3 app without using the browser’s default color picker.
First of all, run the following command to install the required library:
npm i @lk77/vue3-color
Code language: CSS (css)
Once it’s installed, we can now use it.
The library comes up with 7 color pickers (including 2 swatches).
It even comes with a slider picker which doesn’t allow users to choose complete light (white) or complete dark (black) values.
Here’s the implementation showing all the available color pickers:
<template>
<div>
<div v-if="colors && Object.keys(colors).length !== 0" class="color-values">
<h4>Color values:</h4>
<p>{{ colors ? colors : "" }}</p>
</div>
<photoshop-picker v-model="colors" class="np-mb" />
<compact-picker v-model="colors" class="np-mb" />
<swatches-picker v-model="colors" class="np-mb" />
<slider-picker v-model="colors" class="np-mb" />
<sketch-picker v-model="colors" class="np-mb" />
<chrome-picker v-model="colors" class="np-mb" />
<material-picker v-model="colors" class="np-mb" />
</div>
</template>
<script>
import {
Photoshop,
Material,
Compact,
Swatches,
Slider,
Sketch,
Chrome,
} from "@lk77/vue3-color";
export default {
name: "App",
data() {
return {
colors: {},
};
},
components: {
"material-picker": Material,
"compact-picker": Compact,
"swatches-picker": Swatches,
"slider-picker": Slider,
"sketch-picker": Sketch,
"chrome-picker": Chrome,
"photoshop-picker": Photoshop,
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.color-values {
background: rgb(234, 226, 255);
padding: 4px;
max-width: 500px;
margin: 0 0 30px 0;
border: 1px solid rgb(76, 0, 255);
min-height: 150px;
}
.np-mb {
margin-bottom: 20px;
}
.color-values p {
font-size: 14px;
}
</style>
Code language: HTML, XML (xml)
In the above file, we’ve imported all the components and mapped them with the names we wanted through lines 34-42.
We’re using a reactive state named colors with default value {} (empty object).
Here’s what the above code would look like in action:
You can find a working version of the above code from my repo links below: