简体   繁体   English

为什么axios请求在vue.js(nuxt.js)方法中不起作用

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

I have installed axios inside my nuxt.js application. 我已经在nuxt.js应用程序中安装了axios。 Here my configuration file code: 这是我的配置文件代码:

File: nuxt.config.js 文件: 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? 为什么axios请求的内部methods不起作用?

You cannot call asyncData in you methods object. 您不能在方法对象中调用asyncData。 asyncData is for pre rendering only. asyncData仅用于预渲染。

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. 同样,如上例所示,在使用asyncData时,请勿在数据函数中初始化“ ip”。 What is returned from asyncData is merged into data anyway. 无论如何,从asyncData返回的内容都会合并到数据中。

AsyncData method will be called everytime before loading the page also note that asyncdata is only available in page component in nuxt. 每次在加载页面之前都会调用AsyncData方法,另外请注意,asyncdata仅在nuxt的页面组件中可用。 You don't have access to the component instance through this inside asyncData because it is called before initiating the component. 您无法通过asyncData内部的实例访问组件实例,因为在启动组件之前会调用它。 You can use the returned data from asyncData data in your template without initialising in your data. 您可以使用模板中asyncData数据返回的数据,而无需初始化数据。

Nuxt asyncData Nuxt asyncData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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