Vuex + Vue Router
Login Flow
Vue Router
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
Vue Router
const router = new Router({ routes: [
{ path: "/", name: "Dashboard", component: Dashboard, }
... ], mode: "history" });
Vue Router
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" });
Exercise Time!
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" });
Vue Router Navigation Guards
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(); })
Vue Router Navigation Guards
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
Exercise Time!
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]
Vue Router Navigation Guards
export default { ... methods: { handleLogin() { this.$store.dispatch("logIn") .then(() => { this.$router.push( this.$route.query.redirect || "/"); }); } } };
dispatch and reroute
Vuex + Vue Router
By shortdiv
Vuex + Vue Router
- 815