当声明的参数从空字符串更改时 Vue 发送请求

Vue send request when declared params changed from empty string

在我的应用程序中,我向我的后端应用程序发送了一个请求,我从中收到了一个 ID 类似于 { 'id': '12345'} 的响应。我将这个 id 保存为 loadId 内部数据,这里:

export default {
  name: 'SyncProducts',
  data() {
    return {
      loadId: '',

现在,当此数据 loadId 从空变为空时,我想发送另一个 POST fetchSyncedProductsResultRequest。如何操作?

在我的代码下面:

imports.js

const createApparelMagicProductsRequest = (self, products) => {
  const jwtToken = self.$store.state.idToken;
  console.log(products)
  console.log()
  const payload = JSON.stringify({ product_codes: products['product_codes'].split(',') })

  return axios
    .post(`/api/v1/imports/products_batches`, payload,{
      headers: {
        Authorization: `Bearer ${jwtToken}`,
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    .then(response => response.data['id'])
};

const fetchSyncedProductsResultRequest = (token, id) => {
  return axios
    .get(`/api/v1/imports/products_batches`, {
      params: { id: id },
      headers: {
        Authorization: `Bearer ${token}`,
      }
    })
    .then(response => {
      return response.data['result']
    })
};

sync_products.vue

<script>

import {
  fetchSyncedProductsResultRequest,
  createApparelMagicProductsRequest
} from '../../api/imports'

export default {
  name: 'SyncProducts',
  data() {
    return {
      styleCodes: [],
      fetchedProductSyncResult: [],
      loadId: '',
    }
  },
  async mounted() {
    await fetchSyncedProductsResultRequest(this, load.id)
    this.syncedProductsFetched = true
    this.pageChanged(this.currentPage)
  },
  async mounted() {
    const jwtToken = this.$store.state.idToken;
    fetchSyncedProductsResultRequest(jwtToken).then(data => {
      this.fetchedProductSyncResult = data
    })
  },


</script>

loadId 上使用 watcher,如果它从空字符串更改为 non-empty 字符串,则用新值调用 fetchSyncedProductsResultRequest()

export default {
  watch: {
    loadId(newValue, oldValue) {
      if (!oldValue && newValue) {
        const jwtToken = this.$store.state.idToken;
        fetchSyncedProductsResultRequest(jwtToken, newValue).then(data => {
          this.fetchedProductSyncResult = data
        });
      }
    }
  }
}

demo