vuex
需要说明的以下都不是我写的,只是笔记,方便我看,记在纸上容易丢
vuex笔记:
写的蛮好的,简单易懂: 链接。
1.state,共享状态,相当于只读属性。在组件页面,可以通过辅助函数在computed里面接收,形式有对象如,mapState({count:‘ ’})。数组形式接收如:computed: mapState(['count']);
2.mutation,改变状态的方法,只能通过mutation改变state状态,store.commit()方法触发mutation改变state;
3. getters,对state对象进行处理计算,方便在store中做集中的处理。getters接受state作为第一个参数,通过this.$store.getters调用,也可以接受其他getters作为第二个人参数。在组件页面,使用computed接收,形式如下: computed: {...mapGetters(['countGetter'])};
4.mutation,更改vuex的staore中的状态的唯一方法就是mutations,每一个mutation都有一个事件类型type和一个回调函数handler,调用mutation,需要通过store.commit方法调用mutation type,形式:store.commit('方法名'),也可以传入第二个参数,就是mutation的payload,所以在mutaion:{中 funName(state, payload){对state进行处理操作},
store.commit({type:'funName',aa:10,bb:20}),
nutaion的映射函数mapMutations,辅助函数简化代码,在组件的methods映射为store.commit调用,写法形式如下:
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment' // 映射 this.increment() 为 this.$store.commit('increment')
]),
...mapMutations({
add: 'increment' // 映射 this.add() 为 this.$store.commit('increment')
})
},
mutation必须为同步函数,异步操作用actions
}
所以在vue的computed计算属性中会存在两种辅助函数:
import { mapState, mapGetters } form 'vuex';
export default {
// ...
computed: {
mapState({ ... }),
mapGetter({ ... })
}
}
作者:Yeaseon_Zhang
链接:https://juejin.cn/post/6844903470219149326
作者本人的博客地址:https://yeaseonzhang.github.io/
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

浙公网安备 33010602011771号