vue-搜索github用户

1,拆分组件

2,初始化页面渲染

Main 组件中有请求前,请求中,请求成功,请求失败四种状态,分别定义四个变量控制四种状态

 

 

3,Main 组件有 请求前,请求中,请求成功,请求失败 四种状态,故选择在 Main 组件中发送 ajax 请求更新状态,点击搜索时发布消息告诉Main发送请求,Main 订阅消息开始发送请求

Search 组件发布消息

<template>
  <section class="jumbotron">
    <h3 class="jumbotron-heading">Search Github Users</h3>
    <div>
      <input type="text" placeholder="enter the name you search"  v-model="searchKey"/>
      <button @click="handleSearch">Search</button>
    </div>
  </section>
</template>

<script>
import PubSub from "pubsub-js";
export default {
  data:function(){
    return{
      searchKey:''
    }
  },
  methods: {
   handleSearch(){
     PubSub.publish('search',(this.searchKey))
   }
  },
};
</script>

Main组件订阅消息,并发送 ajax 请求更新请求前后的数据

<template>
  <div>
    <h3 v-if="firstView">请输入关键词搜索</h3>
    <h3 v-if="loading">请求中</h3>
    <h3 v-if="errMsg">{{errMsg}}</h3>
    <div class="row" v-show="users.length>0">
      <div class="card" v-for="(user,index) in users" :key="index">
        <a :href="user.url" target="_blank">
          <img :src="user.avatarUrl" style="width: 100px" />
        </a>
        <p class="card-text">{{user.username}}</p>
      </div>
    </div>
  </div>
</template>

<script>
import PubSub from "pubsub-js";
import axios from 'axios'
export default {
  data: function () {
    return {
      firstView:true, //是否显示初始页面
      loading:false, //是否是请求中
      users:[] , //请求成功返回的数据
      errMsg:'', //请求失败返回的错误信息
    }
  },
  mounted(){
    PubSub.subscribe('search',(msg,searchKey)=>{
      this.getUsers(searchKey);
    })
  },
  methods: {
    getUsers(searchKey){
      //更新数据(请求中)
      this.firstView=false;
      this.loading=true;
      this.users=[];
      this.errMsg='';
      const url=`https://api.github.com/search/users?q=${searchKey}`
      axios.get(url)
        .then(res=>{
          this.loading=false;
          this.users=res.data.items.map(item=>({
            url:item.html_url,
            avatarUrl:item.avatar_url,
            username:item.login
          }))
        })
        .catch(err=>{
          this.loading=false;
          this.errMsg='请求失败';
        })
    }
  },
};
</script>

 

posted @ 2021-02-01 23:29  shanlu  阅读(104)  评论(0编辑  收藏  举报