首页 > 解决方案 > 如何调用 API 以使其返回您请求的任何内容以及如何减少 Vuejs 中的观察者数量

问题描述

如您所见,在我的代码中,我正在调用一个返回链接的 api,但是我还想从 api 中获得其他东西,所以我将如何修改该函数,以便获得类似标题的东西来自 api 的动画或它拥有的剧集列表 此外,如果我确实获得了标题或剧集列表,我是否必须开始观看更多内容?有没有解决的办法?

<template>
  <section class="container">
    <div class="column">
      <img :src="url1" alt="./assets/notFound.png" />
    </div>

    <div class="column">
      <img :src="url2" alt="./assets/notFound.png" />
    </div>
  </section>
</template>

<script>
import axios from "axios";
import Buefy from "buefy";
import "buefy/dist/buefy.css";
import Vue from "vue";
Vue.use(Buefy);

export default {
  props: {
    anime1: String,
    anime2: String,
  },
  data() {
    return {
      url1: "",
      url2: "",
      error: "",
    };
  },
  methods: {
    animeFind(anime, data) {
      axios
        .get(`https://api.jikan.moe/v3/search/anime?q=${anime}`)
        .then((response) => {
          const id = response.data["results"][0]["mal_id"];
          axios
            .get(`https://api.jikan.moe/v3/anime/${id}`)
            .then((response) => (this[data] = response.data["image_url"]));
        })
        .catch((error) => {
          this.error = error; // take care of this later
        });
    },
  },

  watch: {
    anime1: {
      immediate: true,
      // eslint-disable-next-line no-unused-vars
      handler(newVal, oldVal) {
        this.animeFind(newVal, "url1");
      },
    },
    anime2: {
      immediate: true,
      // eslint-disable-next-line no-unused-vars
      handler(newVal, oldVal) {
        this.animeFind(newVal, "url2");
      },
    },
  },
};
</script>

标签: javascriptvue.jsvuejs2

解决方案


首先:要找出您正在使用的 api 的结果,您可以

axios
    .get(`https://api.jikan.moe/v3/search/anime?q=${anime}`)
    .then((response) => {
      const id = response.data["results"][0]["mal_id"];
      axios
        .get(`https://api.jikan.moe/v3/anime/${id}`)
        .then((response) => {
           console.log(response)
         });
    })

在您 console.log() 您的响应之后,尝试在浏览器控制台中查看结果,之后您可以使用响应键获取所需的所有数据

this.key = response.data.[key]

不要忘记在数据对象中添加您要查找的键

data() {
return {
  url1: "",
  url2: "",
  key1: "",
  key2: "",
  error: "",
};},

推荐阅读