vuex仓库请求数据 请求到的数据然后再组件中获取数据

vuex仓库请求数据 请求到的数据然后再组件中获取数据

先是在vuex仓库当中写请求数据
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
    
    
  state: {
    
    
    cartListGet: []
  },
  mutations: {
    
    
    // 加入购物车数据
    GETDATACART(state, pylaod) {
    
    
      state.cartListGet = pylaod
      console.log(state.cartListGet)
    }
  },
  actions: {
    
    
    // 请求购物车数据
    getCartList(conText, pylaod) {
    
    
      axios({
    
    
        url: 'http://localhost:8081/wx/cart/index',
        headers: {
    
    
          'X-Litemall-Token': localStorage.getItem('X-Litemall-Token')
        }
      }).then(res => {
    
    
        // console.log(res.data.data)
        if(res.status === 200) {
    
    
          // conText就等于$store  commit当要修改的时候 
          conText.commit('GETDATACART', res.data.data.cartList)
        }
      })
    }
  },
})

请求完之后想要组件中获取数据的时候 这样写
mounted() {
    
    
    // 当仓库请求到的数据 想要获取仓库请求到的数据 这个地方要这样做
    this.$store.dispatch('getCartList')
    this.cartGetList = this.$store.state.cartListGet
    // console.log(this.cartGetList)
}

猜你喜欢

转载自blog.csdn.net/qq_53135313/article/details/129306650
今日推荐