Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
store:数据中心
module:数据模型
index:实例化
页面数据(各种查询参数、api获取的结果数组)抽象,放在state中。
Vue页面初始化,主动dispatch触发Action请求API数据。
Actions获取API数据后,使用同步commit触发Mutations更新state。
Vue页面使用计算属性,绑定state中的数据,同步更新视图。
Vue页面参数改变,使用同步commit触发Mutations更新state。再使用dispatch触发Action重新请求API数据。
Vue=》dispatch(发送)=》Actions
Action=》commit(交托)=》Mutations(变化)
Mutations=》mutate(改变)=》State
State=》render(绘制)=》Vue
Vue=》commit(交托)=》Mutations(变化)
解构赋值
解析结构,然后自动赋值,简化程序员代码编写;
let obj={username:'java1234',age:31};
/*let username=obj.username; let age=obj.age;*/
let {username,age}=obj;
console.info(username,age);
import Vuex from 'vuex';
import Vue from 'vue';
import orderList from './modules/orderList';
Vue.use(Vuex);
export default new Vuex.Store({
modules:{
orderList
}
})
import Vue from 'vue';
const state={
orderList:[],
params:{}
}
//页面通过调用store的getters方法使用state
const getters={
getOrderList:state=>state.orderList
}
//actions 异步
const actions={
fetchOrderList({commit,state}){
Vue.http.post('/api/getOrderList',state.params)
.then((res)=>{
//actions中使用commit调用mutations
commit('updateOrderList',res.data.list)
},(err)=>{
console.log(err)
})
}
}
//mutations 同步
//vuex只允许mutations修改state
const mutations={
updateOrderList(state,payload){
state.orderList=payload
},
//页面参数更改,是同步动作。
updateParams(state,{key,val}){
state.params[key]=val
}
}
export default{
state,
getters,
actions,
mutations
}
import store from './store';
new Vue({
el:"#app",
router,
store,
template:'
components:{layout}
})
1、Vue页面初始化,mounted主动使用dispatch触发store中的actions,actions异步调用API获取数据。
2、actions中使用commit调用mutations。
3、mutations同步修改state。
4、Vue页面视图数据绑定计算属性,通过getters方法获取store中的state数据,渲染页面。
5、Vue页面参数改变,通过commit触发store中的mutation,mutation同步更新state中的参数。页面再使用dispatch重新触发store中的actions获取新的Api数据。