分析
将页面分为两个组件List
、Search
在Search
组件内发送请求,请求成功/失败后,向List
组件传数据(兄弟间传数据——全局事件总线),List
组件接收数据。
对于List
组件,刚进入页面展示欢迎词,搜索中展示加载中,搜索成功后展示用户列表,搜索失败展示错误信息。
App.vue
<template>
<div class="container">
<Search/>
<List/>
</div>
</template>
<script>
// import axios from 'axios'
import Search from "./components/Search.vue"
import List from "./components/List.vue"
export default {
name: "App",
components:{Search,List}
}
</script>
Search.vue
<template>
<section class="jumbotron">
<h3 class="jumbotron-heading">Search Github Users</h3>
<div>
<input type="text" v-model="keyWord" placeholder="enter the name you search"/>
<button @click="searchUsers">Search</button>
</div>
</section>
</template>
<script>
import axios from 'axios'
export default {
name:'Search',
data() {
return {
keyWord:''
}
},
methods:{
searchUsers(){
//请求前更新List数据
this.$bus.$emit('updateListData',{isFirst:false,isLoading:true,errMsg:'',users:[]})
axios.get(`http://api.github.com/search/users?q=${this.keyWord}`).then(
response => {
// console.log('请求成功了',response.data.items);
//请求成功后更新
this.$bus.$emit('updateListData',{isLoading:false,errMsg:{},users:response.data.items})
},
error => {
// console.log('请求失败了',error.message);
//请求失败后更新
this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
}
)
}
}
}
</script>
List.vue
<template>
<div class="row">
<!-- 展示用户列表 -->
<div v-show="info.users.length" class="card" v-for="user in info.users" :key="user.login">
<a :href="user.html_url" target="_blank">
<img :src="user.avatar_url" style='width: 100px'/>
</a>
<p class="card-text">{{user.login}}</p> <!-- 用户名 -->
</div>
<!-- 展示欢迎词 -->
<h1 v-show="info.isFirst">欢迎使用!</h1>
<!-- 展示加载中 -->
<h1 v-show="info.isLoading">加载中...</h1>
<!-- 展示错误信息 -->
<h1 v-show="info.errMsg">{{info.errMsg}}</h1>
</div>
</template>
<script>
export default {
name:'List',
data() {
return {
info:{
isFirst:true,
isLoading:false,
errMsg:'',
users:[]
}
}
},
mounted(){
this.$bus.$on('updateListData',(dataObj)=>{
// console.log('我是List组件,收到数据',users);
this.info = {...this.info,...dataObj}
})
}
}
</script>
若使用vue-resource
将axios.get
改为this.$http.get