I have a simple problem.
I'm using Vue3 with vite, typescript and router, and I can't figure out, how to trigger a loading screen whilst the user clicks on router paths.
I successfully understood and implemented that within the router/index.ts, I can call a router.beforeEach, in which I can toggle a variable. Called it isLoading, and put a timeout delay before another route is rendered, it looks as follows:
var isLoading = false
router.beforeEach((to, from, next) =>{
console.log("beforeach");
isLoading = true
console.log(isLoading)
setTimeout(() => {
next();
}, 2000);
});
router.afterEach((to, from) => {
console.log("aftereach");
var isLoading = false
console.log(isLoading)
});
In my App.vue, I have a Preloader component imported from my views folder, which contains a simple div with some styling, and I want this component to get a class on beforeEach, and that class to be gone on afterEach.
But I have no idea, how to acquire the state of isLoading from my router/index.ts, or, if there is another way purely within App.vue that could trigger a class to my PreLoader component.
Thanks for your help!
Tried to use beforeEach and afterEach with a delay within router/index.ts, but don't know how to export the state of isLoading to App.vue.
The following two approaches can help you-
1. Using event bus-
Here you can read- How to use event buses in vue3.
2. Using Vuex-
showLoaderin the Vuex state.Here you can read- How to set up Vuex in vue3.
NOTE-
I only provided the logical code, syntax would be different when you use any of the above approaches.