我试图迭代在created()期间获取的数据库对象,我在console.log中获取值,但v-for模板部分仍然为空。我的子问题是:这是好的做法吗?我对 Vue 还很陌生,我对这个问题的搜索让我认为这是一个生命周期问题。
感谢您的帮助。
模板部分:
.content(v-for="(content, key, index) in contents")
h3 {{key}}
.line
| {{getValue(content)}} // this is blank
方法部分:
getValue(value) {
PagesService.fetchDataWrap({
id: value
}).then((response) => {
const test = response.data.values[0].value
console.log(test) //this is working and gives the right value
return test
})
},
getPage() {
PagesService.fetchPage({
id: this.$route.params.page
}).then((response) => {
this.name = response.data.result.name
this.langs = response.data.result.langs
this.project = response.data.result.parent
this.contents = response.data.result.values
})
this.getProject()
}
console.log(this.contents) 结果:
{__ob__: Observer}
footer: "5a29943b719236225dce6191"
header: "5a29a9f080568b2484b31ee1"
这是当 v-for 迭代内容时我想要发送的值,以便 getValue 可以处理它以获取相应的值
最佳答案
我不建议尝试输出异步方法的值。它不太可能正常工作。
相反,在created
Hook 期间完全填充您的contents
数组/对象。例如,这可以将 contents
哈希值替换为 fetchDataWrap
...
getPage () {
PagesService.fetchPage({
id: this.$route.params.page
}).then(response => {
this.name = response.data.result.name
this.langs = response.data.result.langs
this.project = response.data.result.parent
let contents = response.data.result.values
Promise.all(Object.keys(contents).map(key => {
// map each key to a "fetchDataWrap" promise
return PageService.fetchDataWrap({
id: contents[key]
}).then(res => {
// replace the hash with the resolved value
contents[key] = res.data.values[0].value
})
}).then(() => {
// all done, assign the data property
this.contents = contents
})
})
}
然后您可以相信内容已加载用于渲染
.content(v-for="(content, key, index) in contents")
h3 {{key}}
.line
| {{content}}
关于vue.js - 使用 v-for 对动态项进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47704967/