首页 > 解决方案 > Axios GET 不包括 Nuxt 模板中的参数

问题描述

我想将一个 id 传递给 axios,以便我可以动态切换 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

这里发生了什么?

标签: apiaxiosnuxt.js

解决方案


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

要使用新的 api 调用刷新页面数据,您需要从导出的方法部分中返回 axios 承诺。下面的代码先做 axios get 请求,然后用 plus 和 minus 函数对 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>

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


推荐阅读