vue.js路由与vuex数据模型设计

2020/6/2 5:26:22

本文主要是介绍vue.js路由与vuex数据模型设计,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

路由设计

本则路由考虑验证进入登录页面,完成登录操作进入首页。

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 = "";
    }
  }
};


这篇关于vue.js路由与vuex数据模型设计的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程