【问题标题】:How to initialize data with computed value inside asyncData?如何使用 asyncData 中的计算值初始化数据?
【发布时间】:2021-09-14 00:06:02
【问题描述】:

我正在使用 nuxt 构建一个 Web 应用程序。

这里是简化的代码:

pages/index.vue

data() {
 return {
  item: {name:'', department: '', testField: '',},
 }
}
async asyncData() {
  const result = call some API

  const dataToInitialize = {
   name: result.username,
   department: result.department,
   testField: //want to assign computed value
  }
  return {item: dataToInitialize}
}

在 asyncData 中,我调用 API 并将值分配给 dataToInitializedataToInitializetestField 字段,我想根据usernamedepartment 分配一些计算值。 (例如,“a”如果名称以“a”开头,部门为“管理”..等实际场景中的逻辑更复杂)

我曾尝试使用 computed 属性,但我意识到 asyncData 无法访问计算。

有谁知道如何解决这个问题? 任何帮助将不胜感激!

=======

不确定这是否正确,但我通过在 created 中设置 'testfield' 解决了这个问题。

created() {
    this.item.testField = this.someMethod(this.item);
},

【问题讨论】:

  • created 应该在asyncData 之后调用,它是否按预期工作?
  • 它按预期工作。我首先使用 asyncData 初始化数据,然后覆盖内部创建的 testField 字段,以便正确显示数据。我会尝试你建议的方法。(使用 fetch)@kissu

标签: vue.js nuxt.js


【解决方案1】:

我发现解构 fetch({}) 会导致在 fetch 范围内访问 this 时出现问题 ->

async fetch({ store, $anyOtherGlobalVar }){ 
store.dispatch... 
// destructuring approach changes the scope of the function and `this` does not have access to data, computed and e.t.c
}

如果您想访问this 范围,例如this.data,请避免解构并通过this. 访问所有内容

async fetch() {
 this.$store...
 this.data...
}

【讨论】:

    【解决方案2】:

    查看Nuxt lifecyle,您可以看到asyncData 在您的页面上挂载Vue 实例之前就被调用了。
    同时,fetch() 钩子在之后被调用。这是非阻塞的,但在很多方面更灵活。

    使用fetch() 的替代方法如下所示

    <script>
    export default {
      data() {
        return {
          staticVariable: 'google',
        }
      },
      async fetch() {
        await this.$axios(this.computedVariable)
      },
      computed: {
        computedVariable() {
          return `www.${this.staticVariable}.com`
        },
      },
    }
    </script>
    

    另一种选择是使用 URL 查询字符串或参数,这要归功于 Vue-router 并使用它们来构建您的 API 调用(在 asyncData 挂钩中)。
    以下是如何实现此目的的示例:https://stackoverflow.com/a/68112290/8816585


    评论问题后编辑
    您确实可以在 fetch() 挂钩中完全使用 computed。这是一个关于如何实现此目标的示例

    <script>
    export default {
      data() {
        return {
          test: 'test',
        }
      },
      async fetch() {
        const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${this.nice}`)
        console.log(await response.json())
      },
      computed: {
        nice() {
          return this.test + 'wow!'
        },
      },
    }
    </script>
    

    【讨论】:

    • 我尝试按照您的建议使用 fetch(),我可以看到我可以在 fetch 中使用计算值。一个问题。在 fetch 中,我用this.item=dataToInitialize 替换了这一行return {item: dataToInitialize},但应该显示在页面上的this.item 是空白的。我使用组件并将this.item 作为道具传递给这个子组件。那是因为子组件是在 fetch 完成之前创建和挂载的吗?
    • 我已经编辑了我的答案,即使我不确定你是否确实想要。此外,这个链接可能会有所帮助,看看整个事情是如何安装的:stackoverflow.com/a/44319825/8816585 这是 Nuxt 的生命周期:nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle@amu03
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多