laravel - 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>
解决方案
正如 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>
推荐阅读
- git - Merge git repo branch (with different history) into master branch
- java - 如何在一对多关系中处理 Thymeleaf 和 Spring 中的表单?
- python - 如何在 Visual Studio 的 Python 项目中包含多个 .py 文件
- javascript - typescript 参数中允许的最小数量
- python - 实现合并排序时出错 [AttributeError: 'int' object has no attribute 'data']
- typescript - 为什么这个打字稿类型保护不起作用
- javascript - 使用 styled-components 在循环中添加样式不同的组件
- python - 带有宽“笔”的 PyQt5 drawArc
- python - 有没有办法可以返回数据并提供额外的参数,python3 @click
- c++ - 用 const char *str="Hello" 在 C++ 中定义一个字符串;