we will learn how to send HTTP requests using Axios in Vue js. we will send a post requests with parameters as array or form data in vue cli npm app. here will be a simple example of Axios post request in Vue js app from scratch.
Step 1:
Create Vue JS App
vue create my-app
Step 2:
Install vue-axios package
npm install --save axios vue-axios
Step 3:
Use vue-js-toggle-button src/main.js
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
Step 4:
Update HelloWorld Component src/components/HelloWorld.vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Vue Axios Post - rathorji.in</div>
<div class="card-body">
<form @submit="formSubmit">
<strong>Name:</strong>
<input type="text" class="form-control" v-model="name">
<strong>Description:</strong>
<textarea class="form-control" v-model="description"></textarea>
<button class="btn btn-success">Submit</button>
</form>
<strong>Output:</strong>
<pre>
{{output}}
</pre>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log('Component mounted.')
},
data() {
return {
name: '',
description: '',
output: ''
};
},
methods: {
formSubmit(e) {
e.preventDefault();
let currentObj = this;
this.axios.post('http://localhost:8000/yourPostApi', {
name: this.name,
description: this.description
})
.then(function (response) {
currentObj.output = response.data;
})
.catch(function (error) {
currentObj.output = error;
});
}
}
}
</script>
Now you can run this example.