1、vue cil 4.x版本支持vuex 3版本
npm install vue@3
2、cli安装
import Vuex from "vuex"
Vue.use(Vuex);
3、分模块
let counter={
namespaced:true,
state:{
count:100,
users:[
{id:1,name:"张三",age:18},
{id:2,name:"李四",age:22},
{id:3,name:"王五",age:25},
{id:4,name:"赵六",age:26}
]
},
getters:{
/*
第一个参数:本地模块中的state
第二个参数:其它getter
第三个参数:所有模块的state
*/
getUsers(state,getters,rootState){
let users=state.users.filter(res=>res.age>18);
return users
}
},
mutations:{
inc(state,payload){
console.log(state,payload);
state.count+=payload.amount;
}
},
actions:{
asyncInc(conText,payload){
setTimeout(()=>{
console.log(conText,payload)
conText.commit("inc",payload)
},30)
}
}
}
let cart={
namespaced:true,
state:{
count:0
},
mutations:{
inc(state,payload){
state.count+=payload.amount;
}
}
}
4、store加载模块
let store=new Vuex.Store({
modules:{
counter,
cart
}
});
5、vue引入模块
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
6、组件内部引入vuex
import {mapState,mapGetters,mapMutations,mapActions} from "vuex";
7、操作函数
created(){
console.log(this.$store.state.counter.count)
},
methods:{
goShopping(url){
window.location.href=url
},
handleClick(){
this.$emit('handleClick', "我是子组件");
},
...mapMutations({
inc:"counter/inc",
cartInc:"cart/inc"
}),
...mapActions({
asyncInc:"counter/asyncInc"
}),
increment(){
// this.$store.commit("inc",{amount:10})
// this.inc({amount:10})
// this.$store.dispatch("asyncInc",{amount:10})
this.asyncInc({amount:10})
},
cartIncrement(){
this.cartInc({amount:1})
}
},
computed:{
...mapState({
count:state=>state.counter.count,
}),
...mapGetters(['counter/getUsers'])
}
8、页面导入
<div>
计数器{{$store.state.counter.count}},{{count}}
<button type="button" @click="increment">+</button>
购物车数量:{{$store.state.cart.count}}
<button type="button" @click="cartIncrement">+</button>
</div>
<ul>
<li v-for="item in getUsers" :key="item.id">
{{item.name}}--{{item.age}}
</li>
</ul>
</div>