《进阶篇第7章》学习vue中的ajax之后,练习vue案例-github用户搜索案例

简介: 《进阶篇第7章》学习vue中的ajax之后,练习vue案例-github用户搜索案例

image.png

@[toc]

概述:该案例是学习完第6章:vue中的ajax之后,进行的练习和总结,相关知识点详情内容,请查看我的上一篇同一专栏文章。

7.1github接口地址

https://api.github.com/search/users?q=xxx
这是github维护的一个简单测试接口,其中xxx输入什么内容,github接口就会返回相关的数据。

7.2案例代码

注意点1:

问题:这次如何划分组件?

image.png

答案:这次只划分2个组件,上方的search.vue,下方的List.vue

注意点2:axios的get请求url拼接参数有2种方式

> 方式1:字符串+拼接

java axios.get(`https://api.github.com/search/users?q=` + this.keyWord).then()

> 方式2:采用ES6语法,地址字符串采用单引号’’,同时使用${}

java axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then()
注意点3:优化页面效果,初始化显示展示欢迎词,点击按钮调接口时显示加载中...,如果调用报错显示错误信息提示,因此定义4个属性来控制:isFirst、isLoading、errMsg、users,
初始化时:isFirst:true, isLoading:false, errMsg:'', users:[]
请求前更新List的数据:isFirst:false, isLoading:true, errMsg:'', users:[]
请求成功后更新List的数据:isLoading:false, errMsg:'', users:response.data.items
请求失败后更新List的数据:isLoading:false, errMsg:error.message, users:[]
请求失败后 users必须制空,不然页面还是会显示上次成功请求的数据 注意点4:
全局事件总线传多个参数方式有以下几种
方式1:如下直接传多个参数,缺点1:不优雅不直观,不写注释压根不知道传过去的true、false、’’、[]啥意思;缺点2:接收方必须按照索引顺序才能获取参数。

java this.$bus.$emit('updateListData', true, false, '', [])
方式2:传过去的参数封装成json对象方式,
传递方
this.$bus.$emit('updateListData',{
   isLoading:true,errMsg:'',users:[],isFirst:false})
接收方,方式1通过this.属性挨个赋值,缺点:我有100个属性赋值100行?不现实

java data() { return { info:{ isFirst:true, isLoading:false, errMsg:'', users:[] } } }, mounted() { this.$bus.$on('updateListData',(dataObj)=>{ this.info.isFirst = dataObj.isFirst; this.info.isLoading = dataObj.isLoading; this.info.errMsg = dataObj.errMsg; this.info.users = dataObj.users; }) },
接收方,方式2通过整个对象赋值,缺点:会丢属性值,data函数有4个属性,而我传递的dataObj只有3个属性,那么最后控制台会整个替换从而丢一个属性

java data() { return { info:{ isFirst:true, isLoading:false, errMsg:'', users:[] } } }, mounted() { this.$bus.$on('updateListData',(dataObj)=>{ this.info= dataObj; }) },
接收方,方式3通过ES6语法实现局部更新,语法:{...原数据,...接收数据},dataObj没有的属性用data() 原有的,dataObj包含的属性采用dataObj传递过来的值,另一个好处传递方不按属性顺序传值也能接收。
传递方,比如data()中isFirst为第一个属性,而我传递时放在了{}的最后也有效

java this.$bus.$emit('updateListData',{isLoading:true,errMsg:'',users:[],isFirst:false})
接收方
data() {
   
    return {
   
        info:{
   
            isFirst:true,
            isLoading:false,
            errMsg:'',
            users:[]
        }
    }
},
mounted() {
   
    this.$bus.$on('updateListData',(dataObj)=>{
   
             this.info = {
   ...this.info,...dataObj}       
    })
},
注意点5:

问题:注意点3中接收方,方式2通过整个对象赋值方式,我可以把dataObj直接复制给this._data中吗?

答案:不能,如果赋值给this._data就破坏数据结构了,因为直接赋值方式不会让vue动态代理给_data中设置get和set方法。

完整代码

项目结构

image.png

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
   
    el:'#app',
    render: h => h(App),
    beforeCreate() {
   
        Vue.prototype.$bus = this
    },
})

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>

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"/>&nbsp;
            <button @click="searchUsers">Search</button>
        </div>
    </section>
</template>

<script>
    import axios from 'axios'
    export default {
   
        name:'Search',
        data() {
   
            return {
   
                keyWord:''
            }
        },
        methods: {
   
            searchUsers(){
   
                //请求前更新List的数据
                this.$bus.$emit('updateListData',{
   isLoading:true,errMsg:'',users:[],isFirst:false})
        //axios的get请求url拼接参数方式1:字符串+拼接
                axios.get(`https://api.github.com/search/users?q=` + this.keyWord).then(
                //axios的get请求url拼接参数方式2:采用ES6语法,地址字符串采用单引号’’,同时使用${}
        // axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    response => {
   
                        console.log('请求成功了')
                        //请求成功后更新List的数据
                        this.$bus.$emit('updateListData',{
   isLoading:false,errMsg:'',users:response.data.items})
                    },
                    error => {
   
                        //请求失败后更新List的数据
                        this.$bus.$emit('updateListData',{
   isLoading:false,errMsg:error.message,users:[]})
                    }
                )
            }
        },
    }
</script>

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)=>{
   
        //接收方,方式1通过this.属性挨个赋值,缺点:我有100个属性赋值100行?
        // this.info.isFirst = dataObj.isFirst;
        // this.info.isLoading = dataObj.isLoading;
        // this.info.errMsg = dataObj.errMsg;
        // this.info.users = dataObj.users;

        //接收方,方式2通过整个对象赋值,缺点:会丢属性值
        // this.info = dataObj;

        //接收方,方式3采用ES6语法,局部更新
                this.info = {
   ...this.info,...dataObj}
            })
        },
    }
</script>

<style scoped>
    .album {
   
        min-height: 50rem; /* Can be removed; just added for demo purposes */
        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>

结果展示:

image.png

7.3把github用户搜索案例使用axios方式改为使用vue-resource方式

改变地方

main.js

//引入插件
import vueResource from 'vue-resource'
//使用插件
Vue.use(vueResource)

Search.vue

旧代码:
axios.get(`https://api.github.com/search/users?q=` + this.keyWord).then()
新代码:
this.$http.get(`https://api.github.com/search/users?q=${
   this.keyWord}`).then()

完整代码

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false
//引入插件
import vueResource from 'vue-resource'
//使用插件
Vue.use(vueResource)

//创建vm
new Vue({
   
    el:'#app',
    render: h => h(App),
    beforeCreate() {
   
        Vue.prototype.$bus = this
    },
})

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>

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"/>&nbsp;
            <button @click="searchUsers">Search</button>
        </div>
    </section>
</template>

<script>
    //import axios from 'axios'
    export default {
   
        name:'Search',
        data() {
   
            return {
   
                keyWord:''
            }
        },
        methods: {
   
            searchUsers(){
   
                //请求前更新List的数据
                this.$bus.$emit('updateListData',{
   isLoading:true,errMsg:'',users:[],isFirst:false})
        this.$http.get(`https://api.github.com/search/users?q=${
   this.keyWord}`).then(
        //axios的get请求url拼接参数方式1:字符串+拼接
                //axios.get(`https://api.github.com/search/users?q=` + this.keyWord).then(
                //axios的get请求url拼接参数方式2:采用ES6语法,地址字符串采用单引号’’,同时使用${}
        // axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    response => {
   
                        console.log('请求成功了')
                        //请求成功后更新List的数据
                        this.$bus.$emit('updateListData',{
   isLoading:false,errMsg:'',users:response.data.items})
                    },
                    error => {
   
                        //请求失败后更新List的数据
                        this.$bus.$emit('updateListData',{
   isLoading:false,errMsg:error.message,users:[]})
                    }
                )
            }
        },
    }
</script>

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)=>{
   
        //接收方,方式1通过this.属性挨个赋值,缺点:我有100个属性赋值100行?
        // this.info.isFirst = dataObj.isFirst;
        // this.info.isLoading = dataObj.isLoading;
        // this.info.errMsg = dataObj.errMsg;
        // this.info.users = dataObj.users;

        //接收方,方式2通过整个对象赋值,缺点:会丢属性值
        // this.info = dataObj;

        //接收方,方式3采用ES6语法,局部更新
                this.info = {
   ...this.info,...dataObj}
            })
        },
    }
</script>

<style scoped>
    .album {
   
        min-height: 50rem; /* Can be removed; just added for demo purposes */
        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>
目录
相关文章
|
9月前
|
编解码 Oracle Java
java9到java17的新特性学习--github新项目
本文宣布了一个名为"JavaLearnNote"的新GitHub项目,该项目旨在帮助Java开发者深入理解和掌握从Java 9到Java 17的每个版本的关键新特性,并通过实战演示、社区支持和持续更新来促进学习。
289 3
|
9月前
|
前端开发 JavaScript Java
第6章:Vue中的ajax(包含:回顾发送ajax请求方式、vue-cli脚手架配置代理服务器)
第6章:Vue中的ajax(包含:回顾发送ajax请求方式、vue-cli脚手架配置代理服务器)
174 4
|
10月前
|
前端开发
React技术栈-react使用的Ajax请求库实战案例
这篇文章介绍了在React应用中使用Axios和Fetch库进行Ajax请求的实战案例,展示了如何通过这些库发送GET和POST请求,并处理响应和错误。
110 10
React技术栈-react使用的Ajax请求库实战案例
|
10月前
|
前端开发
React技术栈-react使用的Ajax请求库用户搜索案例
这篇文章展示了一个React技术栈中使用Ajax请求库(如axios)进行用户搜索的实战案例,包括React组件的结构、状态管理以及如何通过Ajax请求获取并展示GitHub用户数据。
86 7
React技术栈-react使用的Ajax请求库用户搜索案例
|
10月前
|
JSON 资源调度 JavaScript
Vue框架中Ajax请求的实现方式:使用axios库或fetch API
选择 `axios`还是 `fetch`取决于项目需求和个人偏好。`axios`提供了更丰富的API和更灵活的错误处理方式,适用于需要复杂请求配置的场景。而 `fetch`作为现代浏览器的原生API,使用起来更为简洁,但在旧浏览器兼容性和某些高级特性上可能略显不足。无论选择哪种方式,它们都能有效地在Vue应用中实现Ajax请求的功能。
204 4
|
9月前
|
Unix Shell 网络安全
git学习六:(bug总结)git@github.com: Permission denied (publickey).等
本文是关于解决在使用Git和GitHub时遇到的“git@github.com: Permission denied (publickey)”错误的指南。文章提供了详细的步骤,包括确认SSH Agent运行状态、检查密钥配置、确保密钥匹配、验证仓库URL、检查权限和代理设置,以及配置SSH文件。这些步骤帮助用户诊断并解决SSH认证问题。
1288 0
|
11月前
|
数据采集 数据可视化 Ruby
GitHub星标破万!Python学习教程(超详细),真的太强了!
Python 是一门初学者友好的编程语言,想要完全掌握它,你不必花上太多的时间和精力。 Python 的设计哲学之一就是简单易学,体现在两个方面: 1. 语法简洁明了:相对 Ruby 和 Perl,它的语法特性不多不少,大多数都很简单直接,不玩儿玄学。 2. 切入点很多:Python 可以让你可以做很多事情,科学计算和数据分析、爬虫、Web 网站、游戏、命令行实用工具等等等等,总有一个是你感兴趣并且愿意投入时间的。
|
12月前
|
人工智能 数据挖掘 大数据
爆赞!GitHub首本标星120K的Python程序设计人工智能案例手册
为什么要学习Python? Python简单易学,且提供了丰富的第三方库,可以用较少的代码完成较多的工作,使开发者能够专注于如何解决问题而只花较少的时间去考虑如何编程。此外,Python还具有免费开源、跨平台、面向对象、胶水语言等优点,在系统编程、图形界面开发、科学计算、Web开发、数据分析、人工智能等方面有广泛应用。尤其是在数据分析和人工智能方面,Python已成为最受开发者欢迎的编程语言之一,不仅大量计算机专业人员选择使用Python进行快速开发,许多非计算机专业人员也纷纷选择Python语言来解决专业问题。 由于Python应用广泛,关于Python的参考书目前已经有很多,但将Pytho
N..
|
XML JSON 前端开发
jQuery实现Ajax
jQuery实现Ajax
N..
115 1
|
XML 前端开发 JavaScript
jQuery中ajax如何使用
jQuery中ajax如何使用
168 0

热门文章

最新文章