How to access plugins in navigation guards in Vue 3?

Viewed 552

Vue 3.0, Vue-route 4.0

Issue: According the API the next() function in a navigation guard can be invoked with a callback like vm => ...

  • If pass false to next() it correctly stops the navigation, if I pass true the navigation happens as expected
  • If I however pass any function to next() including vm => false the route guard always let the navigation happen

The goal is to fix the issue just highlighted, and use a plugin property to determine if navigation should happen

next(() => vm.$myPluginData.canNavigate) doesn't seem to work

code:

// define the routes
export const ROUTES = [
  {
    path: '/',
    name: 'main',
    component: Main,
    meta: {
      shouldCheck: false
    }
  },
  {
    path: '/protected-route',
    name: 'protected-route',
    component: () => import('../components/pages/ProtectedComponent.vue'),
    meta: {
      shouldCheck: true
    }
  }
]

// create the router
const router = createRouter({
  history: createWebHashHistory(),
  routes: ROUTES
})

// define the guards
router.beforeEach((to, from, next) => {
  if (!to.meta.shouldCheck) {
    return next()
  }

  return next(vm => vm.$myPluginData.canNavigate)
})
 
// add the plugins to the app
createApp(App)
   .use(MyPlugin) // add the plugin
   .use(router) // add the router
   .mount('#app')

The plugin from which I am trying to access the property is defined as

const reactiveData = reactive({
   canNavigate: false
 })

export default {
  install: app => {
    app.config.globalProperties.$myPluginData = reactiveData
    app.provide('MyPlugin', readonly(reactiveData))
  }
}

Update:

Even if don't return next(), like

  next(vm => {
    console.log(vm)
    return vm.$myPluginData.canNavigate
  })

nothing changes. Also the log is not printed.

0 Answers
Related