Vue在获取后未显示类别

问题描述

大家好,我需要Vue渲染方面的帮助。 我正在制作Vue-wordpress应用,并试图获取每个帖子的类别列表。从WP API支持的每个帖子的类别均作为其ID。我将类别ID作为道具传递给子元素(道具“ cats”),并在获取名称后尝试呈现它。但是在前端即时通讯上什么也看不到(在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>

非常感谢您的帮助!

解决方法

您有一个reactivity caveat,因此应使用this.$set函数:

 .then(res => (this.$set(this.categories,id,res.name)));

id属性应声明为:

 data() {
    return {
      categories: {
       id:null
       }
    };
  },