Vue之关于ajax

使用ajva发送请求可以有效和后台进行数据交互处理,对于Vue来说,常用的有两个ajax库,分别是:vue-resource,axios

一、vue-resource

vue-resource是一个vue插件,非官方库,在vue1.x中使用广泛,目前使用较少,在使用这个方式进行ajax编码:
1、首先用命令下载vue-resource资源,打开命令窗口,输入:npm install vue-resource --save
2、在vue的js入口文件中引入模块,并使用这个插件,在引入模块后,默认会带有属性$http.get/post用于发送不同请求:

import Vue from 'vue'
import App from './App'
import VueResource from 'vue-resource'

//引入vue-resource插件
Vue.use(VueResource)   //默认会添加$http属性
/* eslint-disable no-new */
var vue = new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

3、完成上面两步后就可以通过vue/组件对象发送ajax请求了,如,将请求数据searchName,searchUrl在页面中显示出来:

mounted() {
    /*ajax请求1:vue-resource*/
    var url = 'https://api.github.com/search/repositories?q=v&sort=stars'
    this.$http.get(url).then(
      //请求成功的回调函数
      (response) => {
        console.log(response)
        this.searchName = response.data.items[0].name
        this.searchUrl = response.data.items[0].html_url
      } ,
      //请求失败的回调函数
      (response) =>{
         console.log('ajax-resource请求失败')
      }
    )
  }

二、axios

axios也可实现ajax请求,在vue中,axios是一个资源请求库,是官方推荐使用的资源库,在vue2.x中使用广泛,目前很多vue开发项目都是用这种ajax请求方法。使用此种方式进行ajax编码:
1、首先要在命令窗口输入:npm install axios --save 下载axios资源。
2、在你需要发送ajax请求编码的组件页面引入axios模块,并进行发送ajax请求编码。如:

//导入axios库
import axios from 'axios'
 mounted() {
    /*ajax请求2:axios请求*/
    var url2 = 'https://api.github.com/search/users?q=aa'
    axios.get(url2).then(response => {
      //请求成功回调函数
      console.log(response)
      this.searchName2 = response.data.items[0].login
      this.searchUrl2 = response.data.items[0].html_url
    }).catch(error => {
      //请求失败回调函数
       console.log('axios请求失败')
      console.log(error)
    })
  }

一个使用axios发请求和PubSubJs通信编码的小案例:
在这里插入图片描述
main.js

//入口js文件,实例化一个vue
import Vue from "vue";
import App from "./App";

var vue = new Vue({
  el:'#app',
  components:{
    App
  },
  template:"<App />"
})

App.vue

<template>
  <div class="container">
    <Header />
    <Main />
  </div>
</template>

<script>
  import Header from "./components/Header";
  import Main from "./components/Main";
  export default {
    name: "App",
    components:{
      Header,
      Main
    }
  }
</script>

<style scoped>
</style>

Header.vue

<template>
  <div class="jumbotron">
    <h1>Search Github Users</h1>
    <input type="text" placeholder="enter the name your search" v-model="searchName">
    <button @click="search">Search</button>
  </div>
</template>

<script>
  import PubSub from 'pubsub-js'
  export default {
    name: "Header" ,
    data(){
      return{
        searchName:''
      }
    },
    methods:{
      search:function () {
        //发布消息
        PubSub.publish('search',this.searchName)
      }
    }
  }
</script>

<style scoped>

</style>

Main.vue

<template>
  <div class="container">
    <h3 v-if="initText">输入用户名搜索</h3>
    <h3 v-if="loading">搜索中……</h3>
    <h3 v-if="errorMsg" >数据请求失败</h3>
    <ul class="list-inline listUl">
      <li class="listItem col-md-4" v-for="(item,index) in successMsg" :key="index" >
        <a :href="item.html_url"  class="listA">
          <img :src="item.avatar_url"  alt="avatar" style="height: 100px;width: 100px">
        </a>
        <p class="listLable">{{item.login}}</p>
      </li>
    </ul>
  </div>
</template>

<script>
   import PubSub from 'pubsub-js'
   import axios from 'axios'
  export default {
    name: "Main",
    data(){
      return {
        initText:true,
        loading:false,
        errorMsg:false,
        successMsg:[]
      }
    },
    mounted() {
      //在search之后,发送请求,订阅消息
      PubSub.subscribe('search',(msg,searchName) => {
        this.initText = false
        this.loading = true
        var url = 'https://api.github.com/search/users?q=' + searchName
        console.log(url)
        axios.get(url).then((respons) => {
          //console.log('请求 成功')
          //console.log(respons.data.items)
          this.initText = false
          this.loading = false
          //直接将获取到的数组元素赋值给successMsg
          //this.successMsg = respons.data.items
          //console.log(this.successMsg)

          //将获取到的数组元素选择性的将需要的元素值赋值给successMsg
          var success = respons.data.items.map((item) => ({
            html_url:item.html_url,
            avatar_url:item.avatar_url,
            login:item.login
          }))
          console.log(success)
          this.successMsg = success

        }).catch(error => {
          console.log('请求错误')
          this.initText = false
          this.loading = false
          this.successMsg = []
          this.errorMsg = true
        })
      })
    }
  }
</script>

<style scoped>
.listUl{
  width: 98%;
}
.listItem{
  height: 160px;
  border:1px solid lightgray;
  float: left;
  border-radius: 2px;
  text-align: center;
  margin-bottom: 25px;
}
.listA{
  display: block;
  width: 100px;
  height: 100px;
  margin: auto;
  margin-top: 20px;
}
</style>

在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值