前言:
? ? ? ? 本次案例是一個基于 Vue2 的全局事件總線通信的仿 Github 用戶搜索模塊,使用的接口是 Github 官方提供的搜索接口:?https://api.github.com/search/users?q=xxx(發(fā)送請求時需要將輸入的用戶名稱綁定替換掉xxx),如果對全局事件總線不太熟練的小伙伴可以看這篇文章:http://t.csdn.cn/oHEOWhttp://t.csdn.cn/oHEOW
文章目錄:
一:效果展示?
二:代碼分析
2.1 綁定自定義事件?
2.2?觸發(fā)自定義事件?
三:源碼獲取
一:效果展示?
- 未搜索用戶頁面
- ?查詢后加載中頁面
- ?查詢成功渲染頁面
- 點擊頭像或下部鏈接進入用戶主頁
- ?查詢失敗頁面報錯提示
二:代碼分析
代碼共分為了兩個子組件,一個是搜索組件(Search),另一個是列表組件(List),其次search組件中輸入框v-model雙向數(shù)據(jù)綁定,點擊搜索后開始查詢,其中過程分為了四步:第一是未搜索的歡迎頁面背景,第二是請求未加載出來的loading背景,第三是渲染用戶列表,第四是請求失敗的報錯提示頁面背景。
2.1 綁定自定義事件?
綁定自定義事件在List組件中,data中的數(shù)據(jù)是定義了userinfo對象來存放其四個狀態(tài)的布爾值,后續(xù)的數(shù)據(jù)傳遞是直接傳遞userinfo這個對象,使用 $on 綁定自定義事件 getuserinfo,當這個事件觸發(fā)時執(zhí)行后面的箭頭回調(diào)函數(shù),將傳遞來的對象接收并覆蓋掉data中原有的四個狀態(tài)布爾值。
<script>
export default {
name:'List',
data() {
return {
UserInfo:{
iswelcome:true,
isloading:false,
users:'',
error:''
}
}
},
mounted(){
this.$bus.$on('getUserInfo',(datas)=>{
// console.log('list組件收到了傳來的用戶數(shù)據(jù)',res);
this.UserInfo=datas
console.log(datas);
})
}
}
</script>
2.2?觸發(fā)自定義事件?
點擊搜索按鈕即可使用 $emit 觸發(fā)自定義事件,在請求成功前會將 isloading 改為true,其余改為false進行數(shù)據(jù)傳遞,傳遞給 list 組件后期就會顯示出loading的背景頁面,其余同理文章來源:http://www.zghlxwxcb.cn/news/detail-777640.html
<script>
export default {
name:'Search',
data(){
return {
ipt_value:'',
}
},
methods:{
search(){
this.$bus.$emit('getUserInfo',{iswelcome:false,isloading:true,users:'',error:''})
this.$axios.get(`https://api.github.com/search/users?q=${this.ipt_value}`).then(
response => {
this.$bus.$emit('getUserInfo',{iswelcome:false,isloading:false,users:response.data.items,error:''})
},
error => {
console.log(error);
this.$bus.$emit('getUserInfo',{iswelcome:false,isloading:false,users:'',error:error})
}
)
this.ipt_value=''
}
}
}
</script>
三:源碼獲取
私聊我即可,感謝支持文章來源地址http://www.zghlxwxcb.cn/news/detail-777640.html
到了這里,關(guān)于Github 用戶查詢案例【基于Vue2全局事件總線通信】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!