【问题标题】:Nuxtjs data() variable cannot changeNuxtjs data() 变量不能改变
【发布时间】:2020-11-07 00:28:22
【问题描述】:

我有一个简单的 nuxt/vue 应用程序。它使用 API 来调用过滤器和数据,但 fetch 挂钩不会更改变量。这是我的代码:

data() {
    return {
      filters: {},
      fulldata: [],
      filterName: '',
    }
  },

  async fetch({app}) {
    app.$axios.$get('/api/oklevelek').then(data => {
      this.fulldata = data
      this.filters = data.possibleFilters
      console.log(this.fulldata) //data shows
    })
    console.log('adatok')
    console.log(this.fulldata) //undefined
  },

  fetchOnServer: true,
  methods: {
    test() { //test method for data
      console.log('test')
      console.log(this.fulldata) //undefined
    },
  },

感谢您的宝贵时间并感谢您的帮助!

【问题讨论】:

标签: vue.js nuxt.js


【解决方案1】:

您需要等待 fetch 调用的响应。目前,您正在尝试在调用 api 之后,在数据有机会返回之前立即 console.log this.fulldata

async fetch({app}) {
  app.$axios.$get('/api/oklevelek').then(data => {
    this.fulldata = data
    this.filters = data.possibleFilters
    console.log(this.fulldata) //data shows
  })
  console.log('adatok')
  // this runs immediately after the api call
  console.log(this.fulldata) //undefined
}

这应该会有所帮助:

async fetch({app}) {
  // add await here
  let { data } = await app.$axios.$get('/api/oklevelek')
  // now this code waits for the api call to finish
  this.fulldata = data
  this.filters = data.possibleFilters
  console.log(this.fulldata)
  console.log('adatok')
  console.log(this.fulldata)
}

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 2021-12-04
    • 2022-08-15
    • 2020-11-30
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多