Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vuex的使用总结 #6

Open
willson-wang opened this issue Dec 20, 2017 · 0 comments
Open

vuex的使用总结 #6

willson-wang opened this issue Dec 20, 2017 · 0 comments

Comments

@willson-wang
Copy link
Owner

willson-wang commented Dec 20, 2017

Vuex 文档里面这么说的,vuex是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化;

我自己的理解就是vuex是一个通信工具,它可以让我们在vue的各个组件之间进行实时的数据通信,同时以又以一种特定的方式来设置状态,改变状态,从而实现可预测的变化;在传统的项目开发中,我们一般有以下几种方式来实现组件or模块or页面之间的通信,如EventBus, 事件广播emit and broadcast,locastorage, cookie、传参等,而这些方式多多少少都有一些缺点,而vuex则是一种更便捷及更高效的实现组件or模块之前通信的一种工具;

个人建议学习vuex的时候,可以从下面3点来进行学习
一、vuex内有哪些东西 -> vuex里面有6个关键属性,如下所示

  1. state状态值存储的地方,所有需要公用or需要经过vuex处理的数据都需要先在state内定义;注意的是为了保证vuex内定义的状态是响应式的,最好先在state内定义该状态,然后在通过mutation来进行改变;

  2. mutation改变state内状态值的方法集合,即state内的状态只有通过mutations内定义的方法才可以去改变,这也是保证状态以一种可预测的方式方式变化的原因;

  3. action也是改变state内状态值的方法集合,与mutation不同的是,action不是直接操作state而是通过操作mutation来改变state,另外一个区别是action内可以包含任意异步操作,而mutation内不能;

  4. getter用来获取state值的方法集合,主要有两个特点,第一个过滤获取到的state值,第二个就是与计算属性类似,会对值进行缓存,当依赖发生改变的时候才会重新获取;

  5. module即用来对state进行模块划分的,这样的好处就是便于管理与维护不同模块内定义的state,内部定义state,mutation,action与全局的一样;

  6. mutation-type就是方便维护mutation,能够在一个文件内保存所以的mutation

二、vuex内怎么去定义state、mutation、action、module、getter

  1. 定义state
    state.js
    const state = { userInfo: {}, showLoading: false, showPageTagsList: [] }; export default state;

  2. 定义mutation
    mutations.js 注意mutation传入的第一个参数是state,第二个参数是载荷也就是提交mutation时传入的参数
    export default { [types.SAVE_USERINFO] (state, userInfo) { state.userInfo = userInfo.data; Storage.setSessionStorage('userInfo', JSON.stringify(userInfo.data)); } };

  3. 定义action
    import { loginByuserName } from '@/api/login/login'; import * as types from './mutations-type'; export default { LoginByuserName ({ commit }, userInfo) { const username = userInfo.username.trim(); return new Promise((resolve, reject) => { loginByuserName(username, userInfo.password).then(response => { const data = response.data; commit(types['SAVE_USERINFO'], data); resolve(); }).catch(error => { reject(error); }); }); } };

  4. 定义getter
    export default { userInfo: state => state.userInfo, productMdInfo: state => state.product.productMdInfo, showLoading: state => state.showLoading };

  5. 定义mutation-type
    export const SAVE_USERINFO = 'SAVE_USERINFO'; export const SAVE_PRODUCTMD_INFO = 'SAVE_PRODUCTMD_INFO'; export const TOGGLE_LOADING = 'TOGGLE_LOADING'; export const ADD_NEW_TAG = 'ADD_NEW_TAG';

  6. 最后传入到vuex.store方法内
    export default new Vuex.Store({ modules: { statistics, order, product }, state, mutations, getters, actions, strict: debug, plugins: debug ? [createLogger()] : [] });

三、vue组件内怎样去使用vuex

  1. 通过$state来进行操作
    获取state => this.$store.state.count来进行获取某个state属性,注意这里能够通过this.$store来获取到store对象的原因是在vue初始化app实例的时候就把store注入到vue实例内了;
    提交mutation => this.$store.commit('SAVE_USERINFO ', {type: 'a', name: 'jack'});
    提交action => this.$store.dispatch('LoginByuserName ', {type: 'a', name: 'jack'});

  2. 通过mapState、mapGetters 、mapMutations 、mapActions 来进行操作
    获取state => 在计算属性内使用...mapState(['userInfo']) 这等价于userInfo () {reurn store.state.userInfo}
    提交mutation => 在方法内先解构...mapMutations(['SAVE_USERINFO ']) 等价为 SAVE_USERINFO () {return this.$store.commit('SAVE_USERINFO ', {type: 'a', name: 'jack'});}
    提交action => 现在方法内进行解构与mutation一样
    通过mapGetters 获取到某个state状态状态值,在计算属性内进行结构...mapGetters(['userInfo'])

vuex使用起来不难,难的是这种架构思想,有时间的话会去看下源码;

export default {
  namespaced: true,
  state: {
    msgList: {}
  },
  getters: {
    getListByType: state => type => (state.msgList[type] || {})
  },
  mutations: {
    setMsgList(state, playload) {
      const type = playload.group_id;
      const {data}  = playload.result;
      console.log('setMsgList', state, type);
      if (state.msgList[type]) {
        state.msgList = {...state.msgList, [type]: {
          list: state.msgList[type].list.concat(data),
        }};
      } else {
        state.msgList = {...state.msgList, [type]: {
          list: data,
        }};
      }
    },
    cleanMsg(state, type) {
      console.log('cleanMsg', state, type);
      if (type && state.msgList[type]) {
        state.msgList[type] = {
          list: [],
        }
      }else {
        state.msgList = {}
      }
    }
  },
  actions: {
    async getMsgList({commit, state}, playload) {
      const {group_id, lastest_create_unixtime = 0, oldest_create_unixtime = 0} = playload;
      const result = await getMessageList({
        group_id,
        limit: 20,
      });
      const { data } = result;
      commit('setMsgList', {result, group_id});
      return data;
    }
  }
}

参考链接
https://vuex.vuejs.org/zh-cn/intro.html

@willson-wang willson-wang changed the title vuex的使用方式 vuex的使用总结 Dec 20, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant