axios:通用的ajax请求库,适用范围广,官方支持
vue-resource:vue插件库,vue1.0版本用,已经年久不维护
需求:通过github搜索用户名,并渲染到页面
github查找用户名接口:https://api.github.com/search/users?q=xxx
npm i axios
import axios from "axios"
① 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 Usersh3>
<div>
<input type="text" placeholder="enter the name you search" v-model="keyword"/>
<button @click="getKeyword">Searchbutton>
div>
section>
div>
template>
<script>
//引入ajax
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}}xp>
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>
ajax增强版
核心操作DOM,但vue核心是少操作DOM
① 返回的数值被两层then包裹
② 兼容性差
vue官方推荐
vue官方库,vue1.0常用,但已年久不更新
下载:npm i vue-resource
引入(在main.js文件中引入):import vueRource from "vue-resource"
使用:Vue.use(vueRource)
此时vm与组件实例对象身上都会有$http
,用法与axios一模一样