我嘗試使用來自 v-for 中的引數的引數從 api 獲取資料。在findUser方法上,我可以console.log找到我正在尋找的資料。但是最后我不能得到它findUser,為什么?
我知道有一種async方法可以得到它,但我不明白如何管理它以使其與我想做的事情一起作業;我也想過同時呼叫這兩個API,結果是一樣的,不知道怎么管理。
<template>
<div>
<h4>Listes Re?ues</h4>
<p v-for="element in results" id="flex-list" :key="element.list_id">
{{ element.list_name }} de {{ findUser(element.user_id) }}
</p>
</div>
</template>
<script>
export default {
data() {
return {
results: '',
nickname: '',
}
},
created() {
this.$axios
.get(`/api/listReceived/${this.$auth.user[0].user_id}`)
.then((res) => {
this.results = res.data
console.log(JSON.stringify(this.results))
})
.catch((err) => {
console.error(err)
})
},
methods: {
findUser(id) {
console.log(id)
let data = ''
this.$axios
.get(`http://localhost:3000/api/userdata/${id}`)
.then((res) => {
data = res.data[0].nickname
console.log(data)
})
.catch((err) => {
console.error(err)
})
return data
},
},
}
</script>
uj5u.com熱心網友回復:
在我的最佳答案之上,這對于這個問題并不重要,但仍然相關,這里有一個關于如何正確處理交叉路口的例子。
我沒有使用端點,而是在本地模擬資料,data()因此我將我的帖子保留在上面。
<template>
<div class="flex flex-col items-center">
<h1 class="p-4 bg-green-700 rounded-md">
List of users ordered by their according message
</h1>
<!-- <pre>{{ messages }}</pre> -->
<section>
<div v-for="user in groupedMessages" :key="user.id" class="mt-4">
<p>
User: <b>{{ user.name }}</b>
</p>
<aside>
Messages:
<span v-if="!user.messages.length">No messages actually</span>
</aside>
<p v-for="message in user.messages" :key="message.id">
<span class="italic">- {{ message.text }}</span>
</p>
</div>
</section>
</div>
</template>
<script>
// ES version of lodash, lighter overall
import { cloneDeep } from 'lodash-es'
export default {
name: 'Index',
data() {
return {
messages: [
{
id: 1,
text: 'Hello world',
userId: 1,
},
{
id: 2,
text: 'Nice cool message',
userId: 1,
},
{
id: 3,
text: 'Still for the first user?',
userId: 1,
},
{
id: 4,
text: 'Yep, apparently...',
userId: 1,
},
{
id: 5,
text: "Eh, surprise, I'm a sneaky one...",
userId: 3,
},
{
id: 6,
text: 'Oh, a second one.',
userId: 2,
},
{
id: 7,
text: "You're damn right!!",
userId: 2,
},
],
users: [
{
name: 'Patrick',
id: 1,
messages: [],
},
{
name: 'Pablo',
id: 2,
messages: [],
},
{
name: 'Unkown author',
id: 5,
messages: [],
},
{
name: 'Escobar',
id: 3,
messages: [],
},
],
}
},
computed: {
groupedMessages() {
// we use that to avoid any kind of further mutation to the initial `users` array
const clonedUsers = cloneDeep(this.users)
// we do loop on each message and find a corresponding user for it
this.messages.forEach((message) =>
clonedUsers.forEach((user) => {
if (user.id === message.userId) {
user.messages.push(message)
}
})
)
return clonedUsers
},
},
}
</script>

uj5u.com熱心網友回復:
created()Vue 完全沒問題,但通常你會在 Nuxt 中使用fetch()和鉤子。這是使用JSONplaceholder 的 API
的基本思想。asyncData()
這是一個可能的/pages/index.vue
<template>
<div class="flex flex-col items-center">
<h1 class="p-4 bg-green-700 rounded-md">
List of users from JSONplaceholder
</h1>
<section class="mt-4">
<p v-for="user in users" :key="user.id">
{{ user.name }} ?? {{ user.email }} ~
<nuxt-link
:to="{ name: 'users-id', params: { id: user.id } }"
class="border-b-4 border-green-500"
>
Check details
</nuxt-link>
</p>
</section>
</div>
</template>
<script>
export default {
name: 'Index',
data() {
return {
users: [],
}
},
async fetch() {
this.users = await this.$axios.$get('/users')
},
}
</script>
<style>
* {
@apply bg-gray-800 text-gray-100;
}
</style>
/pages/users/_id.vue以及使用fetch()鉤子的詳細頁面。
<template>
<div class="flex flex-col items-center">
<nuxt-link class="p-4 bg-purple-700 rounded-md" :to="{ name: 'index' }">
Go back
</nuxt-link>
<h2>User details ID: # {{ $route.params.id }}</h2>
<p v-if="$fetchState.pending">Loading user's info...</p>
<p v-else-if="$fetchState.error">Error while fetching user</p>
<div v-else>
<p>{{ user.name }}</p>
<p>{{ user.phone }}</p>
<p>{{ user.website }}</p>
<p>{{ user.company.name }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'UserId',
data() {
return {
user: {},
}
},
async fetch() {
this.user = await this.$axios.$get(`/users/${this.$route.params.id}`)
},
}
</script>
我確實更喜歡這種方法,因為它不會阻塞渲染,您可以添加一些平滑的骨架來讓用戶知道正在發生某些事情。最重要的是,fetch()在組件和頁面上都可用,而asyncData()僅適用于頁面。
它還提供了非常方便的好$fetchState幫手!
這是/pages/users/_id.vue使用asyncData() hook.
<template>
<div class="flex flex-col items-center">
<nuxt-link class="p-4 bg-purple-700 rounded-md" :to="{ name: 'index' }">
Go back
</nuxt-link>
<p>{{ user.name }}</p>
<p>{{ user.phone }}</p>
<p>{{ user.website }}</p>
<p>{{ user.company.name }}</p>
</div>
</template>
<script>
export default {
name: 'UserId',
async asyncData({ route, $axios }) {
const user = await $axios.$get(`/users/${route.params.id}`)
return { user }
},
}
</script>
Main benefit of using asyncData is the fact that it's more safe and that it's blocking the render (can be either a pro or a con, more of a con for me personally).
Here are some other in-depth answers comparing fetch() vs asyncData().
Check out this handy blog article on the subject and also this dev.to clone example.
Finally, if you want to take the SSG path and optimize the whole thing with the least amount of API calls once on the client-side, you can also check my other answer.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448913.html
標籤:javascript Vue.js 异步 axios nuxt.js
