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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值