繁体   English   中英

如何调用 API 以返回您请求的任何内容以及如何减少 Vuejs 中的观察者数量

[英]How to make a call to a API so that it returns whatever you're requesting and how to reduce the amount of watchers in 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>

首先:要找出您正在使用的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: "",
};},

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM