根据Nuxt 3动态组件中的路由参数进行API调用

问题描述 投票:0回答:3

我正在尝试创建一个简单的 Nuxt 3 应用程序以用于学习目的,该应用程序在加载页面时使用“动态路由”从 API 加载数据。我想要弄清楚的是如何将路由 id 参数与组合 API 一起使用来调用外部 API 并使数据在组件中可用。

这是我的基本文件夹结构:

/pages \ index.vue /currency \ [id].vue

index.vue:

<template> <main> <h1>Index Page</h1> <table border="1 px solid"> <thead> <tr> <th>Name</th> <th>Symbol</th> <th>Price</th> <th>Details</th> </tr> <tr v-for="currency in data.data" :key="data.id"> <td>{{ currency.name }}</td> <td>{{ currency.symbol }}</td> <td>{{ currency.price_usd }}</td> <td> <NuxtLink :to="'/currency/' + currency.id">{{ currency.id }}</NuxtLink> </td> </tr> </thead> </table> </main> </template> <script> export default { async setup() { const {data} = await useFetch('/api/coinlore/tickers'); return { data }; } } </script>

这就是我的
[id].vue

<template>
  <main>
    <h1>{{ data.data.name }} Detail page</h1>
    {{ $route.params.id }}
  </main>
</template>

<script>
export default {
  async setup() {
    const {data} = await useFetch('/api/coinlore/ticker?id=90');

    console.log(data);

    return {
      data
    };
  }
}
</script>

从这篇
博客文章

我尝试了这个 <template> <main> <h1>{{ data.name }} Detail page</h1> {{ $route.params.id }} </main> </template> <script> export default { async setup() { const coin = reactive({}); function fetchCoin(id) { const {data} = await useFetch('/api/coinlore/ticker?id=' + $route.params.id); coin = data; } watch('$route.params.id', fetchCoin) return { coin }; } } </script>

但那里也没有骰子。

如何简单地 1) 进行 API 调用并 2) 使用

id

组件中的

[id].vue
参数填充数据?
    

vue.js nuxt.js watch nuxtjs3
3个回答
3
投票

useRoute()挂钩

import { useRoute } from 'vue-router'; export default { setup() { 👇 const route = useRoute(); const { data: coin } = await useFetch('/api/coinlore/ticker?id=' + route.params.id); return { coin } } }

演示


0
投票

在index.vue中最好使用编程路由:

<NuxtLink :to="{path: '/currency', params : {id: currency.id} }">{{ currency.id }}</NuxtLink> // it will build link: `/currency/[id]`

正如 Tony19 所发布的,需要在组件中定义 
route

(useRoute hook): // import in script import { useRoute } from 'vue-router'; // define route from 'vue' const route = useRoute() // read ID from route params const currencyId = route.params.id // actually it's better use literal string for using dynamic data => better reading const { data: coin } = await useFetch(`/api/coinlore/ticker?id=${currencyId}`);



0
投票

<NuxtLink :to="{path: '/currency', params : {id: currency.id} }">{{ currency.id }}</NuxtLink>

这段代码将重定向到/currency/id

文件夹结构也应该是这样的,pages=>currency[id].vue

© www.soinside.com 2019 - 2024. All rights reserved.