首页 > 解决方案 > 获取后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>

非常感谢,求帮助!

标签: javascriptwordpressapivue.jsfetch

解决方案


你有一个反应性警告,所以你应该使用this.$set函数:

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

并且id应该声明该属性:

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


推荐阅读