Accessing app inside beforeRouteEnter - vue.js

I'd like to show some loading animation in the app root while a component prepares to be rendered by vue router.
Already found this question, proposing the use of navigation guards, and another question, where the accepted answer shows how to use the beforeEach guard to set a variable in app, showing a loading animation.
The problem is that this doesn't work when deep-linking to some route (initial url includes a route path, such as 'someurl#/foo'). The beforeEach guard simply doesn't get called then.
So i switched to the loaded component's beforeRouteEnter guard, which would also allow me to show the loading animation for some components only:
app:
var app = new Vue({
el: '#app',
data: { loading: false }
router: router
});
component:
var Foo = {
template: '<div>bar</div>',
beforeRouteEnter: function(to, from, next) {
app.loading = true; // 'app' unavailable when deep-linking
// do some loading here before calling next()...
next();
}
}
But then i found that when deep-linking to the component, app isn't available in beforeRouteEnter, as it gets called very early in the initialisation process.
I don't want to set loading to true inside the app data declaration, as i might decide at some point to deep-link to another route, whose component doesn't need a loading animation.

I believe, your solution is correct. However, I would suggest using next() function instead. As written in vue-router docs.
https://router.vuejs.org/en/advanced/navigation-guards.html
The beforeRouteEnter guard does NOT have access to this, because the guard is called before the navigation is confirmed, thus the new entering component has not even been created yet.
However, you can access the instance by passing a callback to next. The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument:
beforeRouteEnter (to, from, next) {
next(vm => {
vm.$root.loading = true;
})
}

Found a workaround using Vue.nextTick:
beforeRouteEnter: function(to, from, next) {
Vue.nextTick(function(){
// now app is available
app.loading = true;
// some loading to happen here...
seTimeout(function(){
app.loading = false;
next();
}, 1000);
})
}
Feels a little hacky, so would be thankful for other suggestions.
Find a demo of this solution here:
https://s.codepen.io/schellmax/debug/aYvXqx/GnrnbVPBXezr#/foo

What about using beforeRouteLeave to trigger the loading then have the component toggle it off in mounted.
For the initial load of the app you could have
app:
var app = new Vue({
el: '#app',
data() => ({ loading: true }),
mounted() { this.loading: false },
router: router
});
then for your components
component:
var Foo = {
template: '<div>bar</div>',
mounted() {
app.loading = false;
},
beforeRouteLeave(to, from , next) {
switch(to){
case COMPONENT_TO_SHOW_LOADING_ON:
case OTHER_COMPONENT:
app.loading = true;
default:
}
}
}

Related

Make vue router stay on same page if condition is not met

Im working on a vue app and I navigate through pages with vue router from the different page views, I want to set up vue router in a way where it would push a route if there is no error and stay on the same view/route if there is one. I have the following code that succeeds but I'm unsure if that is the best way to do it, and afraid it may cause bugs:
login() {
this.$store
.dispatch("method", {})
.then(() => {
if (!this.error) {
this.$router.push({ name: "nextPage" });
} else {
this.$router.push({ name: "samePage" });
}
});
}

Vue router : run beforeEach after fetching data

I'm working on a webapp with authentication (cookie based). While the app is loading (fetching global settings and checking if a user is logged in) I want to show a loading state. Otherwise the actual route may be shown.
To check if a user has access to a certain route I'm using vue-router beforeEach function
router.beforeEach((to, _, next) => {
const isLoggedIn = store.getters["auth/isLoggedIn"];
console.log(`Is user logged in?: ${isLoggedIn}`);
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth);
const requiresGuest = to.matched.some(
(record) => record.meta.redirectIfLoggedIn
);
if (requiresAuth && !isLoggedIn) {
next("/login");
} else if (requiresGuest && isLoggedIn) {
next("/");
} else {
next();
}
});
export default router;
The fetch requests are being done in the created function of App.vue
<template>
<Loader v-if="isLoading" />
<component v-else :is="this.$route.meta.layout">
<router-view />
</component>
</template>
<script>
import Loader from "#/components/general/Loader.vue";
export default {
data() {
return {
isLoading: true,
};
},
components: {
Loader,
},
async created() {
await this.$store.dispatch("settings/loadSettings");
await this.$store.dispatch("auth/tryLogin");
this.isLoading = false;
},
};
</script>
The problem I'm facing is that the beforeEach function is running before the fetching is done so isLoggedIn is always false. What can I do to make sure the fetch requests are completely finished before going into the beforeEach middleware?
Console log of the actions:
1) Settings before loading: {"logo_url":null,"background_color":"#089dde","text_color":"#ffffff"}
2) loading settings
3) Is user logged in?: false
4) Settings after loading: {"logo_url":null,"background_color":"#089dde","text_color":"#ffffff"}
5) User before loading: null
6) loading user
7) User after loading: {"id":1,"name":"John Doe","email":"johndoe#company.com"}
I've put some code with a fake fetch request in a codesandbox project. https://codesandbox.io/s/elegant-agnesi-399z5
Initial navigation occurs in Vue router before the application is initialized. Since a store is available outside Vue application instance, this can solved by initializing the state prior to application initialization. In this case a loader needs to be moved from Vue application to HTML file, this also allows to show it as soon as possible.
Alternatively, initial navigation can be postponed until the application is fully initialized. App component can interact with router in any way, but there should be a promise that will prevent beforeEach from proceeding further:
export let start;
const startPromise = resolve => { start = resolve };
router.beforeEach(async (to, _, next) => {
await startPromise;
...
and
await this.$store.dispatch("settings/loadSettings");
await this.$store.dispatch("auth/tryLogin");
start();

Vue test-utils how to test a router.push()

In my component , I have a method which will execute a router.push()
import router from "#/router";
// ...
export default {
// ...
methods: {
closeAlert: function() {
if (this.msgTypeContactForm == "success") {
router.push("/home");
} else {
return;
}
},
// ....
}
}
I want to test it...
I wrote the following specs..
it("should ... go to home page", async () => {
// given
const $route = {
name: "home"
},
options = {
...
mocks: {
$route
}
};
wrapper = mount(ContactForm, options);
const closeBtn = wrapper.find(".v-alert__dismissible");
closeBtn.trigger("click");
await wrapper.vm.$nextTick();
expect(alert.attributes().style).toBe("display: none;")
// router path '/home' to be called ?
});
1 - I get an error
console.error node_modules/#vue/test-utils/dist/vue-test-utils.js:15
[vue-test-utils]: could not overwrite property $route, this is usually caused by a plugin that has added the property asa read-only value
2 - How I should write the expect() to be sure that this /home route has been called
thanks for feedback
You are doing something that happens to work, but I believe is wrong, and also is causing you problems to test the router. You're importing the router in your component:
import router from "#/router";
Then calling its push right away:
router.push("/home");
I don't know how exactly you're installing the router, but usually you do something like:
new Vue({
router,
store,
i18n,
}).$mount('#app');
To install Vue plugins. I bet you're already doing this (in fact, is this mechanism that expose $route to your component). In the example, a vuex store and a reference to vue-i18n are also being installed.
This will expose a $router member in all your components. Instead of importing the router and calling its push directly, you could call it from this as $router:
this.$router.push("/home");
Now, thise makes testing easier, because you can pass a fake router to your component, when testing, via the mocks property, just as you're doing with $route already:
const push = jest.fn();
const $router = {
push: jest.fn(),
}
...
mocks: {
$route,
$router,
}
And then, in your test, you assert against push having been called:
expect(push).toHaveBeenCalledWith('/the-desired-path');
Assuming that you have setup the pre-requisities correctly and similar to this
Just use
it("should ... go to home page", async () => {
const $route = {
name: "home"
}
...
// router path '/home' to be called ?
expect(wrapper.vm.$route.name).toBe($route.name)
});

VueJS Adding to lifecycle hooks on every component

So I have a loader screen in my app, and the idea is to show the loader screen on the beforeCreate hook so the user can't see the stuff being rendered, and then on the mounted hook remove the loader screen.
This is fun and nice for when you have two or three view/components, but currently my app has a lot more than that, and adding it to each component/view doesn't make much sense for me.
So I was wondering, is there any way to add something to the beforeCreate and mounted hooks on a global scope. Something like this:
main.js
Vue.beforeCreate(() => {
//Show the loader screen
});
Vue.mounted(() => {
//Hide the loader screen
});
That way it would be applied to every component and view
You can use mixins for this purposes, and import in components.
//mixins.js
export default {
beforeCreate() {},
mounted() {}
}
And in component add mixins: [importedMixins]
You will have access to 'this'.
Actualy you can use and vuex to (mapGetters, mapActions etc.)
If you don't want include mixins in every component, try to use vue plugins system (https://v2.vuejs.org/v2/guide/plugins.html):
MyPlugin.install = function (Vue, options) {
// 1. add global method or property
Vue.myGlobalMethod = function () {
// something logic ...
}
// 2. add a global asset
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// something logic ...
}
...
})
// 3. inject some component options
Vue.mixin({
created: function () {
// something logic ...
}
...
})
// 4. add an instance method
Vue.prototype.$myMethod = function (methodOptions) {
// something logic ...
}
}
And use your plugin like this Vue.use(MyPlugin, { someOption: true })
There is something very silimar to your request in vue-router. I've never used afterEach but beforeEach works perfectly.
router.beforeEach((to, from, next) => {
/* must call `next` */
})
router.beforeResolve((to, from, next) => {
/* must call `next` */
})
router.afterEach((to, from) => {})
Here is a documentation
There is also a hook called 'beforeRouteEnter'.
Link to beforeRouteEnter docs

Can I handle back button within methods in vuejs 2?

I need some help in vuejs 2. I want to detect back button pressed event. I did some research and found this,
document.addEventListener("backbutton", yourCallBackFunction, false");
I think it is global event. I need something local, within a method. where i can use some logic.
methods: {
backButtonPressed() {
}
}
Or can i bind the global one to local function? Can anyone help me with that? TIA
Add the event on your mounted method on your root Vue component (the one the Vue instance is tied to.
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
},
methods: {
yourCallBackFunction () {
// Your logic
}
}
mounted () {
document.addEventListener("backbutton", this.yourCallBackFunction, false);
},
beforeDestroy () {
document.removeEventListener("backbutton", this.yourCallBackFunction);
}
})
We also remove it on beforeDestroy to keep things tidy.
Note: I've not personally used the back button event so have added it to this example only because you say it's working but need a way to globally handle it. This code will do just that.
Note: As per #Luke's comment - we add the listener in the mounted event so it doesn't execute for in the SSR context. If SSR isn't a factor / consideration then we can use the created lifecycle hook.
If still someone come across this issue.
A solution for an event listener for browser-back is https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onpopstate
window.onpopstate = function() {
alert('browser-back');
};
Is easy, if you need to catch that behavior only your component, you can use beforeRouteLeave function in the root of your component.
Example:
beforeRouteLeave (to, from, next) {
const answer = window.confirm('Do you really want to leave?)
if (answer) {
next()
} else {
next(false)
}
}
But if you need to add this behavior globally, you need catch with beforeEnter in the routes.
If you are using vue-router(no idea if you don't, why...) a good solution is to use in your component:
beforeRouteLeave(to, from, next) {
if (from.name === 'nameOfFromRoute' && to.name === 'nameOfToRoute' ) {
next(false);
} else {
next();
}
console.log({ to, from });
},
This was one variation I found to work as well, a little less verbose and uses router.push in the beforeDestroy lifecycle method
Listen for popstate
Push the desired name/path to redirect
The code below would be a better understanding.
beforeDestroy() {
window.addEventListener("popstate", (event) => {
this.$router.push({ path: <your path> });
});
},
This implementation was on Nuxt 2.14.6 and works just as well with all versions of Vue.
I have a similar problem and solved using #click="backFunction"
and created the function on methods like this:
methods: {
backFunction(){
//yourlogic
},