vuex学习笔记

一、一个简单的学习案例
<body>
  <div id="app">
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</body>
<script type="text/javascript">
  const store = new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      increment: state => state.count++,
      decrement: state => state.count--
    }
  })
  new Vue({
    el: '#app',
    computed: {
      count() {
      // 每当store.state.count发生变化的时候,都会重新求取计算属性,并且触发更新相关联的DOM
        return store.state.count
      }
    },
    methods: {
      increment() {
        store.commit('increment')
      },
      decrement() {
        store.commit('decrement')
      }
    }
  })
</script>
屏幕快照 2018-07-24 上午11.45.52.png
二、vuex工作原理
vuex工作原理
state

      从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态:

// 访问方法一:
const Counter = {
  template: `<div>{{ count }}</div>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}
// 访问方法二:
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,
    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',
    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}
Getter方法

      有时候我们需要从store中的state中派生出一些状态,例如对列表进行过滤并计数,getter可以被认为是store的计算属性,如同计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算;

// 定义方法
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
// 访问方法一
computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}
// 访问方法二
import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
提交mutation,mutation中都是同步事务

      1)在组件中使用this.$store.commit('xxx')提交mutation;
      2)使用mapMutations辅助函数将组件中的methods映射为store.commit调用(需要在根节点注入store);

// commit方法
computed: {
    ...mapState({
      gymList: 'gymList',
    }),
    ...mapGetters({
      gym: 'currentGym',
    }),
    gymId: {
      get() {
        return this.$store.state.gymId
      },
      set(value) {
        this.$store.commit('setGymId', value)
        this.$store.commit('setRoomId', this.gym.roomList ? this.gym.roomList[0].id : '')
      }
    },
// 辅助函数
import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}
Action

      1)Action类似于mutation,不同在于:Action提交的是mutation,而不是直接变更状态;
      2)Action可以包含任意异步操作;

// 使用mapActions辅助函数提交
import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}
if (!state.gymId) {
    context.commit('setGymId', gymList[0].gym.id)
}
一个完整的store包含
const store = new Vuex.Store({
    state: {
      gymList: [],
      gymId: null,
      roomId: null,
      user: {
        username: null,   // 登录用户名
        role: null        // 角色
      }
    },
    //plugins: process.env.NODE_ENV !== 'production' ? [createLogger()] : [],
    getters: {
      currentGym: state => {
        return _.find(state.gymList, {gym: {id: state.gymId}})
      },
    },
    mutations: {
      setGymList(state, payload) {
        state.gymList = payload;
      },
      setGymId(state, payload) {
        state.gymId = payload;
      },
      setRoomId(state, payload) {
        state.roomId = payload;
      },
      setUser(state, payload) {
        state.user = payload
      }
    },
    actions: {
      fetchGymList(context) {
        axios.get(`${api_host}/lego/manage/gym/list`).then((res) => {
          let gymList = res.data.data;
          let state = context.state;

          if (!state.gymId) {
            context.commit('setGymId', gymList[0].gym.id)
          }
          if (!state.roomId) {
            context.commit('setRoom', gymList[0].roomList[0]);
            context.commit('setRoomId', gymList[0].roomList[0].id);
          }

          context.commit('setGymList', gymList)
        });
      }
    },
    modules: {}
});

      Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vuex 是什么? ** 官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式**。它采用集中...
    Rz______阅读 2,316评论 1 10
  • vuex学习笔记 vuex是什么? Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存...
    EL_PSY_CONGROO阅读 775评论 0 0
  • vuex 状态管理器 作为应用中所有组件的中央储存 只能以预定的方式去操作状态 把所有组件共享的状态抽取出来作为全...
    一只大椰子阅读 800评论 0 1
  • 学习目的 了解和熟练使用 VueX,能够在实际项目中运用。 VueX介绍 Vuex 是一个专为 Vue.js ...
    _1633_阅读 2,803评论 0 7
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 2,962评论 0 7