api - 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
这里发生了什么?
解决方案
看起来 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>
如果有人想详细说明或发布更好的解决方案,请继续 - 但我发布此内容是因为我搜索了很多教程,但在找到解释文档的方法之前没有任何效果,这肯定不适合初学者。
推荐阅读
- json - 疯狂约会的杰克逊序列化错误
- direct2d - Direct2D:平滑的图像移动?
- angular - Ionic v4 嵌套选项卡
- java - 在保存到 mongoDB 数据库 java 独立应用程序之前回滚数据
- wpf - 如何折叠 WPF DocumentViewer 控件工具栏中的 CopyButton?
- angular - 如何在量角器中执行 Graphql 请求
- angular - rxjs switchMap 和嵌套的 observables
- python - Python 函数可以在 Flask 或 Django 中使用吗?
- css - Bootstrap 4 防止在水平滚动的溢出行上剪裁
- python - Python Socket.io 客户端停止并显示消息“收到类型 1 的意外数据包”