javascript - Vue生命周期和firebase:为什么我会得到“TypeError:无法读取null的属性'url'”?
问题描述
我正在努力解决一个问题。我在我的模板中得到了这个图像元素,如下所示:
<img :src="photo.url" :id="photo.filename" :alt="photo.title" v-if="photo.url" />
这是我的data()
功能:
data() {
return {
photo: null,
// set variable during component creation to use when mounting
anno: {}
}
我有一个方法可以像这样抓取 img 元素的数据:
async mounted() {
// get photo properties
await this.getPhotoDoc()
// initialize Annotorious and assign to 'anno' variable for use throughtout component
this.anno = await new Annotorious({ image: this.photo.filename })
这是我的照片文档方法:
async getPhotoDoc() {
try {
const docRef = await photosCollection
.doc(this.$route.params.id) // to be dynamic
.get()
if (docRef.exists) {
// data() returns all data about the doc
let photo = await docRef.data()
this.photo = photo
} else {
console.log('no docs exist for this photo')
}
} catch (error) {
console.log('Error getting document:', error)
}
}
我似乎无法摆脱控制台中的这个错误:
[Vue warn]: Error in render: "TypeError: Cannot read property 'url' of null"
found in
---> <PhotoDetail>
<App> at src/App.vue
<Root>
有人发现我可以调整的任何东西吗?
解决方案
由于 photo 是异步初始化的,生命周期中有一个点 whenphoto
是未定义的。OP 中的 v-if 不足以检查这种情况。将其更改为...
v-if="photo && photo.url"
推荐阅读
- react-native - 在 RN 中使用多个视图时的边距
- math - 三次贝塞尔路径——在拉直弧长的同时保持弧长
- jenkins - 为什么 Jenkins 因错误而失败:退出 9009
- android - 如何调试 D8 错误,例如“类型 X 被引用为 Y 的接口”?
- javascript - 如何限制从 Mongoose 数组填充返回的项目?
- google-apis-explorer - Google Knowledge Graph API 响应中缺少返回信息
- wordpress - 更改主域后无法访问 Wordpress Multisite 中的站点
- android - 为什么 appium v1.12.1 在我执行测试脚本时会出现此错误?安卓版本:6.0
- arguments - 此函数的参数过多
- c# - 为什么 EF 代码不选择单列?