【问题标题】:change methods vuejs to nuxtjs将方法 vuejs 更改为 nuxtjs
【发布时间】:2021-07-12 22:43:10
【问题描述】:

我想改变这个方法。我有这个 vue.js 代码:

computed: {
  ...mapGetters('user/auth', ['Id']),
},
async mounted() {
  await this.doFetchCustomer(this.Id)
},

methods: {
  async doFetchCustomer(Id) {
    const app = { $axios: this.$axios }
    const datas = (await customerApi.getData(app, Id)) || []
    console.log(datas)
  },
},

我想将此代码转换为 nuxt asyncData 但我在下面尝试的方法不起作用。如何正确转换?

computed: {
  ...mapGetters('user/auth', ['Id'])
},
async asyncData({$axios}) {
  const datas = (await customerApi.getData($axios, this.Id )) || [];
  console.log(datas);
  return {datas}
}

【问题讨论】:

  • 到目前为止有什么问题?您不能在mounted()fetch() 挂钩中以相同的方式使用它吗?
  • 这个问题我想使用 asyncData 钩子来检索数据,而不需要通过挂载或方法来获取数据
  • 不,我的意思是:这里的错误在哪里?你那边出了什么问题?另外,您的mapGetters 正在使用Id,而您的getData 函数正在使用this.id?确定这不是问题吗?您在console.log 中看到datas 吗?
  • 对不起,我刚刚修复了 Id,当我使用 asyncdata 挂钩时,未调用函数,这是我的问题
  • 好的,如何跳转到相关页面?根本不叫?您能否通过编辑您的问题和触发导航的问题向我们展示具有asyncData 的组件。

标签: javascript vue.js nuxt.js


【解决方案1】:

asyncData 没有在您的组件中被调用这一事实表明该组件不是页面组件。

Nuxt docs 声明要求:

asyncData 钩子。这个钩子只能放在页面组件上。

您可以改用fetch hook,它适用于所有组件类型:

export default {
  data() {
    return {
      datas: null
    }
  },
  async fetch() {
    this.datas = (await customerApi.getData(this.$axios, this.Id)) || [];
  },
}

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多