通过小项目演示使用vue-axios如何和后端进行通信!
vue项目中通常使用的两个ajax库!
1:插件vue-resource(不推荐使用,常用在vue1.0)
2:axios(推荐使用!!!!!)
- 案例内容:
目标:根据关键字 V 在后台GitHub中进行搜索,搜索到最受欢迎的带v的仓库(肯定是vue了)
然后点击链接,就回跳转到相应的主页中!
具体:是一个异步效果,没有请求到时,显示loading状态,返回后显示相应链接
- 具体结构代码如下:
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测试小案例结束,记录学习,感谢观看!