本则路由考虑验证进入登录页面,完成登录操作进入首页。
import Vue from "vue"; import Router from "vue-router"; Vue.use(Router); import store from "@/store/store"; // (延迟加载) const Login = () => import("@/views/login"); const Home = () => import("@/views/home"); const HomeRoute = { path: "/", name: "首页", component: Home }; export { HomeRoute }; const router = new Router({ base: process.env.BASE_URL, routes: [ { path: "/login", name: "登录", component: Login }, HomeRoute ] }); router.beforeEach((to, from, next) => { let loginName = store.state.user.loginName; if (to.path === "/" && loginName == "") { next("/login"); } else { next(); } }); export default router;~~~~
const state = { loginName: "" }; const mutations = { SET_LOGINNAME(state, loginName) { state.loginName = loginName; } }; const actions = { login({ commit }, userInfo) { return new Promise((res, ret) => { commit("SET_LOGINNAME", userInfo); res(); }); }, logout({ commit }) { return new Promise((res, ret) => { commit("SET_LOGINNAME", ""); res(); }); } }; export default { namespaced: true, state, mutations, actions };
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); import user from "./modules/user"; const store = new Vuex.Store({ modules: { user } }); export default store;
import { mapState, mapMutations, mapActions } from "vuex"; export default { name: "login", data() { return { currentVal: "", list: ["咨询服务", "音悦台", "体育台", "财经频道", "时尚资讯"], index: 0 }; }, computed: { ...mapState({ loginName: state => state.user.loginName }) }, methods: { ...mapActions({ login: "user/login" }), handleToHome() { let userInfo = "user"; this.login(userInfo); this.$router.push({ path: "/" }); }, handleKeydown() { this.currentVal = this.list[this.index]; this.index++; let len = this.list.length - 1; if (this.index > len) { this.index = 0; } }, reset() { this.index = 0; this.currentVal = ""; } } };