使用Nuxt+Firestore时数据无法在vuetify v-text-field内显示
问题原因
- Vuetify 的
v-text-field组件的输入值完全由v-model绑定的变量控制,写在组件标签中间的内容不会渲染到输入框内 - 你从 Firestore 拿到的数据只存入了
Test数组,没有赋值给和输入框绑定的editedItem.name,所以数据只会显示在外部的<p>标签里,不会出现在输入框中
修改方案
你是读取当前登录用户的单条文档,不需要用数组存储也不需要v-for遍历,直接把拿到的数据赋值给editedItem即可,修改后的代码如下:
模板部分
<template> <div> <v-container> <v-layout> <v-flex> <v-card> <v-card-text> <v-form> <v-layout> <v-row> <v-col cols="12" sm="6" md="6"> <v-text-field v-model="editedItem.name" label="姓名"></v-text-field> </v-col> <v-col cols="12" sm="6" md="6"> <v-btn @click="test">提交</v-btn> </v-col> </v-row> </v-layout> </v-form> </v-card-text> </v-card> </v-flex> </v-layout> </v-container> </div> </template>
脚本部分
<script> import firebase from "firebase/app"; import firestore from "@/plugins/firebasetest"; export default { middleware: "authentication", layout: 'dashboard', data: () => ({ editedItem: { name: '', } }), created() { this.readTest(); }, methods: { readTest() { firestore .collection('test') .doc(firebase.auth().currentUser.uid) .get() .then((doc) => { if (doc.exists) { // 直接把拿到的数据赋值给绑定输入框的变量 this.editedItem.name = doc.data().name || '' } }) }, test() { var data = { name: this.editedItem.name, } firestore .collection('test') .doc(firebase.auth().currentUser.uid) .set(data) .then(() => { // 不需要刷新页面,重新拉取数据即可 this.readTest() }) }, }, } </script>
如果需要保留原有的Test数组逻辑,只需要在readTest的回调里加一行this.editedItem.name = doc.data().name即可,不需要改动其他原有代码。
内容的提问来源于stack exchange,提问作者user16136444
相关产品推荐
相关产品推荐

