Categories
Vue Answers

How to show confirmation dialog before route change with Vue.js?

Spread the love

We can show a confirmation dialog before route changes in a Vue.js application by leveraging Vue Router navigation guards.

Specifically, we can use the beforeRouteLeave guard to intercept route changes and display a confirmation dialog. Here’s a basic example of how to implement this:

// main.js or our Vue entry file

import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';

Vue.use(VueRouter);

const routes = [
  // Our routes here
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => {
  // Check if the component has a beforeRouteLeave hook
  if (from.meta.confirmation && typeof from.meta.confirmation === 'function') {
    // Call the confirmation function passing the next() callback
    from.meta.confirmation(next);
  } else {
    // If there's no confirmation function, proceed to the next route
    next();
  }
});

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

Then, in our component where we want to show the confirmation dialog before route change, we can define the beforeRouteLeave hook along with the confirmation logic. Here’s an example:

// YourComponent.vue

export default {
  data() {
    return {
      confirmDialog: false // Whether to show the confirmation dialog or not
    };
  },
  beforeRouteLeave(to, from, next) {
    // If confirmation is required, set confirmDialog to true
    if (/* Our condition for showing the confirmation dialog */) {
      this.confirmDialog = true;
      
      // Define the confirmation logic
      this.$nextTick(() => {
        // Display confirmation dialog using our preferred UI library/modal
        // Example with native confirm dialog
        if (confirm("Are you sure you want to leave this page?")) {
          // If confirmed, proceed to the next route
          next();
        } else {
          // If not confirmed, stay on the current route
          next(false);
        }
      });
    } else {
      // If confirmation is not required, proceed to the next route
      next();
    }
  }
};

This way, before leaving the current route, the beforeRouteLeave hook will be triggered, and if the condition for showing the confirmation dialog is met, it will display the dialog and wait for user confirmation before proceeding to the next route.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *