Vue知识点整理(四)- Vue中的ajax(1)- 配置代理、github用户搜索案例

目录

一、配置代理

1.1. vue脚手架配置代理

二、github用户搜索案例

2.1 静态组件

2.1.1 App.vue - 项目主组件

2.1.2 Search.vue - 搜索框组件

2.1.3 List.vue - 列表组件

2.1.4 bootstrap.css - 第三方样式

2.2 列表展示

2.2.1 main.js

2.2.2 List.vue

2.2.3 Search.vue


一、配置代理

1.1. vue脚手架配置代理

方法一:

官方文档:Vue CLI - 配置参考 - devServer

在vue.config.js中添加如下配置:

module.exports = {
  devServer: {
    proxy: 'http://localhost:4000'
  }
}
  • 优点:配置简单,请求资源时直接发给前端(8080)即可
  • 缺点:不能够配置多个代理,不能灵活的控制请求是否走代理
  • 工作方式:若按照上述配置,当请求了前端不存在的资源时,那么请求会转发给服务器(优先匹配前端资源,即前端资源命名与服务器内的请求命名相同时,会优先获取前端资源,而非走代理转发给服务器

方法二:

官方文档 :Vue CLI - 配置参考 - devServer.proxy

编写vue.config.js配置具体代理规则:

module.exports = {
  devServer: {
    proxy: {
      '/api1': {    // 匹配所有以 '/api1' 开头的请求路径
        target: '<url>',    // 代理目标的基础路径
        ws: true,
        changeOrigin: true,
        pathRewrite: {'^/api1': ''}    // 重写路径,匹配所有以api1开头的路径,并将api1改为空字符串
      },
      '/api2': {    // 匹配所有以 '/api2' 开头的请求路径
        target: '<other_url>',    // 代理目标的基础路径
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
/* 
    举例:请求头中的host为:localhost:8080, 服务器基础路径中的host为: localhost:5000
    changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
    changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
    changeOrigin默认值为true
 */
  • 优点:可以配置多个代理,且可以灵活控制请求是否走代理
  • 缺点:配置相略微繁琐,请求资源时必须加前缀

二、github用户搜索案例

2.1 静态组件

首先将静态页面以各个组件划分

2.1.1 App.vue - 项目主组件

主组件app.vue调用其他组件,构建页面

<template>
  <div class="container">
    <Search></Search>
    <List></List>
  </div>
</template>

<script>
import Search from "./components/Search.vue";
import List from "./components/List.vue";

export default {
  name: "App",
  components: { Search, List },
};
</script>

<style></style>

2.1.2 Search.vue - 搜索框组件

目前 Search.vue 仅包含搜索框基本结构

<template>
  <section class="jumbotron">
    <h3 class="jumbotron-heading">Search Github Users</h3>
    <div>
      <input
        type="text"
        placeholder="enter the name you search"
      />&nbsp;<button>Search</button>
    </div>
  </section>
</template>

<script>
export default {
  name: "Search",
};
</script>

<style></style>

2.1.3 List.vue - 列表组件

目前 Search.vue 仅包含列表基本结构

<template>
  <div class="row">
    <div class="card">
      <a href="https://github.com/xxxxxx" target="_blank">
        <img src="https://cn.vuejs.org/images/logo.svg" style="width: 100px" />
      </a>
      <p class="card-text">xxxxxx</p>
    </div>
    <div class="card">
      <a href="https://github.com/xxxxxx" target="_blank">
        <img src="https://cn.vuejs.org/images/logo.svg" style="width: 100px" />
      </a>
      <p class="card-text">xxxxxx</p>
    </div>
    <div class="card">
      <a href="https://github.com/xxxxxx" target="_blank">
        <img src="https://cn.vuejs.org/images/logo.svg" style="width: 100px" />
      </a>
      <p class="card-text">xxxxxx</p>
    </div>
    <div class="card">
      <a href="https://github.com/xxxxxx" target="_blank">
        <img src="https://cn.vuejs.org/images/logo.svg" style="width: 100px" />
      </a>
      <p class="card-text">xxxxxx</p>
    </div>
    <div class="card">
      <a href="https://github.com/xxxxxx" target="_blank">
        <img src="https://cn.vuejs.org/images/logo.svg" style="width: 100px" />
      </a>
      <p class="card-text">xxxxxx</p>
    </div>
  </div>
</template>

<script>
export default {
  name: "List",
};
</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: 0.75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: 0.75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>

2.1.4 bootstrap.css - 第三方样式

下载 bootstrap.css:Versions · Bootstrap v5.1 (getbootstrap.com) ,选择3.4版本即可

引入bootstrap.css:在public文件夹下创建css文件夹,将bootstrap.css拖入文件夹后,在index.html内引入即可

    <!-- 引入第三方样式 -->
    <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css" />

注意:静态页面的css样式文件引入的第二种方法,将样式文件放入 src文件夹 -> assets文件夹 -> css文件夹,并在App.vue中引入。但通过该方式引入的样式,vue脚手架会做一个非常严格的检查,即该css样式文件内只要使用到不存在的资源,就会出现报错。所以第三方样式(公共样式)不采用该方法引入,而是使用link标签引入。

import './assets/css/xxx.css'

2.2 列表展示

在输入框内输入内容后,点击按钮,向github网站提供的免费接口发送请求:

因此需要提前安装axios,在终端输入以下内容即可

cnpm install axios --save 或者 npm install axios --save

2.2.1 main.js

因为用到了全局事件总线,所以在main.js内安装全局事件总线

// 引入Vue
import Vue from "vue";
// 引入App
import App from "./App.vue";

Vue.config.productionTip = false;

// 创建vm
new Vue({
  el: "#app",
  render: (h) => h(App),
  // 安装全局事件总线
  beforeCreate() {
    Vue.prototype.$bus = this;
  },
});

2.2.2 List.vue

  • 利用 v-show 分别展示在 第一次使用时、搜索加载时、用户列表加载完毕后、请求失败时 4种情况时该区域显示的内容
  • 利用全局事件总线绑定 updateListData事件,并设置回调函数
<template>
  <div class="row">
    <div
      class="card"
      v-show="info.users.length"
      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) => {
      // 利用扩展运算'...'符合并去重
      this.info = { ...this.info, ...dataObj };
      console.log(this);
    });
  },
};
</script>

<style scoped>
...
</style>

2.2.3 Search.vue

  • 用v-model绑定输入框输入的内容与 keyWord 绑定,且通过点击按钮触发 searchUsers事件
  • 触发 searchUsers事件后,通过axios向github网站提供的免费接口发送请求,并用ES6模板字符串的方式,是接口链接后面接上 keyWord
  • 若请求成功,通过 全局事件总线 触发当前实例上的updateListData事件,并回传给List.vue上的监听器回调
  • 若请求失败,通过 全局事件总线 触发当前实例上的updateListData事件,并回传给List.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("updataListData", {
        isFirst: false,
        isLoading: true,
        errMsg: "",
        users: [],
      });
      // ES6模板字符串, 通过axios向github网站提供的免费接口发送请求
      axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
        (response) => {
          console.log("请求成功!");
          console.log(response);
          // 请求成功后更新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>

<style></style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JHY97

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值