【问题标题】:Shopping Cart with Vue and Vuex使用 Vue 和 Vuex 的购物车
【发布时间】:2020-01-10 18:58:30
【问题描述】:

我从https://github.com/vueschool/learn-vuex 克隆了这个很棒的购物车存储库,它运行良好,但不能处理我的用例的数据。对于使用过此 repo 的任何人,我如何通过从数据库或 Api 获取产品来扩展它?

Shop.js

const _products = [
{"id": 1, "title": "iPad 4 Mini", "price": 500.01, "inventory": 2},
{"id": 2, "title": "H&M T-Shirt White", "price": 10.99, 
"inventory": 10},
{"id": 3, "title": "Charli XCX - Sucker CD", "price": 19.99, 
"inventory": 5}
  ]

export default {
getProducts (cb) {
    setTimeout(() => cb(_products), 100)
   },
buyProducts (products, cb, errorCb) {
    setTimeout(() => {
    // simulate random checkout failure.
    (Math.random() > 0.5 || 
navigator.userAgent.indexOf('PhantomJS') > -1)
    ? cb()
    : errorCb()
}, 100)
 }
}

通过 vuex 操作调用商店

actions: {
   fetchProducts({commit}) {
     return new Promise((resolve, reject) => {
    // make the call
    // call setProducts mutation
    shop.getProducts(products => {
      commit('setProducts', products)
      resolve()
    })
  })
 }

【问题讨论】:

  • Promise 之后的then 在哪里?

标签: vue.js vuex vue-router


【解决方案1】:

您可以使用axios调用服务器,获取如下产品

export default new Vuex.Store({
    state: {
        products: {},
    },
    actions: {
        getProducts({commit},data) {
            axios.get(`api/product?page=`+ data.page + '&orderBy='+ data.orderBy).then((response) => {
            commit('updateProducts', response.data);
        })
    },
    mutations: {
        updateProducts (state, products) {
            state.products = products
        }
    }
});

【讨论】:

猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 2021-03-17
  • 2017-11-05
相关资源
最近更新 更多