javascript - 使用基于路由器参数的 Vue http 获取数据
问题描述
我已经四处寻找答案,并按照vue 路由器文档中的示例进行操作,但仍然遇到问题。我正在尝试对组件的初始加载进行 http 调用,然后还观察路由器参数并更新来自 vue-resource 的“get”调用。
我的vue组件js长这样...
export default {
name: 'city',
components: {
Entry
},
data () {
return {
city: null
}
},
mounted() {
this.fetchData();
},
watch: {
'$route': 'fetchData'
},
methods: {
fetchData() {
const cityName = this.$route.params.name;
this.$http.get('http://localhost:3000/cities?short=' + cityName).then(function(response){
this.city = response.data;
}, function(error){
alert(error.statusText);
});
console.log(cityName)
}
}
}
我已经在我的 fetchData 方法中注销了“cityName”,它总是返回正确的名称,但是当我将该“cityName”附加到 http get 调用时,它没有返回正确的数据。在初始加载时,this.city 保持为空,然后每次我更新路线时,数据都会返回选择的前一个城市,而不是路线中新的更新城市。我已经尝试使用 Vue 的created
属性来代替,mounted
并且发生了同样的事情。有任何想法吗?
解决方案
尝试将您的fetchData
方法更改为以下内容:
fetchData() {
const cityName = this.$route.params.name;
this.$http.get('http://localhost:3000/cities?short=' + cityName).then((response) => {
this.city = response.data;
}, (error) => {
alert(error.statusText);
});
console.log(cityName)
}
=>
函数符号保留this
在组件的上下文中。
推荐阅读
- google-chrome - chrome 更新到版本 81.0.4044..111 后无法播放远程视频流
- mongodb - 适合上传 PDF 的云以及 react native 和 mern stack
- python - 从 scipy 子模块导入的正确方法
- asp.net-core - ASP.NET Core 2.2 POST 操作参数为空
- visual-studio - 自定义 Visual Studio 离线安装
- c# - JObject 会导致高使用环境中的内存泄漏吗?
- python-3.x - 如何使用输出绘制频率图?
- angular - 使用 http 调用解析可观察的属性
- web-scraping - 如果 class 或 id 不存在,如何在 beautifulsoup 中找到 div
- swift - CoreBluetooth peripheralManager 广告在后台停止