In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "how Vuejs requests data through Axios". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "Vuejs how to request data through Axios" can help you solve your doubts.
Request data through Axios
Let's build the api API invocation tool Axios. Vue itself does not support ajax calls, if you need these features, you need to install the corresponding tools.
There are many tools that support ajax requests, such as superagent and axios. What we use today is axios, because I heard that most of the tutorial books on the Internet recently use axios, and axios itself has been well optimized and encapsulated, but when using it, it is still quite cumbersome, so let's re-package it.
Install Axios tool cnpm install axios-D
During installation, be sure to change to our project root directory, then run the installation command, and then if prompted by the above information, the installation is complete.
Encapsulate the Axios tool
Edit the src/api/index.js file (we created an empty index.js file in the src/api/ directory when we organized the directory structure in the previous chapter), and now let's fill in the contents for that file.
/ / configure API interface address var root = 'https://cnodejs.org/api/v1'// reference axiosvar axios = require (' axios') / / Custom determine element type JSfunction toType (obj) {return ({}) .toString.call (obj). Match (/\ s ([a-zA-Z] +) /) [1] .toLowerCase ()} / / Parameter filter function 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 (okey]) } else if (toType (o [key]) = = 'array') {o [key] = filterNull (o [key])}} return o} / * Interface handler function this function is different from project to project. What I am adjusting now is the interface suitable for https://cnodejs.org/api/v1. If it is another interface, it needs to be adjusted according to the parameters of the interface. The address of the reference document: https://cnodejs.org/topic/5378720ed6e2d16149fa16bd is mainly that the success identification and failure prompt of different interfaces are inconsistent. In addition, different projects are handled differently. The error here is simple 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)}})} / / returns the calling interface 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)} in the vue template, 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)}}
For more explanation of AxIos, see: https://github.com/mzabriskie/axios
Configure the Axios tool
Before we use it, we need to make a simple configuration in src/main.js. Let's take a look at the original main.js file.
/ / 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:', components: {App}})
Modified to:
/ / 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' / / reference the API file import api from'. / api/index.js'// to bind the API method to the global Vue.prototype.$api = api Vue.config.productionTip = false / * eslint-disable no-new * / new Vue ({el:'# app', router Template:'', components: {App}})
With the above configuration, we can use the axios tool in the project, and then let's test this tool.
Use the Axios tool
Let's modify the src/page/Index.vue file and adjust the code to the following code:
Index pageexport default {created () {this.$api.get ('topics', null, r = > {console.log (r)})}}
We enter some data requested by the interface into the browser console in Index.vue. If you and I are the same, it means that our interface configuration is correct. As shown below:
If you follow my operation step by step, then the final result should be the same as mine. If something goes wrong, please check the code carefully.
Vue request data (axios) what is axios
Axios is a Promise-based HTTP library that can be used in browsers and node.js.
Vue.js version 2.0 recommends using axios to complete the ajax request.
Introduce
There is no need to worry about the order of vue when it is introduced, it does not depend on vue
Usage
1.get request
There is only one parameter in get, which includes the previous address, and the later parameter is passed with "?" Splice after the address
Created () {axios .get ("http://wkt.myhope365.com/weChat/applet/course/banner/list?number=4") .then (res) = > {console.log (res); this.imgList = res.data.data;});}
2.post request (form format)
You need to define a form to put the parameters you want to pass in.
There are two parameters: request address, form
Created () {let from = new FormData (); from.append ("type", "boutique"); from.append ("pageNum", 2); from.append ("pageSize", 10) Axios .post ("http://wkt.myhope365.com/weChat/applet/course/list/type", from) .then ((res) = > {console.log (res); this.courseList = res.data.rows; / / console.log (this.courseList);});}
3.post request (JOSN format)
In this case, there are two parameters: request address, {passed parameter}
The transferable parameters should be in the format of JOSN
Created () {axios .post ("http://wkt.myhope365.com/weChat/applet/subject/list", {enable: 1,}). Then (res) = > {console.log (res); this.list = res.data.rows; console.log (this.list) (});}, reading here, the article "how to request data through Vuejs through Axios" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to learn more about related articles, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.