vuex 状态管理state、getter、mutation和action

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37068028/article/details/79860553

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。然而在生产环境中,就不能使用了。

猜你喜欢

转载自blog.csdn.net/m0_37068028/article/details/79860553