Vue的学习(10)Vue_Ajax

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
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值