Vuex + local storage for data persistence

$router-push ("/my"); $router-push ("/my"); Import {mapMutations} from "VUEX "; 2. Save the data returned after successful login to the STATE of VUEX. 2.2 The method is introduced into the methods of components that need to use the Mutations method of VUex... MapMutations (["getUser"]), 2.3: Save the data returned after successful login to the state of VUex this.user_data (res.data); 3. Vuex: 3.1 State defines an empty object to hold user information 3.2 Mutations defines a function, [USER_DATA](state, Data) {state.loginstatus = true state.token = data.token state.user = data // Save the login data to the local, Localstorage.setitem ('userData', json.stringify (data))} // Obtain the local storage data, {let userInfo = json.parse (localstorage.getitem ('userData')) if (userInfo) { State.loginstatus = true state.token = userinfo.token state.user = userInfo}} 3.4 Write the local information initialization call to the created app.vue <script> export default { created() { this.$store.commit("USER_INIT"); }}; State import {mapState} from "vuex"; 4.2 Creating user computed in computed: {... MapState ({user: (state) => state.users.user, // user loginStatus: <div v-if="loginStatus" class="loginUser"> <! <div v-if="loginStatus" class="loginUser"> <img: SRC =" user.imgurl == 1? '.. /images/searchShop.png' :user.imgUrl" alt /> <span>{{user.name || user.tel}}</span> </div> <div v-else @click="goLogin" <span style =" box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; white-space: inherit! Important;"Copy the code

Vuex code: on the store folder

  1. Let me write the name of the function that stores mutations-types.js

2. Create a users.js file: State getters mutations Actions alone import {USER_DATA, USER_INIT} from "./mutations-types" export default {state: {loginStatus: false, mutations-types: false, mutations-types: false Mutations: {// token user: {}, mutations: {// token user: {}, mutations: {// Second argument: [USER_DATA](state, Data) {state.loginstatus = true state.token = data.token state.user = data // Save the login data to the local, Localstorage.setitem ('userData', json.stringify (data))}, [USER_INIT](state) {let userInfo = json.parse (localstorage.getitem ('userData')) if (userInfo) { state.loginStatus = true state.token = userInfo.token state.user = userInfo } }, Logout (state) {localstorage.removeItem ('userData') state.loginstatus = false state.token = null state.user = {}  } }, actions: {} }Copy the code
  1. Add the users.js file to the store index.js file and mount it to the modules