VUE-ajax请求

一、VUE-ajax请求

  1. 在声明周期回调函数中发送请求:mounted(){}
  2. 使用vue-resource库或者axios来发送ajax请求去获取数据
  3. 安装vue-resource:npm install vue-resource --save
  4. 安装:axios:npm install axios --save
  5. 在main.js引入插件vue-resource:import VueResource from 'vue-resource'
  6. 在main.js声明使用插件:Vue.use(VueResource)
  7. 在需要使用的组件中引入axios:import axios from 'axios'

(1)发送ajax请求:vue-resource

  1. 当引入和声明插件后,内部会给vm对象和组件对象添加一个属性:$http。这个属性有get()post()方法。
  2. 开始调用this.$http.get(url)返回的是一个promise对象,可以调用then()方法。
<div>
  <p v-if="!nUrl">加载中。。。</p>
  <p v-else>点击这个星最多的<a :href="nUrl">{{name}}</a></p>
</div>

 mounted() {
     //发送ajax请求,查找星最多的
       const url='http://api.github.com/search/repositories?q=v&sort=star'
       this.$http.get(url).then((response) => {
       const result=response.data//data是返回查找的内容中的数据
       const mostRepo=result.items[0]//查找结果中排第一的笔记
       this.nUrl=mostRepo.html_url//将笔记地址赋值给nUrl
       this.name=mostRepo.name
    },(response) => {
        alert('请求失败')
     })

(2)发送ajax请求:axios

 axios.get(url).then((response) => {
        const result=response.data//data是返回查找的内容中的数据
        const mostRepo=result.items[0]//查找结果中排第一的笔记
        this.nUrl=mostRepo.html_url//将笔记地址赋值给nUrl
        this.name=mostRepo.name
     }).catch(error => {
         alert('请求失败11')
     })

二、实例:

要求:在搜索框输入,点击搜索,显示用户。有四个状态:
(1)开始搜索前firstView
(2)请求中loading
(3)请求之后的返回结果:成功状态
(4)失败状态errorMsg
App.vue

<template>
<div>
<div class="container">
      <Search></Search>
      <user-main></user-main>
  </div>
</div>
</template>
<script>
import Search from './components/search.vue'
import Main from './components/main.vue'

export default{
  components: { //直接写Main会有冲突
    Search, 
    UserMain :Main
    }

search.vue

<template>
<div>
    <section class="jumbotron">
      <h3 class="jumbotron-heading">Search Github Users</h3>
      <div>
        <input type="text" placeholder="enter the name you search" v-model="searchName"/>
        <button @click="search">Search</button>
      </div>
    </section>
</div>
</template>
<script>
import Pubsub from 'pubsub-js'
export default{//向外默认暴露一个配置对象
 data() {
     return {
         searchName:''
     }
 },
 methods: {
     search(){
         const searchName=this.searchName.trim();
         if(searchName){
             //有值就开始搜索了------发布搜索的消息----search是消息名
             Pubsub.publish('search',searchName)
         }
     }
 }
}
</script>
<style>
</style>

main.vue

<template>
<div>
   <h2 v-if="firstView">输入用户名进行搜索</h2>
   <h2 v-if="loading">loading......</h2>
   <h2 v-if="errorMsg">{{errorMsg}}</h2>
     <div class="row">
      <div class="card" v-for="(user,index) in users" :key="index">
        <a :href="user.url" target="_blank">
          <img :src="user.image" style='width: 100px'/>
        </a>
        <p class="card-text">{{user.name}}</p>
      </div>
    </div>
</div>
</template>
<script>
import Pubsub from 'pubsub-js'
import axios from 'axios'
export default{//向外默认暴露一个配置对象
data() {
    return {
        firstView:true,//开始状态
        loading:false,//加载中userImage
        users:[],//搜索成功后的用户[{url:'',image:'',name:''}]
        errorMsg:''//失败信息

        }
},
mounted() {//一开始就应该订阅搜索的消息
Pubsub.subscribe('search',(msg,searchName) => {
    //const url='https://api.github.com/search/users?q=${searchName}'
      const url = `https://api.github.com/search/users?q=${searchName}`
         this.firstView=false//改变状态
         this.loading=true//开始加载中
         this.users=[]
         this.errorMsg=''
        
        //说明此时需要发ajax请求进行搜索了
       
         axios.get(url).then((response) => {//axios来发送ajax请求,使用get方法,是一个Promise对象,response来保存axios.get(url)请求成功的结果
               const result=response.data
               const users=result.items.map(item => ({//解决名字和数据中的名字不一致的问题,用map方法
               url:item.html_url,
               image:item.avatar_url,
               name:item.login
         }))
         
              //搜索成功,更新状态
                this.loading=false
                this.users=users
         }).catch(error => {
              //搜索失败,更新状态
               this.loading=false
               this.errorMsg="请求失败"
         })         
})   
}
}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值