我正在尝试创建一个简单的 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
参数填充数据?在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}`);
<NuxtLink :to="{path: '/currency', params : {id: currency.id} }">{{ currency.id }}</NuxtLink>
这段代码将重定向到/currency/id
文件夹结构也应该是这样的,pages=>currency[id].vue