在src下面新建一个文件夹 store
index.js文件
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
Vue.use(Vuex);
const state = {
name:'',//名字
count:0 //商品数量
}
export default new Vuex.Store({
state,
mutations,
actions
});
在main.js 挂载
import store from './store'
在组件中使用
1.第一种方式
//获取state的值
computed:{
name(){
return this.$store.state.name;
},
count(){
return this.$store.state.count;
}
},
methods:{
// 获取商品数量
getCartCount(){
this.axios.get('/carts/products/sum').then((res=0)=>{
this.$store.dispatch('saveCount',res);
})
},
// 获取用户名称
login(){
this.axios.post('/user/login',{
username,
password
}).then((res)=>{
this.$store.dispatch('saveName',res.username);
})
},
},
2.第二种方式
import {mapState, mapActions } from ‘vuex’;
computed:{
/*username(){
return this.$store.state.username;
},
cartCount(){
return this.$store.state.cartCount;
}*/
...mapState(['name','count'])
},
methods:{
...mapActions(['saverName','saveCount']),
// 获取商品数量
getCartCount(){
this.axios.get('/carts/products/sum').then((res=0)=>{
// this.$store.dispatch('saveCount',res);
this.saveCount(res);
})
},
// 获取用户名称
login(){
this.axios.post('/user/login',{
username,
password
}).then((res)=>{
// this.$store.dispatch('saveName',res.username);
this.saveName(res.username);
})
},
},
action.js文件
export default {
saveName(context,username){
context.commit('saveName', username);
},
saveCount(context, count) {
context.commit('saveCount', count);
}
}
mutations.js文件
export default {
saveName(state, username) {
state.name = username;
},
saveCount(state, count) {
state.count = count;
}
}