效果展示
App页面的代码:
<template>
<div id="app">
<Search></Search>
<List></List>
</div>
</template>
<script>
import Search from './components/Search.vue'
import List from './components/List.vue'
export default {
name: 'App',
components: {
Search,
List,
},
data(){
return {
}
}
}
</script>
子组件List的代码
<template>
<div class="row">
<!-- 展示用户列表 -->
<div
v-show="info.users.length"
class="card"
v-for="item in info.users"
:key="item.id"
>
<a :href="item.html_url" target="_blank">
<img :src="item.avatar_url" style="width: 100px" />
</a>
<p class="card-text">{{ item.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) => {
// 保证info中的数据不丢失
this.info={...this.info,...dataObj}
});
},
};
</script>
<style scoped>
.row{
display: flex;
flex-wrap: wrap;
}
</style>
子组件search的代码
<template>
<section>
<h3>Search Github Users</h3>
<div>
<input type="text" placeholder="enter the name you search" v-model="keyWord" />
<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(`https://api.github.com/search/users?q=${this.keyWord}`).then(
response=>{
// 请求成功
this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})
},
error=>{
// 请求失败
this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
}
)
}
}
}
</script>