一、vue-resource
vue 插件,非官方库,vue1.x 使用广泛。返回的是一个Promise。
文档:https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
下载:npm install vue-resource --save
1、在main.js中声明使用vue-resource
import VueResource from 'vue-resource'
// 声明使用组件
Vue.use(VueResource) // 内部会给vm对象和组件对象添加一个属性:$http
2、在组件中使用vue-resource
mounted () {
//发ajax请求获取数据
const url = `https://api.github.com/search/repositories?q=v&sort=stars`
this.$http.get(url).then(
response => {
const result = response.data
//得到第一个repo
const mostRepo = result.items[0]
this.repoUrl = mostRepo.html_url
this.repoName = mostRepo.name
},
reponse => {
alert("http请求失败!")
}
)
}
二、axios
通用的 ajax 请求库,官方推荐,vue2.x 使用广泛。
文档:https://www.kancloud.cn/yunye/axios/234845
下载:npm install axios --save
import axios from 'axios' //在哪使用就在那引入即可
mounted () {
//使用axios发送ajax请求
axios.get(url).then( response => {
const result = response.data
//得到第一个repo
const mostRepo = result.items[0]
this.repoUrl = mostRepo.html_url
this.repoName = mostRepo.name
}).catch(error => {
alert("axios请求失败!")
})
}