vuex (状态管理)
1.网站很多数据,很多组件,共享状态
2.直接做法,通过事件(even bus)
3.状态管理的模型: 每个组件更新,数组中心触发每个更新组件
4.v组件 –> Actions –> Mutations (动作) –> State(数据中心状态)–> 反映到页面的组件渲染
5.Actions(异步操作) –> Mutations(同步) –> 数据的单向流动
6.安装vuex : cnpm install vuex –save
7.引入vuex : import Vuex from ‘vuex’
Vue.use(Vuex)
let store = new Vuex.store({ })
8.let store = new Vuex.store({
state :{
totalPrice: 0 (数据中心存储的数据)
},
mutations : {
increment (state,price) {
state.totalPrice += price
},
decrement (state,price) {
state.totalPrice -= price
}
}
})
在全局函数注册组件,挂载 new Vue({ store })
increment : 增加
decrement : 减少
9. 可以在每一个子组件里 通过 this.$store.state.totalPrice
(调用或触发里面的方法或状态)
10.App.vue 引入两个组件,在根元素上面以标签显示.每个组件里面有两个按钮,一个是加1,一个是减1;在methods里面写方法 , 调用this.$store.commit('increment(Mutations)',this.price)
this.$store.commit
方法
11.在数据中调用状态: 通过computed : { }
计算属性
totalPrice () { return this.$store.state.totalPrice }
12.vuex 状态管理数据,点击不同模块的操作,不需要发送事件,通过调用数据中心的Mutations,实现模块间共享的功能;
13.actions : 在Mutations之前的动作,只能调用Mutations,不可以更改state
actions : {
increase (content,price) {
content.commit('increment',price)
},
}
在methods里面写方法 , 调用this.$store.dispatch(‘increase(actions)’,this.price)
14.Mutations 和 actions 不同: actions可以进行异步的操作,Mutations 是同步的,跟后端的接口必须放在actions 里面 ( 产品的id ,api请求id ,请求回来的价格再执行)
actions : {
increase (content,id) {
api(id,function (price) {
content.commit('increment',price)
})
},
}
思路:
15.Mutations 只能根据从上向下流的事件,不可以异步.
16.getters : 获取状态集里面的数据,设置不同的getters
getters : {
getTotal (state) { // 不用每次都从数据集里面拿数据
return state.totalPrice // 获取的数据
}
}
从app.vue 里面的computed : { totalPrice () { return this.$store.getters.getTotal }}
17. moduleA 分为不同的模型
18.所有的应用层级放在store –> 更改数据中心(Mutations) –> 异步请求的数据的(actions).
19. index.html –> main.js –> api( –> Api) –> component (App.vue …) –> store –> index.js [对外接口,统一输出接口]–> actions.js (异步的逻辑)–> Mutations.js [全局]–> modules ( cart.js [购物车]–> products.js[产品])
20.vues/vuex : github平台 案列