Vue3 Composition API结合Firestore文档字段双向绑定异步数据获取问题
解决方案
问题根因
getDocument返回的document是Vue响应式ref对象,初始值为null- Firestore的
onSnapshot回调是异步执行的,setup函数同步运行阶段无法拿到后端返回的文档数据,直接访问document.value.title自然返回undefined
方案1:使用watch监听文档更新(推荐入门使用)
监听document的变化,异步给title赋值即可,适配你现有的代码逻辑:
<script> import getDocument from 'getDocument' import { ref, watch } from 'vue' export default { props: ['id'], setup(props) { const { error, document } = getDocument('items', props.id) const title = ref('') // 监听document变化,数据返回后自动赋值 watch(document, (newDoc) => { if (newDoc) { title.value = newDoc.title } }, { immediate: true }) return { title } } } </script>
方案2:使用可写计算属性(适合需要同步更新到Firestore的场景)
如果你的双向绑定需要把用户修改的内容自动同步回Firestore,用可写计算属性会更简洁,不需要额外维护单独的title ref:
<script> import getDocument from 'getDocument' import { computed } from 'vue' import { projectFirestore } from '../firebase/config' export default { props: ['id'], setup(props) { const { error, document } = getDocument('items', props.id) const title = computed({ get() { // 可选链兜底,避免document为null时报错 return document.value?.title || '' }, set(newVal) { // 用户修改输入框内容时自动更新到Firestore,高频输入场景可自行加防抖逻辑 projectFirestore.collection('items').doc(props.id).update({ title: newVal }) } }) return { title, error, document } } } </script>
模板优化建议
可以增加加载、错误状态判断,优化用户体验:
<template> <!-- 文档加载完成后再显示表单 --> <div v-if="document"> <input type="text" name="title" placeholder="Title" v-model="title" class="form-xxx"> </div> <div v-else-if="error">{{ error }}</div> <div v-else>文档加载中...</div> </template>
内容的提问来源于stack exchange,提问作者Rasmus Justesen
相关产品推荐
相关产品推荐

