【问题标题】:how to migrate from Nuxt 2 Axios to usefetch in Nuxt3如何从 Nuxt 2 Axios 迁移到 Nuxt3 中的 usefetch
【发布时间】:2022-11-11 09:39:09
【问题描述】:

我正在尝试将一个小项目从 Nuxt2 迁移到 Nuxt3。在 Nuxt2 中,我使用 axios 进行 API 调用。 现在我想在 nuxt3 中获取,但 Axios 在这里不起作用。

如何迁移此代码以在 Nuxt3 中使用 fetch 方法。

这就是我在 nuxt2 中所拥有的

<script>
import axios from "axios";
export default {
  data() {
    return {
      allDestinations: [],
      allSubDestinations: [],
      allTours: [],
      form: "",
    };
  },

  async asyncData({ route }) {
    let { data: countrydata } = await axios.get(
      `${process.env.backendapi}/dests/getcountry/${route.query.countryid}`
    );

    let { data: allDest } = await axios.get(
      `${process.env.backendapi}/dests/getmaindests?limit=5000`
    );

    let { data: allSubDest } = await axios.get(
      `${process.env.backendapi}/dests/getsubdests?limit=5000`
    );

    let { data: alltours } = await axios.get(
      `${process.env.backendapi}/tours/gettours?limit=10000`
    );

    return {
      form: countrydata,
      allDestinations: allDest.results,
      allSubDestinations: allSubDest.results,
      allTours: alltours.results,
    };
  },
};
</script>

【问题讨论】:

    标签: vue.js axios nuxt.js nuxtjs3


    【解决方案1】:

    Nuxt3 中的等价物如下。

    .env

    NUXT_PUBLIC_TEST_URL="https://jsonplaceholder.typicode.com"
    

    nuxt.config.ts

    import { defineNuxtConfig } from 'nuxt'
    
    export default defineNuxtConfig({
      runtimeConfig: {
        public: {
          testUrl: '', // fallback empty string, must be present tho
        },
      },
    })
    

    在任何页面中都有这个

    <template>
      <section>
        <div>{{ todo.title }}</div>
        <div>{{ user.email }}</div>
        <div>{{ photos }}</div>
      </section>
    </template>
    
    <script setup>
    const { testUrl } = useRuntimeConfig()
    const route = useRoute() // let's suppose that `countryid` equals 1
    
    const { data: todo } = await useFetch(`${testUrl}/todos/1`)
    const { data: user } = await useFetch(`${testUrl}/users/${route.query.countryid}`)
    const { data: photos } = await useFetch(`${testUrl}/photos/`)
    </script>
    

    关于数据获取的更多细节可以在这里找到:https://v3.nuxtjs.org/guide/features/data-fetching

    但总的来说,useFetch 正在阻止并按照您的预期行事。

    如果你不能使用script setup,你需要这样写:https://v3.nuxtjs.org/guide/features/data-fetching#using-async-setup

    这是有关环境变量的文档:https://v3.nuxtjs.org/guide/features/runtime-config#environment-variables

    【讨论】:

    • 感谢 Kissu 的解释,我已经浏览了文档,现在我明白了。
    猜你喜欢
    • 2022-07-29
    • 1970-01-01
    • 2023-02-04
    • 2022-11-10
    • 2022-11-24
    • 2022-08-09
    • 2021-12-15
    • 2022-12-30
    • 2021-05-30
    相关资源
    最近更新 更多