vuex use case

A: store data warehouse location:

Two: store / user.js Code :( data only on user registration)

import Vue from 'vue'

export const USER_SIGNIN = 'USER_SIGNIN'    //登录成功
export const USER_SIGNOUT = 'USER_SIGNOUT'  //退出登录

export default {
  state:JSON.parse(sessionStorage.getItem('user')) || {},
  mutations:{
      [USER_SIGNIN](state,user){
            sessionStorage.setItem('user',JSON.stringify(user));
            Object.assign(state,user)
      },
      [USER_SIGNOUT](state){
            sessionStorage.removeItem('user');
            Object.keys(state).forEach(k=> Vue.delete(state,k))
      }
  },
  actions:{
    [USER_SIGNIN]({commit},user){
      commit(USER_SIGNIN,user)
    },
    [USER_SIGNOUT]({commit}){
      commit(USER_SIGNOUT)
    }
  }
}

Three: store / index.js Code:

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

Vue.use(Vuex);

export default new Vuex.Store({
  strict:process.env.NODE_ENV !== 'production',//在非生产模式下,使用严格模式
  modules:{
    user
  }
})

IV: store component used in the method of mutations: Auxiliary function mapActions (or directly mapMutations) used here mapActions

       Vuex helper function mapState, mapActions, mapMutations

  import { mapActions } from 'vuex'
  import { USER_SIGNIN } from '../store/user'

  export default{
    data(){
       return {}
    },
    name:'Login',
    methods:{
      ...mapActions([USER_SIGNIN]),
      submit() {
        this.btn = true
        if(!this.form.id || !this.form.name) return
        this.USER_SIGNIN(this.form)
        this.$router.replace({ path: '/personal' })
      }
    }
  }
 import { mapActions } from 'vuex'
  import { USER_SIGNOUT } from '../store/user'
  export default {
    props:['title'],
    components:{
      comheader
    },
    methods: {
      ...mapActions([USER_SIGNOUT]),
      submit() {
        this.USER_SIGNOUT()
        this.$router.replace({ path: '/login' })
      }
    }
  }

Five: component used in the state store in the data: mapState auxiliary function

import { mapState } from 'vuex'
  import logo from '../assets/logo.png'
  import vheader from '../components/comheader.vue'
  export default {
    data() {
      return {
        logo
      }
    },
    components:{
      vheader:vheader
    },
    computed: mapState({ user: state => state.user }),
  }

 

Published 54 original articles · won praise 8 · views 70000 +

Guess you like

Origin blog.csdn.net/yang295242361/article/details/104690653