I have a vue.js project. The vue-component can create a dialog. If the user presses the back button I want to close this dialog (if it is open) instead of leaving the vue-component. How can I achieve this?
I tried this:
beforeRouteLeave(to, from, next) {
let self = this;
//dialog is open
if(self.isShowingDialog){
//closes the dialog
self.isShowingDialog = false;
}
else {
//navigates back to previous component
next();
}
},
It works, but not if I open the the component for the first time and the history is empty. In this case the back button exit my app instead of closing the dialog.
It works now with the hashtag/anchor as suggested by @Kapcash. If I press now the back button the dialog is hidden and my main component doesn't close.
MyComponent.vue:
<StockChooser v-if="showStockChooser" v-model="showStockChooser">
import StockChooser from "./components/StockChooser";
Vue.component('StockChooser', StockChooser)
data() {
return {
showStockChooser: false,
}
},
methods: {
openDialog: {
this.showStockChooser = true;
this.$router.push('#dialogStockChooser')
}
}
StockChooser.vue:
<v-dialog v-model="show" v-if="show" persistent fullscreen>
<v-row>
<v-btn color="red" @click="cancel()" style="width:100%">Cancel</v-btn>
</v-row>
</v-dialog>
data() {
return {
show: false,
}
},
watch: {
"$route.hash": {
handler: function(dialog_id) {
if(dialog_id === '#dialogStockChooser'){
this.show = true;
}
else {
this.show = false;
}
}, immediate: true
},
},
methods: {
cancel(){
this.$router.push(-1)
},
}