Home >Web Front-end >Vue.js >How to use ajax in vue
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 resourcespost()
:Create resourcesput()
:Update resourcesdelete()
: Delete resourcesFor 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:
axios.defaults.headers
Object. axios.defaults.baseURL
option. axios.defaults.timeout
option. Handling the response
After making an AJAX request, the response can be accessed using the following properties:
response. data
:Response dataresponse.status
:HTTP status coderesponse.headers
:Response headersError 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!