【发布时间】:2021-07-29 21:20:45
【问题描述】:
我在处理 vue3 refs 时遇到问题。
我从 Firestore 获取数据。
我记录了[文档],它工作正常。
但是当我从文档的第一个数组中获取值时
例如,
我想要的值:abc1 (first array's displayName)
所以我尝试了
console log
0. documents (works, results below)
1. documents.value.displayName (error)
2. documents.value[0].displayName (error)
Uncaught (in promise) TypeError: Cannot read property '0' of null
at setup (Write.vue?125b:56)
但失败了。
如何从 refs 数组中获取值?
Log document
RefImpl {_shallow: false, __v_isRef: true, _rawValue: null, _value: null}
__v_isRef: true
_rawValue: Array(2)
0: {displayName: "abc1", orgName: "amazon", email: "aaa@aaa.com", regDate2: "2021-7-27", …}
1: {displayName: "abc2", email: "aaa@aaa.com", orgName: "google", …}
设置功能
setup() {
const title = ref('')
const contents = ref('')
const { user } = getUser()
const userUid = user.value.uid
const { documents } = getCollection('user')
console.log(documents, 'documents log')
console.log(documents.value[0].displayName, 'documents value log')
return {title, contents, user, documents }
}
getCollection.js
const getCollection = (collection, query) => {
const documents = ref(null)
const error = ref(null)
// register the firestore collection reference
let collectionRef = projectFirestore.collection(collection)
if (query) {
collectionRef = collectionRef.where(...query)
}
const unsub = collectionRef.onSnapshot(snap => {
let results = []
snap.docs.forEach(doc => {
results.push({...doc.data()})
});
// update values
documents.value = results
error.value = null
}, err => {
console.log(err.message)
documents.value = null
error.value = 'could not fetch the data'
})
watchEffect((onInvalidate) => {
onInvalidate(() => unsub());
});
return { error, documents }
}
export default getCollection
【问题讨论】:
标签: javascript vue.js vuejs3 vue-composition-api