一、Vue中常用的ajax请求库
1、axios
2、vue-resource(使用方法与axios一样)
3、两者区别
axios:通用的ajax请求库,适用范围广,官方支持 vue-resource:vue插件库,vue1.0版本用,已经年久不维护
二、案例练习
需求:通过github搜索用户名,并渲染到页面
github查找用户名接口:https://api.github.com/search/users?q=xxx
1、下载axios
npm i axios
2、引入
import axios from "axios"
3、页面代码
① App组件
<template>
<div id="app">
<Search/>
<List/>
</div>
</template>
<script>
import Search from "./components/Search.vue";
import List from "./components/List.vue";
export default {
name: 'App',
components:{Search,List},
}
</script>
② Search组件
<template>
<div>
<section class="jumbotron">
<h3 class="jumbotron-heading">Search Github Users</h3>
<div>
<input type="text" placeholder="enter the name you search" v-model="keyword"/>
<button @click="getKeyword">Search</button>
</div>
</section>
</div>
</template>
<script>
import axios from "axios";
export default {
name:"Search",
data() {
return {
keyword:"",
}
},
methods:{
async getKeyword(){
this.$bus.$emit("sendMsg",{isFirst:false,isLoad:true,errMsg:'',list:[]});
this.list = await axios.get(`https://api.github.com/search/users?q=${this.keyword}`).then(
response=>{
return this.$bus.$emit("sendMsg",{isLoad:false,errMsg:'',list:response.data.items})
},
error=>{
this.$bus.$emit("sendMsg",{isFirst:false,isLoad:false,errMsg:error.message,list:[]})
}
)
this.keyword="";
}
},
}
</script>
③ List组件
<template>
<div class="row">
<h1 v-show="isFirst">Welocme to ...</h1>
<h1 v-show="isLoad">Loading ...</h1>
<h1 v-show="errMsg">请求出错了:{{errMsg}}</h1>
<div class="card" v-for="l in list" :key="l.id">
<a :href="l.html_url" target="_blank">
<img :src="l.avatar_url" style='width: 100px'/>
</a>
<p class="card-text">{{l.login}}x</p>
</div>
</div>
</template>
<script>
export default {
name:"List",
data(){
return {
isFirst:true,
isLoad:false,
errMsg:"",
list:[],
}
},
mounted(){
this.$bus.$on("sendMsg",(msgObj)=>{
this.isFirst=msgObj.isFirst,
this.isLoad=msgObj.isLoad;
this.errMsg=msgObj.errMsg,
this.list=msgObj.list;
})
},
}
</script>
<style >
.card {
float: left;
width: 33.333%;
padding: .75rem;
margin-bottom: 2rem;
border: 1px solid #efefef;
text-align: center;
}
.card > img {
margin-bottom: .75rem;
border-radius: 100px;
}
.card-text {
font-size: 85%;
}
</style>
初始页面
在页面中搜索111,运行结果
三、发送ajax请求的库(网络请求)
1、xhr
ajax增强版
2、jQuery
核心操作DOM,但vue核心是少操作DOM
3、fetch
① 返回的数值被两层then包裹 ② 兼容性差
4、axios
vue官方推荐
5、vue-rouserce
vue官方库,vue1.0常用,但已年久不更新
下载:npm i vue-resource
引入(在main.js文件中引入):import vueRource from "vue-resource"
使用:Vue.use(vueRource) 此时vm与组件实例对象身上都会有$http ,用法与axios一模一样
|