V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
zzlit
V2EX  ›  前端开发

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

  •  
  •   zzlit · 2019-03-26 20:13:22 +08:00 · 2293 次点击
    这是一个创建于 1829 天前的主题,其中的信息可能已经有所发展或是发生改变。
      // 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) // 空数组
     }
    

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

    5 条回复    2019-03-26 20:48:55 +08:00
    ayase252
        1
    ayase252  
       2019-03-26 20:23:51 +08:00
    请求还没有返回吧
    zzlit
        2
    zzlit  
    OP
       2019-03-26 20:27:41 +08:00
    @ayase252 大致意思就是说在请求的过程中就把我已开始定义的那个空数组打印出来了,的确是还没有返回然后 commit,后面我在另一个点击事件里面能把这个值 console 出来,所以我现在就是想一开始就能等它请求完再 commit,这个该怎么写,请大佬指点一下
    rabbbit
        3
    rabbbit  
       2019-03-26 20:35:03 +08:00   ❤️ 1
    拿 Promise 包起来返回后接 then 打印,或者 watch 那个变量
    zzlit
        5
    zzlit  
    OP
       2019-03-26 20:48:55 +08:00
    @rabbbit 感谢!的确是这样子的,我文档没有看仔细
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2672 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 15:46 · PVG 23:46 · LAX 08:46 · JFK 11:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.