Javascript 获取的存储属性返回未定义的计算页
因此,我有一个存储区,其中填充了post数据,然后显示在页面上,但由于某些原因,post变量没有定义。 下面是一些代码: 组件中的异步获取Javascript 获取的存储属性返回未定义的计算页,javascript,vue.js,nuxt.js,Javascript,Vue.js,Nuxt.js,因此,我有一个存储区,其中填充了post数据,然后显示在页面上,但由于某些原因,post变量没有定义。 下面是一些代码: 组件中的异步获取 async fetch({ store, route }) { db.collection("posts") .doc(route.params.id) .get() .then(doc => { if (doc.exists) { var x = doc.data()
async fetch({ store, route }) {
db.collection("posts")
.doc(route.params.id)
.get()
.then(doc => {
if (doc.exists) {
var x = doc.data()
x.docID = doc.id
store.commit("modules/posts/pushPost", x)
} else alert("No Post found")
})
},
组件中的计算属性
computed: {
post() {
var posts = this.$store.state.modules.posts.posts
return posts.find(x => x.docID === this.$route.params.id)
},
存储提交
pushPost(state, post) {
state.posts.push(post)
console.log(post)
console.log("pushed")
}
两个控制台都记录存储触发器并显示正确的值
但由于某些原因,我页面中的计算帖子未定义我找到了问题的根源
数据库调用获取数据之前的wait关键字丢失,这导致组件在实际填充存储之前准备得太快,这显然导致数据未定义 我会完全忘记
。然后在这种特殊情况下
回调。如果您像下面的示例中那样编写它,那么对于未定义的数据肯定不会有问题,而且它的代码更干净
async fetch({ store, route }){
const doc = await db.collection("posts").doc(route.params.id).get()
if(doc.exists) {
const x = doc.data()
x.docID = doc.id
store.commit("modules/posts/pushPost", x)
} else {
alert("No Post found")
}
}