安装Vuex

前段代码中执行 ` npm i vuex`

配置Vuex

  1. Client根目录下新建store.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const types = {
  SET_USER:"SET_USER"//用户信息
}

const state = {
  user:{}
}

const getters = {
  user:state=>state.user
}

const mutations = {
  [types.SET_USER](state, user) {
    if (user) {
      state.user = user;
    } else {
      state.user={}
    }
  }
}


const actions = {
  setUser: ({ commit }, user) => {
    commit(types.SET_USER,user)
  }
}
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

  1. 修改main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from "./http";
import store from "./store";


Vue.config.productionTip = false
Vue.prototype.$axios = axios

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

3.App.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>
<script>
import jwt_decode from "jwt-decode";
export default {
  name:'app',
  created(){
    if(localStorage.wxpyqToken){
      const decode=jwt_decode(localStorage.wxpyqToken);
      this.$store.dispatch("setUser",decode)
    }
  }
}
</script>

<style>
html,
body,
#app {
  width: 100%;
  height: 100%;
}
</style>

 

使用Vuex

存储数据

// 存储数据
        this.$store.dispatch("setUser", decode);