1, an overview of the

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue’s official debugging tool, DevTools Extension, which provides advanced debugging functions such as zero-configuration time-travel debugging, status snapshot import and export, and so on.

2. Use VUEX to manage login status

1. Import vuex

import Vuex from 'vuex'
Vue.use(Vuex);
import store from './store'
Copy the code
new Vue({
  el: '#app', // enable router, // enable store store, // enable ElementUI render: h => h(App)});Copy the code

2, Create store folder and create index.js file

import Vue from 'vue'
import Vuex from 'vuex'
import user from './model/user'

Vue.use(Vuex);

exportDefault new vuex. Store({// define module user: {user}})Copy the code

3. Create user module

User. Js as follows

Const user = {// If sessionStorage exists, use sessionStorage; otherwise, create an empty user. sessionStorage.getItem('loginUser')? JSON.parse(sessionStorage.getItem('loginUser')) : {
    user: {
      username: ' '}}, // Get object this.$store.getters.getUser.userName
  getters: {
    getUser(state) {
      returnstate.user; }}, // Update object this.$store.updateUser(); mutations: { updateUser(state, user) { state.user = user; }}, // Asynchronously update this object.$store.dispatch("asyncUpdateUser",repos.data.data);
  actions: {
    asyncUpdateUser(context, user) {
      context.commit('updateUser', user); }}};export default user;

Copy the code

4. Modify app.vue to monitor page refresh and temporarily save the value to sessionStorage to solve data loss after refresh

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<script>
  export default {
    name: 'App'.mounted(){// Listen for the page refresh event window.adDeventListener ("unload",this.saveLoginUser);
    },
    methods:{
      saveLoginUserSessionstorage.setitem (){// store state. User in value VUEX into sessionStorage sessionStorage.setitem ('loginUser',JSON.stringify(this.$store.state.user));
      }
    }
  }
</script>
Copy the code