Vue_Ajax请求------axios入门小案例

通过小项目演示使用vue-axios如何和后端进行通信!

vue项目中通常使用的两个ajax库!
	1:插件vue-resource(不推荐使用,常用在vue1.0)
	2:axios(推荐使用!!!!!)
  1. 案例内容:
目标:根据关键字 V  在后台GitHub中进行搜索,搜索到最受欢迎的带v的仓库(肯定是vue了)
           然后点击链接,就回跳转到相应的主页中!
具体:是一个异步效果,没有请求到时,显示loading状态,返回后显示相应链接
  1. 具体结构代码如下:
1:新建vue项目(这里使用vue cli3脚手架创建)
	vue create exercise_axios 
2:页面结构(未渲染,只做演示)
<template>
  <div>
  	//请求链接为空,继续loading显示
    <div v-if="!repoUrl">loading...</div>
    <div v-else>
      github中最多标记的仓库是<a :href="repoUrl">{{ repoName }}</a>
    </div>
  </div>
</template>
3:页面逻辑结构如下

在这里插入图片描述

4:接口信息分析与代码对应
    const url = 'https://api.github.com/search/repositories?q=v&sort=stars'
    查看接口对应的数据,来分析请求代码如何完成

在这里插入图片描述
对应的代码逻辑:
在这里插入图片描述

5:发送请求代码

逻辑结构以及代码展示:
在这里插入图片描述

6:实例结果展示:

在这里插入图片描述

7:验证失败请求:
更改链接代码查找规则如下:
search----> search11----->理想结果,弹出alert警告
const url = 'https://api.github.com/search11/repositories?q=v&sort=stars'

在这里插入图片描述

实例完整代码:

<template>
  <div>
    <div v-if="!repoUrl">loading...</div>
    <div v-else>
      <p>成功查找到数据如下:</p>
      github中最多标记的仓库是<a :href="repoUrl">{{ repoName }}</a>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'App',
  components: {

  },
  data () {
    return {
      repoUrl: '',
      repoName: ''
    }
  },
  // 发送ajax请求一般都是在声明周期回调函数中进行 三个阶段:初始化  更新 死亡
  mounted () {
    // 使用vue-resource发送ajax请求数据
    const url = 'https://api.github.com/search11/repositories?q=v&sort=stars'
    // 使用axios发送ajax请求
    axios.get(url).then(
      response => {
        const result = response.data
        const mostRepo = result.items[0]
        this.repoUrl = mostRepo.html_url
        this.repoName = mostRepo.name
      }).catch(() => {
        alert('查找失败了');
      })
  }

}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

至此:vue-axios测试小案例结束,记录学习,感谢观看!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值