


Detailed example of how Vue2 configures the Axios api interface to call files
Vue itself does not support ajax interface requests, so we need to install an npm package for interface requests to enable our project to have this function. This article mainly introduces the method of Vue2 configuring the Axios api interface to call files. The editor thinks it is quite good, so I will share it with you now and give it as a reference.
This is actually an important Unix idea, that is, a tool can only do one thing well. When you need additional functions, you need to install the corresponding software to execute it. If you have been a heavy user of jquery before, you may need to understand this idea in depth.
There are many tools that support ajax. Initially, I used the superagent tool. But I found that in the past year, most of the tutorials used the axios interface request tool. In fact, there is no difference at all. But in order to prevent you from having conflicts of ideas after reading my blog post and other articles. Therefore, I switched to the tool axios.
In itself, the tool axios has been well optimized and encapsulated. However, it is still a bit cumbersome to use, so I repackaged it. Of course, more importantly, the tool axios is encapsulated for compatibility with the code I wrote before. However, I packaged it very well and recommend it to everyone.
Encapsulate the axios tool and edit the src/api/index.js file
First of all, if we want to use the axios tool, we must first install the axios tool. Execute the following command to install
npm install axios -D
Due to the poor conditions for overcoming the wall in the dormitory, cnpm is used instead
In this way, we have installed the axios tool.
Do you still remember the system structure we organized in the third blog post? We created a new empty text file src/api/index.js and left it there. Here, we fill in the content for it.
// 配置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) } }
Okay, after we write this file, save it.
Added on October 20, 2017, deleted the return that someone reported in the comments would be wrong. Indeed, this return has no effect. But I really didn't make any mistakes here. It doesn't matter, it's useless in the first place, it's just a bad habit code from the past.
For more information about axios, please refer to the official github: https://github.com/mzabriskie/axios, and Chinese information is available on Baidu.
But that’s it, we can’t use this tool in the vue template file yet, and we need to adjust the main.js file.
Adjust main.js to bind api/index.js file
This time, we did not adjust the main.js file first because the original file was configured It's better, I didn't deliberately want to adjust it.
The original file is as follows:
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: '<App/>', components: { App } })
We insert the following code:
// 引用API文件 import api from './api/index.js' // 将API方法绑定到全局 Vue.prototype.$api = api 也就是讲代码调整为: import Vue from 'vue' import App from './App' import router from './router' // 引用API文件 import api from './api/index.js' // 将API方法绑定到全局 Vue.prototype.$api = api Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } })
Okay, In this way, we can use our encapsulated api interface to call files in the project.
Test and see if it can be adjusted
Let’s modify the src/page/index.vue file and adjust the code to the following code:
<template> <p>index page</p> </template> <script> export default { created () { this.$api.get('topics', null, r => { console.log(r) }) } } </script>
Okay, here is calling the topics list interface of cnodejs.org and printing the results.
Let’s open the console in the browser and see if there is any output similar to the picture below under the console. If there is, it means that our interface configuration has been successful.
cnodejs.org Interface Data Demonstration
Okay, if you operate it correctly and there is no format error in the code, then the result you should get now is the same as mine. of. If something goes wrong or something else, please check the code carefully to see if there is any problem.
Related recommendations:
The most complete usage of Vue.js
The most detailed vue.js installation tutorial
Detailed explanation of the construction, packaging and publishing of vue project
The above is the detailed content of Detailed example of how Vue2 configures the Axios api interface to call files. For more information, please follow other related articles on the PHP Chinese website!

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.