使用 axios
npm i axios --save
使用时事件总线
main.js
Vue.prototype.$bus = new Vue()
List组件
<template>
<div>
<div class="list_wrap">
<!-- 展示用户列表 -->
<div
v-show="info.users.length"
class="item_wrap"
v-for="user in info.users"
:key="user.id">
<a :href="user.html_url" target="_blank">
<img :src="user.avatar_url" alt="" />
</a>
<p>{{ 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>
</div>
</template>
<script>
export default {
name: "List",
data() {
return {
info: {
isFirst: true, //是否第一次加载
isLoading: false, // 是否加载中
errMsg: "", // 错误信息
users: [], //用户列表
},
};
},
mounted() {
this.$bus.$on("updateListData", (dataObj) => {
console.log(dataObj);
this.info = { ...this.info, ...dataObj };
});
},
};
</script>
<style lang="less" scoped>
.list_wrap {
width: 80%;
margin: auto;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
&::after {
content: "";
}
.item_wrap {
text-align: center;
margin-top: 20px;
padding: 0 10px;
img {
width: 80px;
height: 80px;
}
p {
width: 80px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
}
</style>
Search组件
<template>
<div>
<div class="search_wrap">
<input type="text" v-model="keyWord" />
<button @click="handleSerch">搜索</button>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "Search",
data() {
return {
keyWord: 0,
};
},
methods: {
handleSerch() {
// 请求前更新list数据
this.$bus.$emit("updateListData", {
isFirst: false,
isLoading: true,
errMsg: "",
users: [],
});
axios.get(`https://api.github.com/1search/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>
<style>
.search_wrap {
width: 80%;
background-color: rgb(221, 221, 221);
margin: auto;
text-align: center;
padding: 30px 0;
}
</style>
App组件
<template>
<div>
<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>
<style>
* {
padding: 0;
margin: 0;
}
</style>
网友评论