简体   繁体   中英

Why axios request not working inside vuejs (nuxt.js) methods

I have installed axios inside my nuxt.js application. Here my configuration file code:

File: nuxt.config.js

modules: [
  '@nuxtjs/vuetify',
  '@nuxtjs/axios',
],

axios: {
  // proxyHeaders: false
}

Here my example working code:

export default {
  data() {
    return {
      ip: ''
    }
  },
  async asyncData({ $axios }) {
    const ip = await $axios.$get('http://icanhazip.com')
    return { ip }
  }
}

And here my not working code:

export default {
  data() {
    return {
      ip: ''
    }
  },
  methods: {
    async asyncData() {
      const ip = await this.$axios.$get('http://icanhazip.com')
      this.ip = ip
    }
  } 
}

Why inside methods axios request not working?

You cannot call asyncData in you methods object. asyncData is for pre rendering only.

Rename your function to something else and it should be fine:

export default {
  data() {
    return {
      ip: ''
    }
  },
  methods: {
    async getData() {
      const ip = await this.$axios.$get('http://icanhazip.com')
      this.ip = ip
    }
  } 
}

Also when you are using asyncData as in your top example, you should not initialise "ip" in your data function. What is returned from asyncData is merged into data anyway.

AsyncData method will be called everytime before loading the page also note that asyncdata is only available in page component in nuxt. You don't have access to the component instance through this inside asyncData because it is called before initiating the component. You can use the returned data from asyncData data in your template without initialising in your data.

Nuxt asyncData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM