Loaders and progress bars are probably some of the most important components of any web application. Creating and showing a loader while some content is being loaded is pretty easy in Vue.js. All we have to do is create an animated loader using CSS and toggle its visibility depending on the situation. We can head over to loading.io to get some of the most popular pure CSS loaders. Once we have the CSS code, we can then inject it into a component to build a loader. Here’s the component I’ve built for the same:
<template>
<div>
<div class="loader"></div>
</div>
</template>
<script>
export default {
name: "Loader",
};
</script>
<style>
.loader {
display: inline-block;
width: 64px;
height: 64px;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
.loader:after {
content: " ";
display: block;
width: 40px;
height: 40px;
margin: 8px;
border-radius: 50%;
border: 6px solid #fff;
border-color: #2e2e2e transparent #2e2e2e transparent;
animation: loader 0.7s linear infinite;
}
@keyframes loader {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
Code language: HTML, XML (xml)
Once we have the loader, we can import it into a component we want to use. Here’s my App.vue file using the above loader:
<template>
<div id="app">
<div class="np-content">
<div v-if="isLoading">
<Loader />
</div>
<div v-else>
<div class="np-loader-btn">
<button @click="toggleLoader">Show loader</button>
</div>
</div>
</div>
</div>
</template>
<script>
import Loader from "./Loader";
export default {
name: "App",
data() {
return {
isLoading: false,
};
},
components: {
Loader,
},
methods: {
toggleLoader() {
this.isLoading = true;
setTimeout(() => {
this.isLoading = false;
}, 2000);
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
padding: 24px;
}
.np-content {
height: 300px;
width: 400px;
background: #eee;
position: relative;
}
button {
background-color: #004cbe;
color: #ffffff;
border: 0px;
border-radius: 6px;
padding: 6px 20px;
margin-right: 1em;
cursor: pointer;
transition: all 0.3s;
}
button:hover {
background-color: #2f79e7;
transition: all 0.3s;
}
.np-loader-btn {
padding: 16px;
}
</style>
Code language: HTML, XML (xml)
You can find a working demo of the above example from my repos below: