This article brings you an introduction to the use of ajax-plus (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
ajax-plus
Vue plug-in based on axios
How to use
npm module introduction
First install through npm
npm install --save ajax-plus or yarn add ajax-plus -S
Then introduce and configure in the entry file:
Configuration for axios, see axios
import Vue from 'Vue' // 引入 import ajaxPlus from 'ajax-plus' // 配置 Vue.use(ajaxPlus, { //这里写一些ajax的option,详见axios文档,比如 baseURL: "https://jsonplaceholder.typicode.com", timeout: 150000 })
Example
$ajaxPlus method
The $ajaxPlus method is added to the Vue component and is used as follows:
// method可以为 get、delete、options、post、put、patch、head // url为去除baseUrl的 // data为object this.$ajaxPlus(method, url, data, res =>{ //success call back code }) //也可以省略data参数,直接写callback(鉴于有些请求不需要传参数) this.$ajaxPlus(method, url, res =>{ //success call back code }) //$ajaxPlus已经在源码中处理catch容错了,假若想在代码里处理报错,再加一个参数,如下 this.$ajaxPlus(method, url, data, res =>{ //success call back code },{ //catch是ajax请求失败后 要执行的代码 //finallyCb是ajax请求结束后 要执行的代码,无论成功或者失败 catchCb:()=>{//code} finallyCb:()=>{//code} })
The above catchCb and finallyCb are rarely used
ajax-plus A loading variable is given to the vue global mixin, which will be automatically set to false after the ajax request is completed. With this variable, you can make some UI layers, such as the button's high-frequency prevention function
Vue.mixin({ data () { return { loading: false } } })
If you still want to do it Other related operations can be written in finallyCb
.
For example,
<el-button :loading="loading1" @click="handleSubmit">按钮1</el-button>
handleSubmit(){ this.$ajaxPlus('post','/submit',{foo:1, bar:2}, res=>{ alert('提交成功了') },{ catchCb:()=>{ alert('提交失败了') }, finallyCb:()=>{ //按钮置为可点击状态 this.loading1 = false; } }) }
$ajax
You can also use all apis of axios through this.$axios The method is as follows:
this.$ajax.get(url, data).then(res =>{ //拿到res了 }) this.$ajax.post(url, data).then( res =>{ //拿到res了 }) try { const data = await this.$ajax.post(url, data) } catch (error) { }
Due to the inconsistency in the front-end and back-end conventions, the deeper processing of callback is not perfect.
Axios can be more powerful when combined with router and vuex. For example, the interceptor determines whether to log in based on status. User authentication can be combined with the store. The combination of response-related errors and related UI Diag and Message will be more powerful. Great.
The above is the detailed content of Introduction to how to use ajax-plus (code). For more information, please follow other related articles on the PHP Chinese website!