vuex+本地存储保存某些用户状态的方法

569 阅读1分钟

1. vuex

store --> index.js

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

var state = {
  lo_uname: "" || localStorage.getItem("lo_uname"),
  lo_uid: "" || localStorage.getItem("lo_uid"),
};

var mutations = {
  // 用户名
  fn_lo_uname(state, data) {
    state.lo_uname = data;
    localStorage.setItem("lo_uname", data);
  },
  // 用户id
  fn_lo_uid(state, data) {
    state.lo_uid = data;
    localStorage.setItem("lo_uid", data);
  },
}

const store = new Vuex.Store({
  state, //状态树
  mutations, //方法库(不支持异步)
});

export default store;

2.load.vue

用户登录成功后

    // 设置本地存储提交vuex中的方法
    that.$store.commit("fn_lo_uname", uname);
    that.$store.commit("fn_lo_uid", uid);

3.其他页面获取数据

    mounted(){
        // 组件创建后获取vuex中的数据
        this.username = this.$store.state.lo_uname;
        this.userid = this.$store.state.lo_uid;
    }