Search code examples
vuejs2vuexvue-router

VUE route redirect not closing modal from other page


I am using vue2 routes set up by another dev but I am trying to change the 'redirect' currently set to go to the 'home' page.

This issue is that there is a page which when you first enter the page (for the very first time) a bootstrap modal is displayed. The issue I'm having is if I enter this page of the first time then change the URL, the 'redirect' is working as expected BUT the modal is also still displaying and I don't know how to make it close.

routes.js

import {store} from './store/store';
import Cart from './components/Cart';
import Stock from './components/Stock';
import Home from './components/Home.vue';
import Review from './components/Review';
import Order from './components/Order.vue';
import OrderReport from './components/OrderReport';
import AccountDetails from './components/AccountDetails';
import ExistingOrders from './components/ExistingOrders';

export const routes = [
    {path: '', component: Home},
    {path: '/order', component: Order},
    {
        path: '/review', component: Review, children: [
            {path: '', component: ExistingOrders},
            {
                path: ':id', component: OrderReport, beforeEnter: (to, from, next) => {

                    let orderCount = store.getters.orderPaginator.items.filter(item => item.id === +to.params.id).length;

                    next(orderCount > 0);
                }
            }
        ]
    },
    {path: '/account', component: AccountDetails},
    {path: '/stock', component: Stock},
    {path: '/cart', component: Cart},
    {path: '*', redirect: '/order'}
];

If I change "redirect: '/order'" to "redirect: '/'" it goes to my home page as expected but with the modal displayed. Is there a way to close on the redirect?

Page where modal should be displayed enter image description here

**Changed URL to 'orders' and clicked 'Enter' enter image description here

Directed to the correct page (Home page) but modal still displayed. Is there a way I can change the :key using routes or would I have to use something like this.$forceUpdate(), although I have read that this may not work in vue2 and is really a nice thing to do.

What's my best approach? Just to mention I am new to vue2


Solution

  • I had success with this approach.

    You can use a feature called Global Before Guards in Vue Router.

    Inside router folder index.js file:

    const router = createRouter({
      // not relevant to the answer
      history: createWebHistory(process.env.BASE_URL),
      routes
    })
    
    router.beforeEach((to, from, next) => {
      // remove modal backdrop if one exists
      let modalBackground = document.querySelector('.modal-backdrop')
      if (modalBackground) {
        modalBackground.remove()
      }
      // do other stuff
    
      next()
    })
    

    In my case I wanted to remove the modal backdrop but you can modify this to suit your needs.