vuex的使用實例

一:store數據倉庫位置:

二:store/user.js代碼:(僅關於用戶註冊的數據)

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)
    }
  }
}

三:store/index.js代碼:

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
  }
})

四:組件中使用store裏的mutations方法:用輔助函數mapActions(或直接用mapMutations)這裏用mapActions

       Vuex的輔助函數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' })
      }
    }
  }

五:組件中使用store裏的state裏的數據: 用輔助函數mapState

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 }),
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章