Rashid
Rashid

Reputation: 1740

CASL Vue - How to access $can in route guard

I am building a Nuxt app and trying to create a route guard. How can I access $can in my Nuxt middleware?

export default (context) => {
    const { route } = context
    route.matched.some((routeRecord) => {
        const options = routeRecord.components.default.options
        console.log(options)
        // should use $can here
        return true
    })
}

I import the following in my nuxt.config.js:

plugins: [
    { src: '@plugins/vue-can.js' },
]

I add casl as plugins on the Nuxt $auth module:

auth: {
    plugins: [
         '@plugins/vue-casl.js',
    ]
}

This is because I need to access $auth.user in my plugins.

All of this works good, except I can't find $abilities or $can in my Nuxt middleware.


PS: I am talking about this package: @casl/vue

Upvotes: 1

Views: 1234

Answers (1)

aseidma
aseidma

Reputation: 752

$abilities and $can should both be available as properties of the context object in your middleware, so you should be able to access them using context.$foo.

If you don't see it, it is probably because it was not injected properly. The plugin you registered in your nuxt.config.js should use inject to add $can to the global vue instance and make it available as a property of this and context. See the documentation for further detail: https://nuxtjs.org/docs/2.x/directory-structure/plugins/#inject-in-root--context

Upvotes: 1

Related Questions