vuex

vue
上图是官网中的vue的介绍(vuex官网

  1. state(相当于vue中的data)
    使用: this.$store.state.属性
    辅助函数: mapState
import { mapState } from 'vuex'
export default {
  computed: mapState({
    count: state => state.count,
    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
    test (){
    //自己定义的方法
    }
  })
}
// 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    count: state => state.count
  })
  test () {
  // 自己定义的方法
  }
  1. getter(相当于vue中的计算属性,使用时也放在computed中)
    使用: this.$store.getters.属性
    辅助函数:mapGetter
import { mapGetters } from 'vuex'
export default {
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // 给属性另起名字,使用对象的方式
      // doneCount: 'doneTodosCount'
    ])
  }
}
  1. mutation(必须是同步函数,我理解的mutation就是一个事件)
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }

使用

//方式一
store.commit('increment',params) //第二个参数可以传参
//方式二
store.commit({
  type: 'increment',
  amount: 10
})

辅助函数:mapMutations

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')`
    })
  }
}
  1. action
    action 提交的是 mutation,而不是直接变更状态。
    action 可以包含任意异步操作。
 mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {  //可以在action里执行异步操作
    increment (context) {
      context.commit('increment')
    }
  }
使用: store.dispatch('increment')   //分发action
//有参数时
// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

辅助函数: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')`
    })
  }
}
  1. modules(当有多个模块时使用)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值