vue-resource
- vue-resource vue.js的一个插件
- 作用:
- 就是发送网络请求 和jQuery相比 功能更加纯粹(只做一件事)
- 发送请求
- 是通过向vue的实例化对象里面添加$http属性 调用get方法 可以发送get请求 post请求 还可以请求跨域资源
- 为什么不推荐使用vue-resource库?
- 1.vue-resource 不需要与vue深度结合 可以使用第三方库
- 2.第三方库或持续迭代更新 功能更全面
- 3.vue团队结合前面两点 觉得没必要花精力去维护vue-resource
- 4.尤雨汐推荐使用axios
html:
<div id="app">
{{weatherList}}
<input type="button" value="点我发请求" @click="search">
</div>
js:
<script src="vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
<script>
const app =new Vue({
el : "#app",
data : {
weatherList : []
},
methods : {
search(){
this.$http.get('http://wthrcdn.etouch.cn/weather_mini?city=武汉').then(res => {
this.weatherList = res.body.data.forecast;
console.log(this.weatherList);
},err => {
console.log(err);
})
}
}
})
</script>
axios
- Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
- 案例
// 为给定 city 的 http://wthrcdn.etouch.cn/weather_min创建请求
axios.get("http://wthrcdn.etouch.cn/weather_mini?city=武汉").then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
// 上面的请求也可以这样做
axios.get("http://wthrcdn.etouch.cn/weather_mini", {
params: {
city : 武汉
}
}).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})