vue.js - 使用 v-for 对动态项进行迭代

标签 vue.js

我试图迭代在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/

相关文章:

vue.js - 动态更改 vuetify v-chip 颜色

vue.js - 如何同时使用 Vue-Router 和 Gorilla Mux 路由器

laravel - 从 oauth 登录返回 JWT token 到 javascript SPA

javascript - 无法从 localStorage 初始化 Vuex 存储以用于 Nuxt 中的身份验证

vue.js - @nuxt/auth 我可以使用参数发送刷新 token 吗?

vue.js - Vuejs 在另一个组件中导入组件

javascript - 检查多个选项并在 vuex 中进行过滤

javascript - 如何在 v-time-picker 中禁用选择分钟?

javascript - 在Vue.js中的双大括号{{}}中渲染元素

javascript - Materialize css 触发器在 Vue js 中不起作用