从Firestore异步取数后Vue页面数组显示为空问题求助
问题:Vue页面中Firestore获取的数组显示为空,但展开后有内容?
我尝试编写一个类方法从Google Firestore中获取员工信息,该类会在其他页面中使用:
- 使用
getDocs()获取集合的DocumentSnapshot后,将所有文档数据推入一个数组 - 在Vue页面中调用该数组
- 数组显示为空,但展开后内部存在对象
CustomFunction.ts
class Employee { private UserCollection = collection(db, "User") array: object[] = [] public async getEmployees() { try { const UserDocuments = await getDocs(this.UserCollection) UserDocuments.forEach((docs) => { this.array.push(docs.data()) }) } catch (error) { console.log(`Error message: ${error}`) } console.log(this.array) } } export const EmployeeList = Employee
EmployeeList.vue
const Employees = new EmployeeList() let FetchUser = async () => { await Employees.getEmployees() } FetchUser() console.log(Employees.array)
日志显示:EmployeeList.vue中的数组为空;CustomFunction.ts中的数组有内容。尝试索引数组时,Vue页面中的数组返回undefined,而CustomFunction.ts中的数组能返回目标对象。
原因分析
核心问题是异步代码的执行顺序:
FetchUser()是异步函数,调用后会立刻返回Promise,不会阻塞后续代码执行- 你在调用
FetchUser()后直接执行console.log(Employees.array),此时getEmployees()里的Firestore网络请求还未完成,数组自然是空的 - 浏览器控制台展开数组能看到内容,是因为控制台会动态更新引用对象的实时状态——当后续异步请求完成、数组被填充后,控制台展开时会显示最新数据,但打印的瞬间数组确实是空的
解决方案
方式一:等待异步函数完成后再访问数组
修改Vue页面代码,确保在getEmployees()执行完成后再操作数组:
const Employees = new EmployeeList() async function FetchUser() { await Employees.getEmployees() console.log(Employees.array) // 此时数组已填充完成 } FetchUser()
方式二:让类方法直接返回数组
调整Employee类的逻辑,避免依赖实例的array属性,直接返回处理后的结果:
class Employee { private UserCollection = collection(db, "User") public async getEmployees() { try { const UserDocuments = await getDocs(this.UserCollection) return UserDocuments.map(doc => doc.data()) // 直接返回处理后的数组 } catch (error) { console.log(`Error message: ${error}`) return [] // 出错时返回空数组避免后续异常 } } } export const EmployeeList = Employee
Vue页面调用:
const Employees = new EmployeeList() async function FetchUser() { const userArray = await Employees.getEmployees() console.log(userArray) // 直接拿到填充好的数组 } FetchUser()
额外Vue响应式优化
如果需要在Vue模板中使用该数组,要确保变量是响应式的:
import { ref } from 'vue' const Employees = new EmployeeList() const userArray = ref([]) async function FetchUser() { userArray.value = await Employees.getEmployees() } FetchUser()
这样模板中使用userArray时,数据更新会自动触发视图渲染。
内容的提问来源于stack exchange,提问作者Dante How
相关产品推荐
相关产品推荐

