从方法返回的数据没有出现在prop中



我不能将数据从方法传递给prop。该方法从firestore中的集合中获取字段。

这里是父组件:

<template>
<post-card
v-for="post in posts"
:key="post.id"
:userId="post.userId"
:userName="userName(post.userId)"
/>
</template>

<script>
components: {
PostCard
}
methods: {
userName(id){
this.$fire.firestore.collection('users').doc(id).get().then(snapshot => {
console.log("id", snapshot.data())
return snapshot.data().name
})
}
}
</script>

这是明信片的部分:

<template>
{{userName}}
</template>
<script>
name: 'post-card'.
props: [
'userName',
'userId'
],
</script>

道具可以这样获取数据吗?工作后会有反应吗?

我没有访问您的特定Firestore数据和模拟它将是相当困难的,所以我使用JSONplaceholder为我的例子。

我将如何处理这种情况

index.vue

<template>
<div>
<post-card v-for="user in users" :key="user.id" :user="user" />
</div>
</template>
<script>
export default {
components: {
'post-card': () => import('~/components/PostCard.vue'),
},
data() {
return {
users: [],
}
},
async mounted() {
this.users = await this.$axios.$get(
'https://jsonplaceholder.typicode.com/users/'
)
},
// methods: {
//   async fetchUsername(id) {
//     const snapshot = await this.$fire.firestore
//       .collection('users')
//       .doc(id)
//       .get()
//     console.log('id', snapshot.data())
//     return snapshot.data().name
//   },
// },
}
</script>

PostCard.vue

<template>
<div>
<span>{{ user.name }}</span>
<pre>{{ details }}</pre>
<hr />
</div>
</template>
<script>
export default {
name: 'PostCard',
props: {
user: {
type: Object,
default: () => {},
},
},
data() {
return {
details: {},
}
},
async mounted() {
this.details = await this.$axios.$get(
`https://jsonplaceholder.typicode.com/users/${this.user.id}`
)
},
}
</script>

这里,我用的是this.$axios.$get,但它基本上是一个花哨的axios + .data组合,没有什么特别的。


我没有像你一样在父级使用:userName="userName(post.userId)",因为这本身是不可行的。在这种情况下,模板是同步的,这意味着在运行函数时不会获得post.userId,因为请求仍然处于挂起状态。同时,你的孩子需要这些信息来直接渲染他自己。

在Vue中,您通常在中执行这种逻辑。组件本身或在mounted钩子中与集合fetch配对。这主要是因为Vue子组件的安装方式不同,如下所示:https://stackoverflow.com/a/44319825/8816585

你也许可以使用这种挂载技巧,但我不建议这样做,因为它会很粗糙,总体上更困难,而且没有必要。

最新更新