介绍

Vuex是一个专门为vue.js应用程序开发的状态管理模式,四个部分

(1)、state:单一状态树,每个应用仅仅包含一个sate实例,使用时

  • this.$store.state.状态名字 (使用)
  • …mapState([“title”])

(2)、getters:从store中的state中派生出一些状态,可以认为是state的计算属性

  • this.$store.getters.计算属性名字 (使用)
  • …mapGetters([“getFilms”])

(3)、mutations:更改Vuex的store中的状态的唯一方法

  • 常量的设计风格
1
2
3
[SOME_MUTATION](state){
    // mutate state
}
  • 必须是同步函数
  • this.$store.commit(“type”,“payload”)(调用)

(4)、actions:

  • Action 提交的是mulation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
  • this.$store.dispatch(“type”,“payload”)

(5)、基础模板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// module 模板
const store = new Vuex.Store({
    state:{
        count:0
    },
    mutations:{
        increment(state,payload){

        }
    },
    actions:{
        increment(context,payload){
            context.commit("increment");
        }
    }
})

(6)、注意

  • 应用层级的状态应该集中到单个store对象中

  • 提交mulation是更改状态的唯一方法,并且这个过程是同步的

  • 异步逻辑都应该封装到action里面

  • 其他 查看vuex数据流可以使用 vue chrome devtools此工具