Vue's Axios use

Source: Internet
Author: User

Axios is the plugin for the Vue request data that appears after Vue-resource. After Vue was updated to 2.0, the author Yuda announced that it was no longer a vue-resource update, but a recommended axios.

Now let's use Axios.

NPM Install Axios--save-dev
Import Axios from "Axios"

At this point, if the Axios command cannot be used in other components. But if Axios is rewritten as the prototype property of Vue, this problem can be solved

1.    Vue.prototype. $ajax =axios

There seems to be another way of not having to modify the Vue prototype, which is that we install a vue-axios in addition to the NPM installation Axios dependency.

NPM Install Vue-axios--save-dev
Import Vueaxios from "Vue-axios"

I used the first method, this has not been tried, interested in everyone can try.

After you add these two lines of code in Main.js, you can use the $ajax command directly in the component's methods

Methods: {  SubmitForm () {this    . $ajax ({      method: ' Post ',      URL: ' Your request URL ',      data: {        name: ' Haha ', '}}   }

The above only writes a callback that initiates the request and does not request a return data.

. Then (function (res) {  console.log (res)}). catch (function (err) {  console.log (err)})

This is the callback function for Axios,. Then is the callback function that requested the success, and the. Catch is a callback function that failed the request

Both of these callback functions have their own separate scopes, if you access this directly inside, can not access to the Vue instance, how to do????

Just add a . Bind (this) to solve this problem

. Then (function (res) {  console.log (this.data)}.bind (this))

Like this, so .... And this ...

Vue's Axios use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.