【Vue】vue-ajax-resource-axios简单使用

1. vue 项目中常用的2 个ajax 库

vue-resource

vue 插件, 非官方库, vue1.x 使用广泛

axios

通用的ajax 请求库, 官方推荐, vue2.x 使用广泛

2. vue-resource 的使用(不是重点,了解即可)

在线文档
https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
下载

npm install vue-resource --save

在这里插入图片描述
示例代码

// 引入模块
import VueResource from 'vue-resource'
// 使用插件
Vue.use(VueResource)
// 通过vue/组件对象发送ajax 请求
this.$http.get('/someUrl')
.then((response) => {
    
    
	// success callback
	console.log(response.data) //返回结果数据
}, (response) => {
    
    
	// error callback
	console.log(response.statusText) //错误信息
})

示例

main.js

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

// 声明使用插件
Vue.use(VueResource) // 内部会给vm对象和组件对象添加一个属性: $http

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

App.vue

<template>
  <div>
    <div v-if="!repoUrl">loading</div>
    <div v-else>
      most star repo is <a :href="repoUrl">{
   
   { repoName }}</a>
    </div>
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      repoUrl: "",
      repoName: "",
    };
  },
  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("请求失败");
      }
    );
  },
};
</script>

<style>
</style>

3. axios 的使用(重点)

在线文档
https://github.com/pagekit/vue-resource/blob/develop/docs/http.md
下载

npm install axios --save

在这里插入图片描述

// 引入模块
import axios from 'axios'
// 发送ajax 请求
axios.get(url)
.then(response => {
    
    
	console.log(response.data) // 得到返回结果数据
})
.catch(error => {
    
    
	console.log(error.message)
})

示例

App.vue

<script>
import axios from 'axios';
export default {
     
     
  data() {
     
     
    return {
     
     
      repoUrl: "",
      repoName: "",
    };
  },
  mounted() {
     
     
    // 发ajax请求获取数据
    const url = "https://api.github.com/search/repositories?q=v&sort=stars";
    // 使用axios发送ajax请求
    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("请求失败");
      });
  },
};
</script>

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44972008/article/details/113921303