请教一个关于使用 vuex 存储请求数据的问题

2019-03-26 20:13:22 +08:00
 zzlit
  // store.js
  state: {
    shopList: []
  },
  mutations: {
    changeShopList (state, arr) {
      state.shopList = arr
    }
  },
  actions: {
    getShopList ({ commit, state }) {
      global.axios.get(url).then(res => {
        let { data: { code, data: { list } } } = res
        if (+code === 200) {
          list.unshift({ id: 0, shop_name: '全部门店' })
          commit('changeShopList', list)
        }
      })
    }
  }
  // index.vue
 computed: {
   shopList () {
     console.log('computed', this.$store.state.shopList) // 空数组
     return this.$store.state.shopList
   }
 },
 created () {
   this.$store.dispatch('getShopList')
   console.log('created', this.shopList) // 空数组
 }

现在问题是我需要打印出来请求到的数据而不是一开始定义的空数组,请教大佬怎么解决这个问题?

2312 次点击
所在节点    前端开发
5 条回复
ayase252
2019-03-26 20:23:51 +08:00
请求还没有返回吧
zzlit
2019-03-26 20:27:41 +08:00
@ayase252 大致意思就是说在请求的过程中就把我已开始定义的那个空数组打印出来了,的确是还没有返回然后 commit,后面我在另一个点击事件里面能把这个值 console 出来,所以我现在就是想一开始就能等它请求完再 commit,这个该怎么写,请大佬指点一下
rabbbit
2019-03-26 20:35:03 +08:00
拿 Promise 包起来返回后接 then 打印,或者 watch 那个变量
rabbbit
2019-03-26 20:36:56 +08:00
zzlit
2019-03-26 20:48:55 +08:00
@rabbbit 感谢!的确是这样子的,我文档没有看仔细

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/548879

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX