• 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=" 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>
    

  • 相关阅读:
    65 JSP 有哪些内置对象?作用分别是什么?
    为什么 JSP 要被淘汰?
    64 JSP 和 servlet 有什么区别?
    63 深拷贝和浅拷贝区别是什么?
    62 如何实现对象克隆?
    马哥博客作业第二周
    马哥博客作业第一周
    02djangoMVC模型
    01Django实践
    了不起的gatsby.js_一个现代化开发网站的网站产生系统
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/13469205.html
Copyright © 2020-2023  润新知