你可以用
router.beforeEach
使用这些规则创建路线守卫。
https://codesandbox.io/s/zealous-cartwright-yhcuy?file=/src/main.js
import { createApp } from "vue";
import { createRouter, createWebHashHistory } from "vue-router";
import App from "./App.vue";
import Home from "./components/Home.vue";
import View1 from "./components/View1.vue";
import View2 from "./components/View2.vue";
const getLoggedInUser = () => {
// user to test routes with
const user123 = {
name: "John",
id: "123",
role: "user"
};
const user5 = {
name: "Sam",
id: "5",
role: "user"
};
const admin = {
name: "Dean",
id: "5",
role: "admin"
};
return user123;
};
const routeGuard = (to, from) => {
const { loggedInRequired, idCheckRequired, authorize } = to.meta;
// if login not required then allow entry
if (!loggedInRequired) {
return true;
}
const currentUser = getLoggedInUser();
if (!currentUser) {
// not logged in so redirect to home
return false;
}
if (authorize.length && !authorize.includes(currentUser.role)) {
// if they don't have the correct role redirect home
return false;
}
if (idCheckRequired && to.params.id != currentUser.id) {
// if the :id param doesn't match the logged in user's id
return false;
}
return true;
};
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: "/",
name: "Home",
component: Home,
children: [
{
path: "streamers/",
name: "Streamers",
component: View1,
meta: {
loggedInRequired: true,
authorize: ["admin"],
idCheckRequired: false
}
},
{
path: "streamers/:id/detail/",
name: "StreamerDetail",
component: View2,
meta: {
loggedInRequired: true,
authorize: ["user"],
idCheckRequired: true
}
}
]
}
]
});
router.beforeEach(routeGuard);
createApp(App).use(router).mount("#app");