vuex的核心由以下及部分组成:
1、state:里面就是存放项目中需要多组件共享的状态;
2、mutations:就是存放更改state里状态的方法;
3、getters:从state中派生出状态,比如将state中的某个状态进行过滤然后获取新的状态
4、actions:是mutations的加强版,塔可以通过commit mutations中的方法来改变状态,最重要的是它可以进行异步操作
5.modules:当用这个容器来装这些状态还是显得混乱的时候,我们就可以把容器分成几块,把状态和管理规则分类来装。这和我们创建js模块是一个目的,让代码结构更清晰。
// 实例化vuex状态库
var vuexStore = new Vuex.Store({
state:{
message:'Hello World',
bookList:[
{
name:'javascript权威指南',
price:100,
en:'jq'
},
{
name:'angularjs权威指南',
price:80,
en:'aq'
},
{
name:'HTTP权威指南',
price:50,
en:'hq'
}
]
},
mutations:{
//同步
showMessage:function(state,data){
state.message = 'Store mutations changed this words。'+data;
}
addBook:function(state,data){
state.bookList.push(data)
}
},
getters:{
filterPrice:function(state){
var narr = [];
for(var i = 0;i<state.bookList.length;i++){
state.bookList[i].price<85 ? narr.push(state.bookList[i]) : null;
}
return narr;
}
},
actions:{
//异步操作
addBook:function(context){
setTimeout(function(){
context.commit('addBook',{name:'HTML5权威指南',price:75});
},2000);
}
},
modules:{
a:storeA,b:storeB
}
});
// vue 实例
var vm = new Vue({
el:'app',
store:VuexStore,
methods:{
showMessage:function(){
this.$store.commit('showMessage','荷载数据')
},
filterList:function(){
return this.store.getters.filterPrice();
},
addBooks:function(){
this.$store.dispatch('addBook')
},
}
});