首页 > 解决方案 > Vue js 函数 countSubcategories() 返回 [object Promise]

问题描述

countSubcategories() 函数返回 [object Promise],它应该返回映射子类别的行数。

这段代码在 vue.js 和 Laravel 中,对此有什么建议吗?

<div v-for="(cat,index) in cats.data" :key="cat.id">

  {{  countSubcategories(cat.id) }}  // Here subcategories row counts should be displayed.

 </div>


 <script>
export default {
  data() {
    return {
      cats: {},
      childcounts: ""
    };
  },

  created() {
    this.getCategories();
  },

  methods: {
    countSubcategories(id) {
      return axios
        .get("/api/user-permission-child-count/" + `${id}`)
        .then(response => {
          this.childcounts = response.data;
          return response.data;
        });
    },

    getCategories(page) {
      if (typeof page === "undefined") {
        page = 1;
      }
      let url = helper.getFilterURL(this.filterpartnerForm);
      axios
        .get("/api/get-user-permission-categories?page=" + page + url)
        .then(response => (this.cats = response.data));
    }
  }
};
</script> 

标签: laravelvue.jspromise

解决方案


正如 Aron 在上一个答案中所说,当您直接从模板调用时,在呈现模板时信息还没有准备好。

据我了解,您需要先运行 getCategories ,然后才能获取其余数据,对吗?

如果是这样,我有一个建议:

将一组猫 ID 发送到您的后端,您可以在那里发回您需要的子类别列表,这个这个是很好的资源,所以请阅读。

而不是有 2 个 getCategories 和 countSubcategories 你可以“合并”然后像这样:

fetchCategoriesAndSubcategories(page) {
  if (typeof page === "undefined") {
    page = 1;
  }
  let url = helper.getFilterURL(this.filterpartnerForm);
  axios
    .get("/api/get-user-permission-categories?page=" + page + url)
    .then(response => {
      this.cats = response.data;
      let catIds = this.cats.map(cat => (cat.id));
      return this.countSubcategories(catIds) // dont forget to change your  REST endpoint to manage receiving an array of ids 
    })
    .then(response => {
      this.childcounts = response.data
    });
}

Promises 允许您在和链中返回 Promise .then 方法

因此,在您的 created() 中,您可以调用 this.fetchCategoriesAndSubcategories 传递您需要的数据。你也可以通过添加一个 v-if 来更新你的模板,这样它就不会在 promise 没有完成加载时抛出错误。像这样的东西:

<div v-if="childCounts" v-for="(subcategorie, index) in childCounts" :key="subcategorie.id">

  {{ subcategorie }}  // Here subcategories row counts should be displayed.

 </div> 

推荐阅读