您的位置:首页 > Web前端 > Vue.js

VUE学习笔记——AJAX

2019-08-04 11:37 288 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_38763173/article/details/98452875

VUE学习笔记——AJAX


vue 项目中常用的 2 个 ajax 库:
1、vue-resource——vue 插件, 非官方库, vue1.x 使用广泛
2、axios——通用的 ajax 请求库, 官方推荐, vue2.x 使用广泛

vue-resource

npm install vue-resource --save
测试接口 : https://api.github.com/search/repositories?q=v&sort=stars

main.js

import Vue from 'vue'
import App from './App.vue'
//第一步:引入vue-resource插件
import VueResource from 'vue-resource'

Vue.config.productionTip = false

//第二步:声明使用插件——内部会给vm对象和组件对象添加一个属性:$http,有get和set两个方法
Vue.use(VueResource)

/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
App.vue

<template>
<div v-if="!repoUrl">loading</div>
<div v-else>most star repo is  <a :href="repoUrl">{{repoName}}</a></div>
</template>
<script>
export default {
data(){
return{
repoUrl:'',
repoName:''
}
},
mounted(){
//第三步:发送Ajax请求
const url = `https://api.github.com/search/repositories?q=v&sort=stars`
this.$http.get(url).then(
response=>{
const result=response.data
const mostRepo=result.items[0]
this.repoUrl=mostRepo.html_url
this.repoName=mostRepo.name
},
response=>{
alert("请求失败")
}
)
}
}
</script>

axios

npm install axios --save

App.vue

<template>
<div v-if="!repoUrl">loading</div>
<div v-else>most star repo is  <a :href="repoUrl">{{repoName}}</a></div>
</template>

<script>
//第一步:引入axios
import axios from 'axios'
export default {
data(){
return{
repoUrl:'',
repoName:''
}
},
mounted(){
//第二步:发送Ajax请求
const url = `https://api.github.com/search/repositories?q=v&sort=stars`
axios.get(url).then(response=>{
const result=response.data
const mostRepo=result.items[0]
this.repoUrl=mostRepo.html_url
this.repoName=mostRepo.name
}).catch(error=>{
alert("请求失败")
})
}
}
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: