【vue脚手架配置代理+github用户搜索案例+vue项目中常用的发送Ajax请求的库+slot插槽】

vue脚手架配置代理+github用户搜索案例+vue项目中常用的发送Ajax请求的库+slot插槽

  • [1 vue脚手架配置代理](#1 vue脚手架配置代理)
  • [2 github用户搜索案例](#2 github用户搜索案例)
    • [2.1 静态列表](#2.1 静态列表)
    • [2.2 列表展示](#2.2 列表展示)
    • [2.3 完善案例](#2.3 完善案例)
  • [3 vue项目中常用的发送Ajax请求的库](#3 vue项目中常用的发送Ajax请求的库)
    • [3.1 xhr](#3.1 xhr)
    • [3.2 jQuery](#3.2 jQuery)
    • [3.3 axios](#3.3 axios)
    • [3.4 fetch](#3.4 fetch)
    • [3.5 vue-resource](#3.5 vue-resource)
  • [4 slot 插槽](#4 slot 插槽)
    • [4.1 效果](#4.1 效果)
    • [4.2 理解](#4.2 理解)

1 vue脚手架配置代理

  • 下载axios

  • 引用axios:import axios from 'axios'

  • 解决跨域方法:
    1> cors:http://t.csdnimg.cn/VdMIT

    2> jsonp:用的少,只能解决get请求的跨域问题
    3> 配置一个代理服务器

  • 配置一个代理服务器方式一:
    开启8080代理服务器方式:nginx(较复杂,需借助后端知识) 、vue-cli(重点)。
    1> 第一步:先通过cmd打开两台服务器

    打开结果如下图所示:

    如忘记打开,终端将会出现GET http://localhost:8081/students 500 (Internal Server Error)错误。
    2> 第二步:在vue.config.js文件里面,加入此语句

    3> 第三步:更改App.vue文件中的端口号

    4> 第四步:点击按钮后,请求结果如下

    工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
    优点:配置简单,请求资源时直接发给前端(8080)即可。
    缺点:1.不能配置多个代理
    2.不能灵活控制走不走代理

  • 配置一个代理服务器方式二:
    1> 第一步:依旧先通过cmd打开两台服务器
    2> 第二步:在vue.config.js文件里面,加入此语句

    changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000 changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080 changeOrigin默认值为true
    3> 第三步:更新App.vue文件中的内容

    4> 第四步:点击按钮后,请求结果如下

    优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
    缺点:配置略微繁琐,请求资源时必须加前缀。

2 github用户搜索案例

2.1 静态列表

  • 目录展示:
  • App.vue:
  • Search.vue:
  • List.vue:
  • index.html:

2.2 列表展示

  • List组件和Search组件为兄弟组件,可使用全局事件总线、消息订阅与发布、把数据交给最外侧App等方式实现数据传递。
  • main.js:
  • Search.vue:
html 复制代码
<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>
    // 引入axios
    import axios from 'axios'

    export default {
        name:'Search',
        data() {
            return {
                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.vue:
html 复制代码
<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:[]
            }
        },
        // 利用全局事件总线
        mounted() {
            this.$bus.$on('getUsers',(users)=>{
                console.log('我是List组件,收到了数据:',users);
                this.users = users
            })
        }
    }
</script>

<style>
    .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>
  • 效果展示(点击头像跳转到用户github主页):

2.3 完善案例

  • 以上展示了请求成功时的呈现(users),还需对其它三种展示进行完善。
  • 1> 添加一个欢迎词(welcome)
  • 2> 当内容未加载出来时添加一个加载中(loading)
  • 3> 添加一个请求失败时的呈现(error)
  • List.vue:
html 复制代码
<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',(isFirst,isLoading,errMsg,users)=>{
            this.$bus.$on('updateListData',(dataObj)=>{
                // console.log('我是List组件,收到了数据:',users);
                /* this.isFirst = isFirst
                this.isLoading = isLoading
                this.errMsg = errMsg
                this.users = users */
                // this.info = dataObj // 此写法没错 但由于isFirst后续不再变化没有书写 会弄丢isFirst数据
                // 因此通过字面量的形式去合并对象
                this.info = {...this.info,...dataObj}
            })
        }
    }
</script>

<style>
    .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>
  • Search.vue:
html 复制代码
<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>
    // 引入axios
    import axios from 'axios'

    export default {
        name:'Search',
        data() {
            return {
                keyWord:''
            }
        },
        methods: {
            searchUsers() {
                // 请求前先更新List的数据
                this.$bus.$emit('updateListData',{isFirst:false,isLoading:true,errMsg:'',users:[]}) 
                // 发送请求
                // 模板字符串
                axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    response => {
                        console.log('请求成功了');
                        // this.$bus.$emit('getUsers',response.data.items)
                        // 请求成功后更新List的数据
                        // 因为isFirst后续不再发生变化 故可删掉
                        this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})
                    },
                    error => {
                        console.log('请求失败了',error.message);
                        // 请求失败后更新List的数据
                        this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
                    }
                )
            }
        }
    }
</script>
  • 效果展示:


3 vue项目中常用的发送Ajax请求的库

3.1 xhr

3.2 jQuery

3.3 axios

  • 通用的 Ajax 请求库, 官方推荐,使用广泛。

3.4 fetch

3.5 vue-resource

  • vue插件库, vue1.x 使用广泛,官方已不维护。
  • 安装:npm i vue-resource
  • 引入与使用:
  • github用户搜索案例的Search.vue组件需改为:

4 slot 插槽

4.1 效果


App.vue:

html 复制代码
<template>
  <div class="container">
    <Category title="美食" :listData="foods"/>
    <Category title="游戏" :listData="games"/>
    <Category title="电影" :listData="films"/>
  </div>
</template>

<script>
  import Category from './components/Category.vue'
  
  export default {
    name:'App',
    components:{Category},
    data() {
      return {
        foods:['火锅','烧烤','小龙虾','牛排'],
        games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
        films:['《教父》','《拆弹专家》','《你好,李焕英》','《米奇妙妙屋》']
      }
    }
  }
</script>

<style lang="css">
  .container {
    display: flex;
    justify-content: space-around;
  }
</style>

Category.vue:

html 复制代码
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <ul>
            <li v-for="(item,index) in listData" :key="index">{{item}}</li>
        </ul>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['listData','title']
    }
</script>

<style>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
</style>


App.vue:

html 复制代码
<template>
  <div class="container">
    <Category title="美食">
      <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
    </Category>

    <Category title="游戏">
      <ul>
        <li v-for="(g,index) in games" :key="index">{{g}}</li>
      </ul>
    </Category>

    <Category title="电影">
      <video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
    </Category>
  </div>
</template>

<script>
  import Category from './components/Category.vue'
  
  export default {
    name:'App',
    components:{Category},
    data() {
      return {
        foods:['火锅','烧烤','小龙虾','牛排'],
        games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
        films:['《教父》','《拆弹专家》','《你好,李焕英》','《米奇妙妙屋》']
      }
    },
  }
</script>

<style scoped>
  .container {
    display: flex;
    justify-content: space-around;
  }
  img {
    width: 100%;
  }
  video {
    width: 100%;
  }
</style>

Category.vue:

html 复制代码
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
        <slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
        
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title']
    }
</script>

<style>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
</style>


App.vue:

html 复制代码
<template>
  <div class="container">
    <Category title="美食">
      <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
      <a slot="footer" href="https://home.meishichina.com/recipe.html">更多美食</a>
    </Category>

    <Category title="游戏">
      <ul slot="center">
        <li v-for="(g,index) in games" :key="index">{{g}}</li>
      </ul>
      <div class="foot" slot="footer">
        <a href="https://www.baidu.com/">单机游戏</a>
        <a href="https://www.baidu.com/">网络游戏</a>
      </div>
    </Category>

    <Category title="电影">
      <video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
      <!-- 写法一 -->
      <!-- <template slot="footer"> -->
      <!-- 写法二 -->
      <template v-slot:footer>
        <div class="foot">
          <a href="https://www.baidu.com/">经典</a>
          <a href="https://www.baidu.com/">热门</a>
          <a href="https://www.baidu.com/">推荐</a>
        </div>
        <h4>欢迎前来观影!</h4>
      </template>
    </Category>
  </div>
</template>

<script>
  import Category from './components/Category.vue'
  
  export default {
    name:'App',
    components:{Category},
    data() {
      return {
        foods:['火锅','烧烤','小龙虾','牛排'],
        games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
        films:['《教父》','《拆弹专家》','《你好,李焕英》','《米奇妙妙屋》']
      }
    },
  }
</script>

<style scoped>
  .container,.foot {
    display: flex;
    justify-content: space-around;
  }
  img {
    width: 100%;
  }
  video {
    width: 100%;
  }
  h4 {
    text-align: center;
  }
  a {
    display: block;
    text-align: center;
  }
</style>

Category.vue:

html 复制代码
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
        <slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现1</slot>
        <slot name="footer">我是一些默认值,当使用者没有传递具体结构时,我会出现2</slot>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title']
    }
</script>

<style>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
</style>


App.vue:

html 复制代码
<template>
  <div class="container">
    <Category title="游戏">
      <template scope="atguigu">
        <ul>
          <li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
        </ul>
      </template>
    </Category>
      
    <Category title="游戏">
      <!-- <template scope="atguigu">
        <ol>
          <li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
        </ol>
      </template> -->
      <!-- 解构赋值写法 -->
      <template scope="{games}">
        <ol>
          <li v-for="(g,index) in games" :key="index">{{g}}</li>
        </ol>
      </template>
    </Category>

    <Category title="游戏">
      <!-- <template scope="atguigu"> -->
      <template slot-scope="{games}">
        <h4 v-for="(g,index) in games" :key="index">{{g}}</h4>
      </template>
    </Category>
  </div>
</template>

<script>
  import Category from './components/Category.vue'
  
  export default {
    name:'App',
    components:{Category},
    
  }
</script>

<style scoped>
  .container,.foot {
    display: flex;
    justify-content: space-around;
  }
  img {
    width: 100%;
  }
  video {
    width: 100%;
  }
  h4 {
    text-align: center;
  }
  a {
    display: block;
    text-align: center;
  }
</style>

Category.vue:

html 复制代码
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <slot :games="games">我是默认的一些内容</slot>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title'],
        data() {
            return {
                games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
            }
        },
    }
</script>

<style>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
</style>

4.2 理解

  • 父组件向子组件传递带数据的标签,当一个组件有不确定的结构时, 就需要使用slot 技术,注意:插槽内容是在父组件中编译后,再传递给子组件的。
  • 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件 ------> 子组件。
  • 分类:默认插槽、具名插槽、作用域插槽
  • 使用方式:
    1> 默认插槽:

    2> 具名插槽:

    3> 作用域插槽:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。 (games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)
相关推荐
Zheng1131 小时前
【可视化大屏】将柱状图引入到html页面中
javascript·ajax·html
前端李易安2 小时前
ajax的原理,使用场景以及如何实现
前端·ajax·okhttp
杨荧2 小时前
【JAVA开源】基于Vue和SpringBoot的旅游管理系统
java·vue.js·spring boot·spring cloud·开源·旅游
一 乐8 小时前
学籍管理平台|在线学籍管理平台系统|基于Springboot+VUE的在线学籍管理平台系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习
小御姐@stella8 小时前
Vue 之组件插槽Slot用法(组件间通信一种方式)
前端·javascript·vue.js
万叶学编程11 小时前
Day02-JavaScript-Vue
前端·javascript·vue.js
萧鼎13 小时前
Python常见问题解答:从基础到进阶
开发语言·python·ajax
积水成江14 小时前
关于Generator,async 和 await的介绍
前端·javascript·vue.js
计算机学姐14 小时前
基于SpringBoot+Vue的高校运动会管理系统
java·vue.js·spring boot·后端·mysql·intellij-idea·mybatis
老华带你飞15 小时前
公寓管理系统|SprinBoot+vue夕阳红公寓管理系统(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·spring boot·课程设计