Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a background color switcher app with Vue 3 and JavaScript.
Create the Project
We can create the Vue project with Vue CLI.
To install it, we run:
npm install -g @vue/cli
with NPM or:
yarn global add @vue/cli
with Yarn.
Then we run:
vue create background-switcher
and select all the default options to create the project.
Create the Background Color Switcher App
To create the background color switcher app, we create 4 circles.
When we click on a circle, the background color switches to the background color of the circle we clicked on.
To do this, we write:
<template>
<div id="screen" :style="{ 'background-color': backgroundColor }">
<div
v-for="c of colors"
:key="c"
:style="{
'background-color': c,
}"
class="circle"
@click="backgroundColor = c"
></div>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
colors: ["red", "green", "blue", "yellow"],
backgroundColor: undefined,
};
},
methods: {},
};
</script>
<style>
.circle {
border-radius: 50%;
width: 50px;
height: 50px;
border: 1px solid black;
display: inline-block;
cursor: pointer;
}
#screen {
width: 100vw;
height: 100vh;
}
</style>
We have the colors
reactive property array that we use to render into circles with v-for
in the template.
We set the background color each circle with the style
prop.
The key
prop is set to the color, which is the unique ID of the array.
We add a click listener to each circle to set the backgroundColor
to the color c
.
The div with ID screen
is has the style
prop to set the background-color
CSS property to the backgroundColkor
reactive property.
In the style tag, we make the divs with class circle
circles by setting the border-radius
to 50%.
Width and height are set to 50px.
border
is set to a black border 1px thick.
display
is set to inline-block
to make the divs display side by side.
cursor
is set to pointer
so that we see the hand when we hover over the div.
Now when we click on the circles, we see the color changes as we click on the circle.
Conclusion
We can create a background color switcher app easily with Vue 3 and JavaScript.