Skip to content

Instantly share code, notes, and snippets.

@tamirvs
Created February 11, 2020 21:01
Show Gist options
  • Save tamirvs/d1a584f3fc9c494cf75d3ca76c54fb1b to your computer and use it in GitHub Desktop.
Save tamirvs/d1a584f3fc9c494cf75d3ca76c54fb1b to your computer and use it in GitHub Desktop.
Mixin to make the back button close dialogs
// inspired by https://jessarcher.com/blog/closing-modals-with-the-back-button-in-a-vue-spa/
export default function (props) {
let initialValues = {};
return {
created () {
for (let prop of props) {
initialValues[prop] = this[prop];
}
const unregisterRouterGuard = this.$router.beforeEach((to, from, next) => {
for (let prop of props) {
if (this[prop] !== initialValues[prop]) {
this[prop] = initialValues[prop];
next(false);
return;
}
}
next();
});
this.$once('hook:destroyed', () => {
unregisterRouterGuard()
});
},
}
}
<template>
<v-dialog v-model="dialog">
...
</v-dialog>
</template>
<script>
import backButton from './mixins/backButton.js';
export default {
mixins: [
backButton(['dialog'])
],
data: () => ({
dialog: false
})
}
</script>
@francoishill
Copy link

This is a temporary solution to vuetifyjs/vuetify#1793 (comment). Thanks @tamirvs

@hanenouche
Copy link

Hi @tamirvs, thanks for your solution, did you find a solution when we have no history ?

@camhart
Copy link

camhart commented Jul 10, 2020

I ran into an issue where this wasn't working for me when the dialogs would appear on the first page load--with no prior vue-router navigations occurring.

I stumbled across this comment vuejs/vue-router#748 (comment) which points to https://forum.vuejs.org/t/router-beforeeach-if-manually-input-adress-in-browser-it-does-not-work/12461/3, which I don't fully understand but basically registering an empty beforeEach prior to creating my vue instance solved the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment