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
})
- [Vuejs]-How to route Vue Server to Node.js Backend
- [Vuejs]-Vueuse useDark function blocking the ability to transition an element
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.
- [Vuejs]-Vue SSR: resolveComponent can only be used in render() or setup()
- [Vuejs]-Reference an external JavaScript file using Vue.js
Source:stackexchange.com