import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
const router = new Router({
routes: [
{
path: "/",
name: "Dashboard",
component: Dashboard,
},
{
path: "/login",
name: "LoginScreen",
component: LoginScreen
}
],
mode: "history"
});
export default router;
router.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
main.js
const router = new Router({ routes: [
{ path: "/", name: "Dashboard", component: Dashboard, }
... ], mode: "history" });
const router = new Router({ routes: [
{ path: "/", name: "Dashboard", component: Dashboard,
beforeEnter: (to, from, next) => { ... }
}
... ], mode: "history" });
per-route navigation guards
const router = new Router({ routes: [
{ path: "/", name: "Dashboard", component: Dashboard, beforeEnter: (to, from, next) => { if (store.getters["isLoggedIn"]) { next(); } else { next("/login"); } } } ... ], mode: "history" });
In the `admin` route, create a per-route navigation guard
https://github.com/shortdiv/vuex-and-router
[step-0]
const router = new Router({ routes: [
{
path: "/",
... beforeEnter: (to, from, next) => { ... } }, { path: "/inventory", ...
beforeEnter: (to, from, next) => { ... } } ], mode: "history" });
const router = new Router({ routes: [...], mode: "history" });
router.beforeEach((to, from, next) => { // check if user is logged in })
global navigation guards
const router = new Router({ routes: [
{
path: "/", meta: { authRequired: true } }, { path: "/inventory",
meta: { authRequired: true }
}
], mode: "history" });
router.beforeEach((to, from, next) => { const authRequired = to.matched.some(route => route.meta.authRequired); })
route metadata
check for route metadata
const router = new Router({ routes: [
{
path: "/", meta: { authRequired: true } }, ...
], mode: "history" });
router.beforeEach((to, from, next) => { const authRequired = to.matched.some(route => route.meta.authRequired); if (!authRequired) return next(); })
import Vue from "vue"; import Router from "vue-router"; import store from "./store";
Vue.use(Router); const router = new Router({... });
router.beforeEach((to, from, next) => { if (store.getters["isLoggedIn"]) { next(); } else { next("/login"); } })
Check vuex state
In the routes file, add metadata to `admin` and `inventory` and create a global navigation guard that checks whether a user is logged in
https://github.com/shortdiv/vuex-and-router
[step-1]
export default { ... methods: { handleLogin() { this.$store.dispatch("logIn") .then(() => { this.$router.push( this.$route.query.redirect || "/"); }); } } };
dispatch and reroute