Implementing a progress indicator for long-running tasks in Vue.js involves creating a component or using a library to handle the UI part and managing the state of the progress. Below, I'll provide a simple example using a custom component and a Vuex store for state management.
bashnpm install vuex
Create a file named store.js
:
javascript// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
progress: 0,
isTaskRunning: false,
},
mutations: {
setProgress(state, value) {
state.progress = value;
},
setTaskRunning(state, value) {
state.isTaskRunning = value;
},
},
});
Create a file named ProgressIndicator.vue
:
html<!-- ProgressIndicator.vue -->
<template>
<div v-if="isTaskRunning">
<p>Task in progress...</p>
<div class="progress-bar">
<div :style="{ width: progress + '%' }"></div>
</div>
</div>
</template>
<script>
export default {
computed: {
progress() {
return this.$store.state.progress;
},
isTaskRunning() {
return this.$store.state.isTaskRunning;
},
},
};
</script>
<style scoped>
.progress-bar {
width: 100%;
height: 20px;
background-color: #f0f0f0;
margin-top: 10px;
position: relative;
}
.progress-bar div {
height: 100%;
background-color: #4caf50;
}
</style>
html<!-- YourComponent.vue -->
<template>
<div>
<!-- Your component content -->
<progress-indicator></progress-indicator>
</div>
</template>
<script>
import ProgressIndicator from './ProgressIndicator.vue';
export default {
components: {
ProgressIndicator,
},
methods: {
async startLongRunningTask() {
this.$store.commit('setTaskRunning', true);
for (let i = 0; i <= 100; i++) {
// Simulate a long-running task
await this.sleep(50);
this.$store.commit('setProgress', i);
}
this.$store.commit('setTaskRunning', false);
this.$store.commit('setProgress', 0);
},
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
},
},
};
</script>
javascript// main.js
import Vue from 'vue';
import App from './App.vue';
import store from './store';
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
store,
}).$mount('#app');
Now, when you call startLongRunningTask
in your component, the progress indicator will be displayed, and the progress will be updated as the task progresses. Adjust the code as needed based on your specific requirements and styling preferences.