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 }),
  }
发布了54 篇原创文章 · 获赞 8 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yang295242361/article/details/104690653