组织结构:
1.Search组件
2.List列表组件
源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| 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)=>{ this.info = {...this.info,...dataObj} }) }, } </script>
<style scoped> .album { min-height: 50rem; padding-top: 3rem; padding-bottom: 3rem; background-color: #f7f7f7; }
.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>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| Search.vue <template> <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="searchUsers">Search</button> </div> </section> </template>
<script> import axios from 'axios' export default { name:'Search', data() { return { keyWord:'' } }, methods: { searchUsers(){ this.$bus.$emit('updateListData',{isLoading:true,errMsg:'',users:[],isFirst:false}) axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then( response => { console.log('请求成功了') this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items}) }, error => { this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]}) } ) } }, } </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| App.vue <template> <div class="container"> <Search/> <List/> </div> </template>
<script> import Search from './components/Search' import List from './components/List' export default { name:'App', components:{Search,List} } </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({ el:'#app', render: h => h(App), beforeCreate() { Vue.prototype.$bus = this }, })
|
第三方资源引用:
这里用到了bootstrap样式文件的第三方资源,这时用import
引入不是好选择,可以选择放在public文件夹里,再用<link>
引入,这时引入href
属性为<%=BASE_URL %>
前缀
请求和跨域:
引入axios来请求
这个项目的跨域问题由于github给的接口已经由后端通过cors方式解决了跨域问题,所以不用我们解决。
组件通信:
用全局事件总线$bus
实现效果:
项目完善:加上第一次加载主页,正在加载提示,以及报错提示: