Vue_Ajax
vue-resource要在main中声明
//在入口文件引入 就是main.js中
import VueResource from 'vue-resource'
//声明使用插件
//内部会给vm对象和组件对象添加一个属性:$http 里面有两个方法get post
Vue.use(VueResource)
<template>
<div>
<div v-if="!repoUrl">loading</div>
<div v-else>most star repo is <a :href="repoUrl">{{repoName}}</a></div>
</div>
</template>
<script>
//axios在当前声明就行
import axios from 'axios'
export default {
data(){
return{
repoName:'',
repoUrl:''
}
},
mounted() {
// 发异步请求获取数据
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('请求失败')
//
// }
// )
//使用axios发送ajax请求
//这里奇怪为什么response为什么不是data
// 第一步的response里面是成功的信息再then才能返回我们要的数据
axios.get(url).then(
response => {
//成功了
console.log(response)
const result = response.data
//得到最受欢迎的repo
const mostRepo = result.items[0]
this.repoUrl = mostRepo.html_url
this.repoName = mostRepo.name
}).catch(error => {
alert('请求失败22')
})
}
}
</script>
<style scoped>
</style>
this.$http.get(url)编码风格Promise,返回的就是一个Promise
response的值,可以看出data