javascript - 获取后Vue不显示类别
问题描述
大家好,我需要一些关于 Vue 渲染的帮助。我正在制作 Vue-Wordpress 应用程序,并尝试获取每个帖子的类别列表。从 WP API 支持的每个帖子的类别作为它的 id。我将类别 ID 作为子元素(道具“猫”)中的道具传输,并在获取名称后尝试呈现它。但是在前端我什么都看不到(在 Vue 仪表板中,我得到了类别名称列表,抱歉我不能用它发布图像)
<template>
<div class="bg-white border rounded border-black border-collapse">
<h2 class="font-bold text-xl p-2 hover:text-gray-600 cursor-pointer">{{ title }}</h2>
<div
class="w-full h-48 bg-cover bg-center"
:style="{ 'background-image': 'url(' + image + ')' }"
></div>
<div class="px-4 py-2">
<p class="text-gray-700 h-40 text-base" v-html="content"></p>
<div>
<span
v-for="(val, index) in categories"
:key="index"
class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2"
>{{val}}</span>
</div>
</div>
</div>
</template>
<script>
export default {
props: ["title", "content", "image", "cats"],
data() {
return {
categories: {}
};
},
created() {
this.getAll();
},
methods: {
getAll: function() {
this.$props.cats.forEach(r => this.getCatName(r));
},
getCatName: function(id) {
fetch(`http://rest-api.local/wp-json/wp/v2/categories/${id}`)
.then(r => r.json())
.then(res => (this.categories[id] = res.name));
}
}
};
</script>
非常感谢,求帮助!
解决方案
你有一个反应性警告,所以你应该使用this.$set
函数:
.then(res => (this.$set(this.categories,id,res.name)));
并且id
应该声明该属性:
data() {
return {
categories: {
id:null
}
};
},
推荐阅读
- winapi - 我如何知道该过程是手动运行还是通过 Windows 启动?
- jquery - 如何修复导航栏后面的空白
- javascript - 为什么我的图像不会出现在画布上?
- c++ - Getline跳过最后一个分号(csv)c ++
- twitter-bootstrap - 移动问题,修改引导类或错误的媒体查询
- apache-spark - Databricks - 创建永久用户定义函数 (UDF)
- excel - 我可以使用 IF 语句将一个数字乘以 Excel 中的数字列表/范围吗?
- java - 从 IntentService 向 BroadcastReceiver 发送数据
- mxgraph - 悬停在 mxgraph 顶点上时有没有办法移动 x ?
- python - 使用标识符列表格式化 CREATE TABLE 查询