[Vuejs]-How to access protected routes if the user is admin or not in vuejs

0👍

If your app is SPA (and not SSR), you can just import your store and access its data in router navigation guards:

Vuex:

// store.js
import { createStore } from 'vuex'

export default createStore({
 state() {
   isAdmin: false
 }
})

// router.js
import store from "./store"


router.beforeEach(() => {
  if (store.state.isAdmin) // do something
})

Pinia:

// useUserStore.js
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {
  const isAdmin = ref(false)
  
  return { isAdmin }
})

// router.js
import { useUserStore } from "./useUserStore"


router.beforeEach(() => {
  const userStore = useUserStore()
  if (userStore.isAdmin) // do something
})

0👍

You can simply do this on the route you want to protect:

In your routes file first get the "isAdmin" from local storage

const isAdmin = localStorage.getItem('isAdmin');

Then in the route do this:

{
  path: "/idAdminRoute",
  name: "admin-route",
  beforeEnter: (to, from, next) => {
      if(isAdmin){
          next()
      }
      return false
    },
  component: () =>
    import("../components/admin.vue")
},

this will get applied to all the child routes as well.

Leave a comment