工作流程
用户通过dispatch触发actions,actions通过commit提交到mutations,mutations改变了state,伴随着state改变会重新渲染组件
state
//调用
goods(){
return this.$store.state.goods
}
...mapState(['goods'])
//或者取别名
...mapState({
goodsList:state=>state.goods
})
getters
//store页面
goodsObj:state=>{
return state.goods
}
goodsById:state=>(id)=>{
return state.goods.filter(item=>item.id === id)//可以改成数值item.id 调用就可以直接写数字
}
goodsById:state=>{
return (id)=>{
return state.goods.filter(item=>(item.id - 0)=== id)
}
}
//调用
this.store.getters.goodsObj
this.store.getters.goodsById("1")//全等字符串和数值要分清
...mapGetters(['goodsObj'])
mutations
mutations:{
add(state,index){
state.goods[index].num++
state.totalNum ++
state.totalPrice += state.goods[index].price
}
}
//调用
handleAdd(index){
this.$store.commit("add",index)
}
//这种调用mutations里面add第二个参数要写{index} 因为这个打印出来是一个对象
this.$store.commit({
type:'add',
index,
})
actions
//actions的底层就是通过调用motations
//支持异步操作 (异步调用及修改,上面的mutations是同步,actions本质就是调用mutations修改的)
action:{
increment({commit},payload){
commit(ADD,payload)
}
}
//调用
this.$store.dispatch('increment',{index})
modules
//前面四个建单独的文件夹(我本人理解利于模块化开发)
modules:{
state,
getters,
mutations,
actions
}