Heim  >  Artikel  >  Web-Frontend  >  Analyse von VueJs zum Erstellen des Axios-Schnittstellenanfragetools

Analyse von VueJs zum Erstellen des Axios-Schnittstellenanfragetools

小云云
小云云Original
2017-12-18 14:51:031998Durchsuche

本文我们主要和大家分享关于VueJs 搭建Axios接口请求工具分析,axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端。今天我们来介绍VueJs 搭建Axios接口请求工具,需要的朋友参考下本文吧,希望能帮助到大家。

axios 简介

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  1. 从浏览器中创建 XMLHttpRequest

  2. 从 node.js 发出 http 请求

  3. 支持 Promise API

  4. 拦截请求和响应

  5. 转换请求和响应数据

  6. 取消请求

  7. 自动转换JSON数据

  8. 客户端支持防止 CSRF/XSRF

上一章,我们认识了项目的目录结构,以及对项目的目录结构做了一些调整,已经能把项目重新跑起来了。今天我们来搭建api接口调用工具Axios。Vue本身是不支持ajax调用的,如果你需要这些功能就需要安装对应的工具。

支持ajax请求的工具很多,像superagent和axios。今天我们用的就是axios,因为听说最近网上大部分的教程书籍都使用的是axios,本身axios这个工具就已经做了很好的优化和封装,但是在使用时,还是比较繁琐,所以我们来重新封装一下。

安装Axios工具

cnpm install axios -D 

在安装的时候,一定要切换进入咱们的项目根目录,再运行安装命令,然后如提示以上信息,则表示安装完成。

封装Axios工具

编辑src/api/index.js文件(我们在上一章整理目录结构时,在src/api/目录新建了一个空的index.js文件),现在我们为该文件填写内容。

// 配置API接口地址
var root = 'https://cnodejs.org/api/v1'
// 引用axios
var axios = require('axios')
// 自定义判断元素类型JS
function toType (obj) {
 return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
 for (var key in o) {
  if (o[key] === null) {
   delete o[key]
  }
  if (toType(o[key]) === 'string') {
   o[key] = o[key].trim()
  } else if (toType(o[key]) === 'object') {
   o[key] = filterNull(o[key])
  } else if (toType(o[key]) === 'array') {
   o[key] = filterNull(o[key])
  }
 }
 return o
}
/*
 接口处理函数
 这个函数每个项目都是不一样的,我现在调整的是适用于
 https://cnodejs.org/api/v1 的接口,如果是其他接口
 需要根据接口的参数进行调整。参考说明文档地址:
 https://cnodejs.org/topic/5378720ed6e2d16149fa16bd
 主要是,不同的接口的成功标识和失败提示是不一致的。
 另外,不同的项目的处理方法也是不一致的,这里出错就是简单的alert
*/
function apiAxios (method, url, params, success, failure) {
 if (params) {
  params = filterNull(params)
 }
 axios({
  method: method,
  url: url,
  data: method === 'POST' || method === 'PUT' ? params : null,
  params: method === 'GET' || method === 'DELETE' ? params : null,
  baseURL: root,
  withCredentials: false
 })
 .then(function (res) {
 if (res.data.success === true) {
  if (success) {
   success(res.data)
  }
 } else {
  if (failure) {
   failure(res.data)
  } else {
   window.alert('error: ' + JSON.stringify(res.data))
  }
 }
 })
 .catch(function (err) {
  let res = err.response
  if (err) {
   window.alert('api error, HTTP CODE: ' + res.status)
  }
 })
}
// 返回在vue模板中的调用接口
export default {
 get: function (url, params, success, failure) {
  return apiAxios('GET', url, params, success, failure)
 },
 post: function (url, params, success, failure) {
  return apiAxios('POST', url, params, success, failure)
 },
 put: function (url, params, success, failure) {
  return apiAxios('PUT', url, params, success, failure)
 },
 delete: function (url, params, success, failure) {
  return apiAxios('DELETE', url, params, success, failure)
 }
}

配置Axios工具

我们在使用之前,需要在src/main.js中进行简单的配置,先来看一下原始的main.js文件

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
 new Vue({
 el: '#app',
 router,
 template: &#39;<App/>&#39;,
 components: { App }
})

修改为:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from &#39;vue&#39;
import App from &#39;./App&#39;
import router from &#39;./router&#39;
// 引用API文件
import api from &#39;./api/index.js&#39;
// 将API方法绑定到全局
Vue.prototype.$api = api
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
 el: &#39;#app&#39;,
 router,
 template: &#39;<App/>&#39;,
 components: { App }
})

通过以上的配置,我们就可以在项目中使用axios工具了,接下来我们来测试一下这个工具。

使用Axios工具

我们来修改一下 src/page/Index.vue 文件,将代码调整为以下代码:

<template>
 <p>index page</p>
</template>
<script>
export default {
 created () {
  this.$api.get(&#39;topics&#39;, null, r => {
   console.log(r)
  })
 }
}
</script>

我们在Index.vue中向浏览器的控制台输入一些接口请求到的数据,如果你和我也一样,那说明我们的接口配置完成正确。如下图:

如果你是按我的操作一步一步来,那最终结果应该和我一样。如果出错请仔细检查代码。

相关推荐:

Vuejs使用 vue-markdown 来渲染评论方法

关于Vuejs技术栈的知识汇总

VueJS全面解析

Das obige ist der detaillierte Inhalt vonAnalyse von VueJs zum Erstellen des Axios-Schnittstellenanfragetools. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn