Home >Web Front-end >Vue.js >How to use ajax in vue

How to use ajax in vue

下次还敢
下次还敢Original
2024-05-08 15:12:18867browse

Using AJAX in Vue

Using AJAX in Vue.js is very simple, you can use the axios library.

Install Axios

You can install Axios through the following command:

<code>npm install axios --save</code>

Import Axios

In Vue Import Axios into the component:

<code class="javascript">import axios from 'axios';</code>

Initiate an AJAX request

To use Axios to initiate an AJAX request, you can use the following methods:

  • get():Get resources
  • post():Create resources
  • put():Update resources
  • delete(): Delete resources

For example, to use the get() method to obtain resources, you can write like this:

<code class="javascript">axios.get('/api/data')
  .then(response => {
    // 请求成功时执行此函数
    console.log(response.data);
  })
  .catch(error => {
    // 请求失败时执行此函数
    console.error(error);
  });</code>

Configuring Axios

You can configure Axios in the following ways:

  • Set the default request headers: Use axios.defaults.headers Object.
  • Set the default baseURL: Use the axios.defaults.baseURL option.
  • Set the timeout: Use the axios.defaults.timeout option.

Handling the response

After making an AJAX request, the response can be accessed using the following properties:

  • response. data:Response data
  • response.status:HTTP status code
  • response.headers:Response headers

Error handling

If the request fails, you can use the catch() method to handle the error:

<code class="javascript">axios.get('/api/data')
  .then(response => {
    // 请求成功时执行此函数
    console.log(response.data);
  })
  .catch(error => {
    // 请求失败时执行此函数
    console.error(error.response.data);
  });</code>

The above is the detailed content of How to use ajax in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn