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;

豌豆资源搜索网站https://55wd.com 广州vi设计公司http://www.maiqicn.com

组件

<div class="modify">
  <input
    type="text"
    @keydown.enter.prevent="handleKeydown"
    v-model="currentVal"
    placeholder="使用enter键切换频道"
  />
  <button @click="reset" style="margin-left:5px;outline:none;cursor:pointer;">复位</button>
</div>
 
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数据模型设计

上一篇:pecl 安装 phpredis


下一篇:Vue 使用v-html 动态加载代码 点击事件失效