【问题标题】:Axios GET not including params in Nuxt templateAxios GET 不包括 Nuxt 模板中的参数
【发布时间】:2019-04-09 16:55:24
【问题描述】:

我想给 axios 传递一个 id,这样我就可以动态切换 url。

我的模板中的axios请求如下:

async asyncData({ params }) {
    const { data } = await axios.get('http://localhost:8000/api/', {
      params: {
        id: 1
      }
    })
    return { data }
  }

传递给我的 api 的请求是:

GET /api/?id=1

但我需要

GET /api/1

这里发生了什么?

【问题讨论】:

    标签: api axios nuxt.js


    【解决方案1】:

    看起来 asyncData 函数在页面加载时被调用了一次。我仍然不知道为什么它不接受文档和众多教程中概述的参数,但它不会刷新页面,因为它再也不会被调用。

    要使用新的 api 调用刷新页面数据,您需要从导出的方法部分中返回 axios 承诺。下面的代码先做axios get请求,然后用加减函数对id加减1。

    <script>
    import axios from 'axios'
    
    export default {
      head() {
        return {
          title: 'Weather'
        }
      },
      data: function() {
        return { counter: 1 }
      },
      methods: {
        plus: function(counter, data, datalength) {
          this.counter += 1
          axios.get('http://localhost:8000/api/' + this.counter).then(res => {
            console.log(this.counter)
            console.log(res.data)
            return (this.data = res.data)
          })
        },
        minus: function(counter, data) {
          if (this.counter >= 2) {
            this.counter -= 1
            axios.get('http://localhost:8000/api/' + this.counter).then(res => {
              console.log(this.counter)
              console.log(res.data)
              return (this.data = res.data)
            })
          } else {
            this.counter = 1
          }
        }
      },
      async asyncData({ params, counter }) {
        let { data } = await axios.get('http://localhost:8000/api/1')
        return { data }
      }
    }
    </script>
    

    如果有人想详细说明或发布更好的解决方案,请继续 - 但我发布此内容是因为我搜索了很多教程,但在找到解释文档的方法之前没有任何效果,这肯定不适合初学者.

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      相关资源
      最近更新 更多