【VUEX】state、mutations、actions、getters、modules以及辅助函数mapState和mapGetters

Vuex

简介:vuex是vue.js的状态管理库

提供一种集中式存储管理应用程序中的所有组件的状态,并将其分离到一个可预测的状态容器中。

五个核心属性:state、mutations、actions、getters、modules
属性 作用
state 存放状态(数据),所有组件共享
mutations 唯一可以修改state的地方,改变state状态需要通过显示地commit(提交)mutation(同步)
actions 用于异步操作提交mutations,根据后端接口返回数据去commit更新数据
getters 获取state中的状态
modules 将store分割成模块,每个模块都拥有自己的state、mutation、action、getters和子模块,以便提高应用程序的可维护性
两个辅助函数:mapState、mapGetters
属性 作用 用法
mapState 将 store 中的 state 映射到局部计算属性 computed: {…mapState([‘count’, ‘xx’]),}
mapGetters 将 store 中的 getter 映射到局部计算属性 computed: {…mapGetters([‘count’, ‘xx’]),}

当一个组件需要获取多个状态的时候,可以使用 mapState或mapGetters 辅助函数帮助我们生成计算属性,减少冗余代码:

// store 中的 state、getter 映射到局部计算属性
import {
    
     mapState, mapGetters } from 'vuex'; 
computed: {
    
    
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState(['count']),
  ...mapGetters(['count']),
  localComputed () {
    
     /* ... */ },
}

可以通过 this.$store 访问store实例,从Store中读取state(状态),改变state状态需要通过显示地commit(提交)mutation;

//当有modules模块化时要注意提交commit需要加上文件名
this.$store.commit('app/SET_COUNT', 10)

猜你喜欢

转载自blog.csdn.net/sunshineTing2/article/details/131533088