vuex 初步理解

2017-04-07  本文已影响309人  coolheadedY
new Vuex.Store({
  state, // 状态
  getters, // 
  mutations,  // 突然变化了
  actions, // 触发mutations
})

mutations

当执行程序时state突然发生变化成为mutations
mutation的第一个参数是网站的state


const mutations = {
  increment(state) { // 每个mutations方法里第一个参数都是state
    state.count++
  },
  decrement(state) {
    state.count--
  }
}

actions

actions引起副作用和异步操作的函数
actions可以包含任意异步操作
actions不改变state只进行commit到mutations

const actions = {
  increment: ({ commit }) => commit('increment'),
  decrement: ({ commt }) => commit('decrement'),
  incrementIfOdd({ commit, state }) {
    if ((state.count + 1) % 2 === 0) {
      commit('increment ')
    }
  },
  incrementAsync({
    commit
  }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('increment')
        resolve()
      }, 1000)
    })
  }
}

getters

可以当做计算属性来写,所有的getter接受一个完整的state做第一个参数

const getters = {
  evenOrOdd: state => state.count % 2 === 0 ? '偶数' : '奇数'
}

模板里

<template>
  <div id="app">
    <!--file : /my-project/src/vuex-demo/v02_counter.vue -->
    <h1>点击: {{ $store.state.count }} 次数,此為 {{ evenOrOdd }} <br></h1>
    <button class="btn"  @click="increment">+</button>
    <button class="btn"  @click="decrement">-</button><br>
    <button class="btn"  @click="incrementIfOdd">业务设计:当 奇数时,才增加</button><br>
    <button class="btn"  @click="incrementAsync">业务设计:1秒后,才会增加 1</button><br>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex' // 使用了mapGetters和mapActions
export default {
  computed: mapGetters([ // 当做了计算属性来写,操作是在store.js里
    'evenOrOdd' 
  ]),
  methods: mapActions([ // 执行actions, actions 中commit到mutations在store.js里
    'increment',
    'decrement',
    'incrementIfOdd',
    'incrementAsync'
  ])
}
</script>
上一篇 下一篇

猜你喜欢

热点阅读