1. 程式人生 > >vuex 狀態管理state、getter、mutation和action

vuex 狀態管理state、getter、mutation和action

vuex 狀態管理

1. state的三種用法

  • 直接獲取store的state
computed: {
  count () {
    return this.$store.state.count
    }
  }
  • 從mapState中獲取
computed: {
  ...mapState(['count'])
}
  • 在mapState中定義別名
computed: {
  ...mapState({
    count: (state) => state.count
  })
}

2. getter 獲取計算後的state

// getter.js
fullName (state) {
  return `${state.firstName} ${state.lastName}`
}
  • 從store的getters中獲取
computed: {
  fullName () {
    return this.$store.getters.fullName
  }
}
  • 在mapGetters中獲取
computed: {
  ...mapGetters(['fullName'])
}

3. mutation 更改state

// mutations.js
updateCount (state, {num}
) { state.count = num }
  • 使用store的commit觸發mutation
mounted () {
  setInterval(() => {
    this.$store.commit('updateCount', { num: num++ })
  }, 1000)
}
  • 使用mapMutations
methods: {
  ...mapMutations(['updateCount'])
}

此時updateCount的用法

mounted () {
  setInterval(() => {
    this
.updateCount({ num: num++ }) }, 1000)
}

4. action 非同步修改state

// action.js
updateCountAsync (store, data) {
  setTimeout(() => {
    store.commit('updateCount', {num: data.num})
  }, data.time)
}
  • 使用store的dispatch 觸發action
mounted () {
  this.$store.dispatch('updateCountAsync', {num: 3, time: 2000})
}
  • 使用mapActions
methods: {
  ...mapActions(['updateCountAsync'])
}

此時updateCountAsync的用法

mounted () {
  this.updateCountAsync({
    num: 3,
    time: 2000
  })
}

stroe.js

import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './action/action'

const isDev = process.env.NODE_ENV === 'development'

export default () => {
  return new Vuex.Store({
    strict: isDev,
    state: defaultState,
    mutations,
    getters,
    actions
  })
}

store例項中配置strict為true時,在開發中不允許直接修改store的內容,控制檯會有warning。然而在生產環境中,就不能使用了。