vuex的使用

在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;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值