0

我在我的 VueJs 应用程序中使用 VueX,在我从服务器获得 4 个我的 get 请求的答案后,我需要关闭预加载器。我尝试使用回调函数来更改预加载器状态,但它会在请求开始后更改,但我需要在所有请求成功后更改预加载器状态。下面是我的代码:

索引.vue

<template>
 <div class="index">
  <div class="content-is-loading"
     v-if="appIsLoading"></div>
  <div v-else class="index__wrapper">
   <navbarInner></navbarInner>
   <div class="index__content">
    <sidebar></sidebar>
    <router-view></router-view>
   </div>
   <foo></foo>
  </div>
 </div>
</template>

<script>
import NavbarInner from './NavbarInner'
import Sidebar from './Sidebar'
import Foo from './../Foo'
import Shows from './Shows/Shows'
import Dashboard from './Dashboard'
import { API_URL } from '../../../config/constants'
import { mapState } from 'vuex'
export default {
 name: 'index',
 data () {
  return {
   appIsLoading: true,
   bandName: ''
  }
 },
components: {
 NavbarInner,
 Sidebar,
 Foo,
 Shows,
 Dashboard
},
created () {

 function loadData (context, callback) {
  // Loading bands for the user
  context.$store.dispatch('getBands')

  // Loading contacts for the user
  context.$store.dispatch('getContacts')

  // Loading merch for the user
  context.$store.dispatch('getInventory')

  // Loading tours for the active band
  context.$store.dispatch('getToursList')

  callback(context)
 }

 loadData(this, function (context) {
   context.appIsLoading = false
  })
 }
}

下面我添加一个请求的代码:api/tour.js

import axios from 'axios'
import { API_URL } from '../../config/constants'

export default {

 getToursList () {
  return new Promise((resolve, reject) => {
   let bandId = window.localStorage.getItem('active_band_id')
   let token = window.localStorage.getItem('token')
   axios.get(API_URL + '/api/bands/' + bandId + '/tours/', {
     headers: {'x-access-token': token}
   })
    .then((result) => {
      return resolve(result.data)
    })
    .catch(err => reject(err))
  })
 },

 getInventory () {
  return new Promise((resolve, reject) => {
   let token = window.localStorage.getItem('token')
    axios.get(API_URL + '/api/merch/listProductForUser/1000/0', {
     headers: {'x-access-token': token}
   })
    .then((response) => {
      let items = response.data
      return resolve(items)
    })
    .catch((err) => {
      return reject(err)
    })
   })
  },

 getContacts () {
  return new Promise((resolve, reject) => {
   let token = window.localStorage.getItem('token')
    axios.get(API_URL + '/api/contact/get_contacts_for_user/1000/0', {
     headers: {'x-access-token': token}
   })
    .then((response) => {
      console.log(response.data)
      let contacts = response.data
      return resolve(contacts)
    })
    .catch((err) => {
      return reject(err)
    })
  })
 },

 getBands () {
  return new Promise((resolve, reject) => {
   let token = window.localStorage.getItem('token')
    axios.get(API_URL + '/api/band/getBandsForUser/1000/0', {
     headers: {'x-access-token': token}
   })
    .then((response) => {
      console.log(response.data)
      let bands = response.data
      return resolve(bands)
    })
    .catch((err) => {
      return reject(err)
    })
  })
 }
}

Vuex/tour.js

import api from '../../api/onload'
import * as types from '../mutation-types'
const state = {
 tours: [],
 contacts: [],
 bands: [],
 merch: [],
 success: false,
 loading: false
}

const actions = {
 getToursList ({commit}) {
  api.getToursList()
   .then((tours) => {
    commit(types.RECEIVE_TOURS, tours)
   }).catch((err) => {
    console.error('Error receiving tours: ', err)
    commit(types.RECEIVE_TOURS_ERROR)
  })
},

getInventory ({commit}) {
 api.getInventory()
  .then((items) => {
    commit(types.RECEIVE_INVENTORY, items)
  })
  .catch((err) => {
    console.error('Error receiving inventory: ', err)
    commit(types.RECEIVE_INVENTORY_ERROR)
  })
},

getBands ({commit}) {
 api.getBands()
  .then((bands) => {
    commit(types.RECEIVE_BANDS, bands)
  })
  .catch((err) => {
    console.error('Error receiving bands: ', err)
    commit(types.RECEIVE_BANDS_ERROR)
  })
},

getContacts ({commit}) {
 api.getContacts()
  .then((contacts) => {
    commit(types.RECEIVE_CONTACTS, contacts)
  })
  .catch((err) => {
    console.error('Error receiving bands: ', err)
    commit(types.RECEIVE_CONTACTS_ERROR)
  })
 }
}

const mutations = {
 [types.RECEIVE_TOURS] (state, tours) {
  state.tours = tours
},

[types.RECEIVE_INVENTORY] (state, items) {
 state.items = items
},

[types.RECEIVE_BANDS] (state, bands) {
 state.bands = bands
},

[types.RECEIVE_CONTACTS] (state, contacts) {
  state.contacts = contacts
  console.log(state.contacts)
 }
}

export default {
 state, mutations, actions
}

我应该如何更改代码?

4

1 回答 1

1

您发布的代码实际上并没有等待您调用的任何操作的响应。

您还可以将所有内容移至方法并重构。

最后我假设你的行为会返回一个 Promise 即

created () {
  this.getAll()
},

methods: {

  getAll () {

    Promise.all([
        this.$store.dispatch('getBands'),
        this.$store.dispatch('getContacts'),
        this.$store.dispatch('getInventory'),
        this.$store.dispatch('getToursList'),
    ])
    .then(responseArray => {
        this.appIsLoading = false
    })
    .catch(error => { console.error(error) })

编辑

要让您的操作在您需要时解决(当突变已触发并且您的商店已更新时),您需要将它们包装在 Promise 中:

Vuex/tour.js(动作对象)

getToursList: ({ commit }) =>
    new Promise((resolve, reject) => {

        api.getToursList()
            .then((tours) => {
                commit(types.RECEIVE_TOURS, tours)
                resolve()
            }).catch((err) => {
                console.error('Error receiving tours: ', err)
                commit(types.RECEIVE_TOURS_ERROR)
                reject()
            })

    })
于 2016-11-27T20:17:53.467 回答