Vue之Ajax---用户搜索案例

 效果图如上,因为上传TodoList案例中List中嵌套了Item组件,此处便尝试不嵌套,直接写List组件

1、组件化

和之前案例一样,index.html代码复制到<template><div id="app">这里</div></template>

index也是和上面一样复制到App.vue内,只不过是<style>标签内,注意此时只是先大致看看页面样子,待会要拆html和css代码放到不同组件当中

bootstrap.css这种已经成型的公共样式引入方法:

1、新建文件src/assets/css,assets就是静态资源文件夹,复制bootstrap文件到css内

2、新建文件public/css,复制bootstrap文件到css内

以上方法都需要在App.vue内引入,分别是:

1、在App.vue内import './assets/css/bootstrap.css',有缺点是如果bootstrap.css内存在一些不存在引入文件资源,如字体文件之类的,Vue会严格检查导致报错,但是该案例只需要bootstrap的卡片式图。bootstrap内还引入其他不存在的第三方资源,此时便不推荐改引入方法。

2、在index.html内<link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">,不会存在上面的问题。<link>不会报错

 分别是App.vue内和index.html内引入示例

 

组件化: 

然后是拆组件,我们之前把所有的div内容全复制在App.vue,现在要根据Search和List将该处代码分开到Search和List组件内,然后在App.vue当中应用并且注册两组件

同上,把之前复制的index.css样式也分开粘贴到两个组件当中并且<style scoped>,该项目中css样式全部为Search服务

 tips:index.html内

即之前的index.html和App.vue外层都是一个上面22行代码,一点重复了,所以说组件化时候删除一个。所以说在App.vue内不要用<div id="app">

2、列表展示

用户列表即用户data数据是在List组件内

1、请求地址为:https://api.github.com/search/users?q=xxx

其中q=xxx是请求的参数

2、请求事件是在Search组件内,但是请求的结果显示在List当中,两组件兄弟关系,所以说事件总线传递数据

3、显示在List组件中的内容有用户头像(avatar_url)、用户名(login)、用户首页链接(html_url)

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

<script>
    import axios from 'axios';
    export default {
        name:'Search',
        data(){
            return{
                keyWord:''
            }
        },
        //q=${this.keyWord}动态绑定输入框的值来作为请求的参数
        methods: {
            searchUsers(){
                axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    response => {
                        console.log('请求成功');
                        this.$bus.$emit('getUsers',response.data.items)
                    },
                    error => {
                        console.log('请求失败',error.message)
                    }
                )
            }
        }
    }
</script>
//List组件
//注意下面的用户名、头像、链接都是动态绑定的,要前面加冒号:
<template>
    <div class="row">
        <div class="card" v-for="user in 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>
    </div>
</template>

<script>
    export default {
        name:'List',
        data(){
            return{
                users:[]
            }            
        },
        //全局事件总线,main.js里面要配置内容不要忘了
        mounted() {
            this.$bus.$on('getUsers',(users)=>{
                console.log('List组件收到数据:',users);
                this.users = users
            })
        },
    }
</script>

3、完善案例 

需要完善的地方:

最初的欢迎词 isFirst:true,               //是否初次请求,一开始是true

加载的isLoading:false,                    //是否加载中,一开始是false

发送请求失败的信息errMsg:' ',        //错误信息(如果用isError只会返回成和不成布尔值)

补充es6知识点:扩展运算符合并数组

//合并数组,就相当于把arr1和arr2展开在[]当中,重名的以后边的为准
arr1:{name:'赵仕强',age:11}
arr2:{name:'嘀嘀嘀',gender:1}
let newarr = {...arr1,...arr2}   //{name:'嘀嘀嘀',age:11,gender:1}

let arr1=[11,22,33,55];
let arr2=["aa","bb","cc","dd"];
let newarr=[...arr1,...arr2]    // [11, 22, 33, 55, "aa", "bb", "cc", "dd"]

 

//List组件代码
<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>
		<!-- 展示错误信息 info.errMsg是显示详细错误信息-->
		<h1 v-show="info.errMsg">{{info.errMsg}}</h1>
    </div>
</template>

<script>
    export default {
        name:'List',
        data(){
            return{
                //data的数据较多,为了下面批量替换加上info,否则就要一个个的用,不能info一次弄完
                info:{
                    isFirst:true,      //是否初次请求,一开始是
                    isLoading:false,   //是否加载中,一开始是否
                    errMsg:'',         //错误信息
                    users:[]
                }
            }            
        },
        //发送users时,顺便把其余三个数据也发送了
        mounted() {
            this.$bus.$on('updateListData',(dataObj)=>{
                this.info = {...this.info,...dataObj}
            })
        },
    }
</script>
//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="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',{isFirst:false,isLoading:true,reeMsg:'',users:[]})
                axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    response => {
                        console.log('请求成功');
                        //请求成功更新list数据,isFirst是因为在加入页面是true,请求前false,后面一直false,不管他了
                        this.$bus.$emit('updateListData',{isLoading:false,reeMsg:'',users:response.data.items})
                    },
                    error => {
                        console.log('请求失败')
                        //请求失败更新list数据,失败了users要变为空,否则下一次请求会残留此次的数据
                        this.$bus.$emit('updateListData',{isLoading:false,reeMsg:'error.message',users:[]})
                    }
                )
            }
        }
    }
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值