一.介绍
vue有两个ajax库,vue-resource(vue 1.x)和axios(vue 2.x),官方推荐使用axios
二.安装
vue-resource:npm install vue-resource --save
axios:npm install axios --save
三.使用
vue-resource请求数据
安装完成后在main.js中引入并声明使用,内部会给vm对象和组件对象添加一个属性$http
import VueResource from 'vue-resource'
//声明使用插件
Vue.use(VueResource)//内部会给vm对象和组件对象添加一个属性$http
我们做一个请求搜索热度最高的关键字例子,并获取它的name和url
<div>
<div v-if="!repoUrl">loading</div>
<div v-else>most star repo is <a :href="repoUrl">{{repoName}}</a></div>
</div>
data () {
return {
repoUrl: '',
repoName: ''
}
}
先定义一个url用于搜索关键字,发送get请求,成功则获取repoName ,repoUrl
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
},
response => {
alert('失败了')
}
)
}
axios请求数据
在哪用就在哪里引入,写法更简洁
import axios from 'axios'
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('请求失败')
})
请求前
请求后