如何将Firestore返回的Promise直接解析为Vue的reactive()代理对象
问题原因
你当前的写法是直接将FireStore返回的Promise实例传给了reactive(),而reactive本身不会自动等待Promise状态变更、绑定其resolve返回的结果,因此你打印拿到的始终是Promise对象本身,并非你需要的业务数组数据。
正确实现方案(不使用forEach、Vuex)
核心逻辑是先初始化空的响应式数组,等FireStore查询Promise resolve之后,直接将map()处理好的结果赋值给响应式数组即可:
import { reactive } from 'vue' import { db } from '你的firebase配置文件路径' // TS场景建议提前定义类型规范,可根据业务扩展字段 interface Client { id: string name: string } setup(){ // 1. 初始化空的响应式数组 const clients = reactive<Client[]>([]) // 2. 执行FireStore查询,拿到结果后更新响应式数组 db .collection('users') .orderBy('name', 'asc') .get() .then(snapshot => { // 全程用map处理原始数据,不需要借助forEach const clientList = snapshot.docs.map(doc => ({ id: doc.id, name: doc.data().name as string })) // 直接将map处理后的结果塞入响应式数组即可触发响应式更新 clients.push(...clientList) }) .catch(err => console.error('用户列表查询失败:', err)) return { clients } }
如果使用<script setup>语法,也可以用async/await写得更简洁:
<script setup lang="ts"> import { reactive } from 'vue' import { db } from '你的firebase配置文件路径' interface Client { id: string name: string } const clients = reactive<Client[]>([]) const getClientList = async () => { const snapshot = await db.collection('users').orderBy('name', 'asc').get() const clientList = snapshot.docs.map(doc => ({ id: doc.id, name: doc.data().name as string })) clients.push(...clientList) } // 执行查询 getClientList() </script>
内容的提问来源于stack exchange,提问作者Ryan Prentiss
相关产品推荐
相关产品推荐

