1、State
this.$store.state.count
不要直接改变 state, 通过提交 mutation 的方式,而非直接改变 store.state.count
2、mutatioins
this.$store.commit('方法名','载荷(参数) { Object } 对象的形式')
这里是官方介绍的传参风格
store.commit({ type: '方法名', amount: 10 // 参数 })
当使用风格的提交方式,整个对象都作为载荷 穿给 mutaions, mutasions 中的写法如下:
3、actions(记得这是异步)
store.js
const store = new Vuex.Store({ state:{ loading: false, todoList : [ {id:1,name:'11'}, {id:2,name:'22'}, {id:3,name:'33'}, ], num: 0, }, mutations:{ setNumIs5(state){ state.num = 5 }, setNumIsWhat(state,payload){ state.num = payload.num } }, actions:{ <----- 增加actions属性 setNum(context){ <----- 增加setNum方法,默认第一个参数是content,其值是复制的一份store return new Promise((resolve)=>{ <----- 返回一个promise,我们模拟一个异步操作,1秒后修改num为5 setTimeout(()=>{ context.commit('setNumIs5') resolve() },1000) }) } } })
actions 中调用 state、 mutations、 getters 的语法
context.commit 提交一个mutations
context.state 获取 state
context.getters 获取 getters
可以进行解构,简化写法
*.vue
async () => { await this.$store.dispath('actions 方法名') }
actions 中的传参,模仿 mutations 进行传参
actions:{ setNum(content,payload){ <----- 增加payload载荷 return new Promise((resolve)=>{ setTimeout(()=>{ console.log('测试载荷---'+payload.id); <----- 测试载荷输出 content.commit('setNumIs5') resolve() },1000) }) } } await this.$store.dispatch('setNum',{id:111}) <------ App.vue里调用的时候加上载荷(传参)即可
组合 Action
// 假设 getData() 和 getOtherData() 返回的是 Promise actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // 等待 actionA 完成 commit('gotOtherData', await getOtherData()) } }
************************************* 华丽的分割线 😊***************************************************
辅助函数的使用
辅助函数使用之前,需要先引入
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
为了好记忆,下面辅助函数中,本人都是传入对象的形式, 数组形式也是可以的。
computed: { // 使用对象展开运算符将此对象混入到外部对象中 ...mapState({ count }) }
...mapMutations({ 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')` })
methods:{ ...mapMutations({ setNumIsWhatAlias:'setNumIsWhat' }), ...mapActions({ <----- 就像这样,解构到methods中 'setNum', myname:'setNum'//自定义名称 }) } await this.setNum({id:222}) <----- 这样调用即可
人生很漫长,或许我只是你人生中微不足道的一小段,只是你人生中的惊鸿一瞥。