I have a vue component that takes care of showing all my records and make it possible to edit every record. I have 100+ records so i'm working with pagination.
problem: as example I would like to edit a record that is located on page 3 of the pagination. I can edit the record, but after the update my pagination starts at page 1 again. This happens because I'm fetching my data again after the update.
question: How can I improve my code that this doesn't happen? Do I really need to fetch my data again to display the changes?
Vue component
<template>
<div>
<h2> Quest template </h2>
<div class="container">
<div class="row">
<div class="col-md-7">
<form class="form-inline mb-3">
<input class="form-control mr-sm-2" style='width:55%;' type="search" placeholder="Search"
aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
<nav aria-label="Page navigation example">
<ul class="pagination">
<li v-bind:class="[{disabled: !pagination.prev_page_url}]" class="page-item"><a class="page-link" href="#"
#click="fetchQuests(pagination.prev_page_url)">Previous</a></li>
<li class="page-item"><a class="page-link disabled text-dark" href="#">Page {{pagination.current_page}} of {{pagination.last_page}}</a></li>
<li v-bind:class="[{disabled: !pagination.next_page_url}]" class="page-item"><a class="page-link" href="#"
#click="fetchQuests(pagination.next_page_url)"
>Next</a></li>
</ul>
</nav>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="quest in quests" v-bind:key="quest.id">
<th scope="row">{{quest.id}}</th>
<td>{{quest.name}}</td>
<td>No price set</td>
<td><a #click="editQuest(quest)" href="#" class=" btn btn-outline-dark"> Edit</a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-4">
<h2 class="text-center">EDIT PANEL</h2>
<p class="text-center"> </p>
<form #submit.prevent="updateQuest">
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">Quest name</div>
</div>
<input type="text" class="form-control" v-model="quest.name" placeholder="" :disabled="!this.edit">
</div>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
Quest price
</div>
</div>
<input type="text" class="form-control" v-model="quest.price" placeholder="" :disabled="!this.edit">
<div class="input-group-prepend">
<div class="input-group-text">
M
</div>
</div>
</div>
</div>
<button v-bind:class="[{disabled: !this.edit}]" class="btn btn-outline-dark float-right"> Update</button>
</form>
</div>
</div>
</div>
</div>
</template>
Vue component script
<script>
export default {
data() {
return {
quests: [],
quest: {
id: '',
name: '',
price: '',
},
quest_id: '',
pagination: {},
edit: false
}
},
created() {
this.fetchQuests();
},
methods: {
fetchQuests(page_url) {
let vm = this;
page_url = page_url || '/api/quests'
fetch(page_url, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(res => {
this.quests = res.data;
vm.makePagination(res.meta, res.links);
})
.catch(error => console.log(error));
},
makePagination(meta,links) {
let pagination = {
current_page: meta.current_page,
last_page: meta.last_page,
next_page_url: links.next,
prev_page_url: links.prev,
}
this.pagination = pagination;
},
updateQuest() {
if(this.edit) {
fetch( `/api/quests/${this.quest.id}`, {
method:'put',
body: JSON.stringify(this.quest),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(data => {
this.quest.name = "";
this.quest.price = "";
this.fetchQuests();
})
.catch(error => console.log(error));
}
},
editQuest(quest) {
this.edit = true;
this.quest.id = quest.id;
this.quest.quest_id = quest.id;
this.quest.name = quest.name;
this.quest.price = quest.price;
}
}
}
</script>
This question is vague. And if you wrote this yourself, you're obviously not a noob, so I'm gonna keep this simple. Why not just reload the current page? Keep a track of the current page in a data variable and when you make an update, rather than loading the from the start, reload the current page url.
data: function() {
current_page_url: '/api/quests
},
methods: {
fetchQuests: function(page_url) {
let vm = this;
page_url = page_url || this.current_page_url;
this.current_page_url = page_url;
fetch(page_url, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(res => {
this.quests = res.data;
vm.makePagination(res.meta, res.links);
})
.catch(error => console.log(error));
}
}
Related
I am trying to hide a modal after submitting a form. I am using bootstrap 5, vue 2 and django 3.2. I am a beginner in javascript and vue.
I can asynchronously submit the form with fetch and clear the fields, but I can't close the modal.
I report part of my code (bootstrap and vue only) which unfortunately does not provide a minimum reproducible example, but I hope it is sufficient.
The html template is:
<div style="margin-right: 230px" id="app">
<h4 style="text-align:left;float:left;">User Managment</h4>
<a
href="#"
data-bs-toggle="modal"
data-bs-target="#add_userModal"
class="btn btn-sm btn-outline-primary px-4"
style="text-align:right; float:right;">
Add
</a>
<hr style="clear:both; border-top: 1px solid grey;"/>
<table class="table" id="userTable">
<thead>
<tr>
<th class="col-md-4">First name</th>
<th class="col-md-8">Last name</th>
</tr>
</thead>
<tbody>
<tr v-for="userdb in usersdb">
<td>{% verbatim %}{{ userdb.first_name }}{% endverbatim %}</td>
<td>{% verbatim %}{{ userdb.last_name }}{% endverbatim %}</td>
</tr>
</tbody>
</table>
<div class="modal fade" id="add_userModal" tabindex="-1" aria-labelledby="add_userModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Utente</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form #submit.prevent="createUserdb">
<div class="modal-body">
<div class="form-group mb-3">
<label>First name*</label>
<input
type="text"
class="form-control"
id="first_name"
v-model="userdb.first_name"
required>
</div>
<div class="form-group mb-3">
<label>Last name*</label>
<input
type="text"
class="form-control"
id="last_name"
v-model="userdb.last_name"
required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-sm btn-outline-primary">Add</button>
</div>
</form>
</div>
</div>
</div>
</div>
The javascript code is
var app = new Vue({
el: '#app',
data: {
csrf: null,
userdb: {
first_name: '',
last_name: '',
full_name: ''},
usersdb: []
},
methods: {
async sendRequest(url, method, data) {
var myHeaders = new Headers({
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
})
if (method !== 'get') {
myHeaders.set('X-CSRFToken', await this.getCsrfToken())
};
var response = await fetch(url, {
method: method,
headers: myHeaders,
body: data
});
return response
},
async getCsrfToken() {
if (this.csrf === null) {
var response = await this.sendRequest(mainUrl + 'csrf', 'get')
var data = await response.json();
this.csrf = data.csrf_token;
};
return this.csrf;
},
async getUserdb() {
var response = await this.sendRequest(mainUrl, 'get');
this.usersdb = await response.json();
},
async createUserdb() {
await this.getUserdb();
await this.sendRequest(mainUrl, 'post', JSON.stringify(this.userdb));
this.userdb.first_name = '';
this.userdb.last_name = '';
await this.getUserdb();
}
},
async created() {
await this.getUserdb();
}
})
I made many attempts to add code in createUserdb, but without success. For example
document.getElementById("add_userModal").hide();
How can I hide the modal after submitting the form?
Any help is truly appreciated
You'll want to entirely manage the Bootstrap modal instance in the Vue app...
1 - First, add a new data var for the modal..
data: {
csrf: null,
userdb: {
first_name: '',
last_name: '',
full_name: ''},
usersdb: [],
myModal: null
},
2 - And a new method (ie: showModal()) to get an instance of the Bootstrap.modal and show it...
showModal(){
this.myModal = new bootstrap.Modal(document.getElementById('add_userModal'), {})
this.myModal.show()
},
3 - Bind the new method to #click handler to show the modal (instead of using data-bs attributes)...
<a
#click="showModal()"
class="btn btn-sm btn-outline-primary px-4"
style="text-align:right; float:right;">
Add
</a>
4 - Finally, call the hide() method after the async processing...
async createUserdb() {
await this.getUserdb();
await this.sendRequest(mainUrl, 'post', JSON.stringify(this.userdb));
this.userdb.first_name = '';
this.userdb.last_name = '';
this.myModal.hide()
}
Demo
I´m traying to send data of my array data to one modal, but always in web console i can see this message:
[Vue warn]: Property or method "nombreUsuario" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property
in my component i´m creating a modal and i thinked that i could pass this data to my modal, but i can´t.
i´m traying declare one variable in export deafult of my component, but always returned me a error.
i´m showing in internet very much examples that how to do this, but i can´t.
I appreciate all help
My actual code is:
componentVUE
<template>
<div class="tabla-usuarios">
<table class="table table-hover table-striped">
<thead>
<th>Id</th>
<th>Nombre</th>
<th>Email</th>
<th>Dirección</th>
<th>Editar</th>
</thead>
<tbody>
<tr>
<td>{{ datosUsuario.id }}</td>
<td>{{ datosUsuario.nombre }}</td>
<td>{{ datosUsuario.email }}</td>
<td>{{ datosUsuario.direccion }}</td>
<td>Editar</td>
</tr>
</tbody>
</table>
<div class="modal fade" id="create">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="nombre">Nombre:</label>
<input type="text" class="form-control" id="nombre" :nombreUsuario="nombreUsuario">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email">
</div>
<div class="form-group">
<label for="direccion">Direccion:</label>
<input type="text" class="form-control" id="direccion">
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Guardar">
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
datosUsuario: [],
isOpen: false,
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
})
.catch((error) => console.error(error));
},
},
};
</script>
The easiest way to pass information to a modal is to pass it through a function and store it in a Vue property. First, in your loop, change your button to this:
<td>Editar</td>
Then you want to add both the property and the method:
<script>
export default {
data() {
return {
datosUsuario: [],
isOpen: false,
selectedItem: {}
};
},
created: function () {
this.cargar();
},
methods: {
cargar: function () {
let url = "/getDatosPersonales";
axios
.get(url)
.then((response) => {
this.datosUsuario = response.data;
})
.catch((error) => console.error(error));
},
setSelectedItem(item) {
this.selectedItem = item;
}
},
};
</script>
Then it's real easy to get that data back into your modal:
<div class="form-group">
<label for="nombre">Nombre:</label>
<input type="text" class="form-control" id="nombre" v-model="selectedItem.nombre">
</div>
You can also use the selectedItem in other functions, such as when submitting it back to the server.
I have a Javascript function in a leaf page using Vapor 3 the function should trigger a post to an api to save a customers card detials and return a token representing that card. I would normally do this in swift on our vapor server but to be PCI complient we are not allowed to take the customers credit card detials onto our server they must go directly to Sum Up (payment provider) I have no experiance with javascript and after lots of googling this it the fucntion I came up with.
<script>
function savecard() {
var name = document.getElementById("nameonCard").value
var cardNo = document.getElementById("cardNumber").value
var expiry_year = document.getElementById("expiryMonth").value
var expiry_month = document.getElementById("expiryYear").value
var cvv = document.getElementById("cvc").value
var body = `{"type":"card","card":{"name":"${name}","number":"${cardNo}", "expiry_month": "${expiry_month}", "expiry_year": "${expiry_year}","cvv": "${cvv}"}}`
return fetch("https://api.sumup.com/v0.1/customers/" + #(sumCustId) + "/payment-instruments", {
method: "POST"
headers: {
"Authorization": "Basic " + #(auth),
"Content-Type": "application/json"
},
data: body,
})
.then(function(response){
document.getElementById("response").value = response.text()
return response.text();
})
.then(function(data){
console.log(data)//text version
var data_obj = JSON.parse(data);
document.getElementById("data_obj").value = data_obj
return data_obj
})
}
</script>
I don't appear to be getting anything back but I'm not sure where I am going wrong, any help is much appreciated.
Here is the entire leaf page.
<!doctype html>
<html lang="en">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Pay for Membership</title>
<body>
<div class="card bg-dark text-white h-100">
<img class="card-img bg-dark img-fluid" src="https://images.unsplash.com/photo-1575151772039-542722abbf63?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format" alt="Card image">
<div class="card-img-overlay">
<div class="card-deck">
<div class="card bg-transparent border-warning align-self-start ">
<div class="card-header">
<h4 class="card-title text-center">Order Summary</h4>
</div>
<div class="card-body">
<ul>
#for(sum in orderSum){
#if(isLast == false){
<li class="list-group-item bg-transparent d-flex justify-content-between align-items-centert">#noam(sum)
<span class="badge badge-info badge-pill text-right align-self-center">#am(sum)</span>
</li>
}
}
</ul>
</div>
<div class="card-footer text-center">
#for(sum in orderSum){
#if(isLast){
<h5>#(sum)</h5>
}
}
</div>
</div>
<div class="card bg-dark border-warning">
<div class="card-header">
<h4 class="card-title">Payment Details</h4>
</div>
<div class="card-body">
<form method="post" action="/completedsumupmember" id="paymentForm">
<div class="row form-group" hidden>
<input type="number" class="form-control" id="amount" name="amount" value =#(amount) hidden>
<input type="text" class="form-control" id="currency" name="currency" value =#(currency) hidden>
<input type="text" class="form-control" id="orderId" name="orderId" value =#(orderId) hidden>
<input type="text" class="form-control" id="desc" name="desc" value =#(desc) hidden>
<input type="text" class="form-control" id="type" name="type" value =#(type) hidden>
<input type="text" class="form-control" id="orgId" name="orgId" value =#(orgId) hidden>
<input type="text" class="form-control" id="payToEmail" name="payToEmail" value =#(payToEmail) hidden>
<input type="text" class="form-control" id="auth" name="auth" value =#(auth) hidden>
<input type="hidden" class="form-control" id="response" name="response" value ="" hidden>
<input type="hidden" class="form-control" id="data_obj" name="data_obj" value ="" hidden>
<input type="text" class="form-control" id="customerId" name="customerId" value =#(sumCustId) hidden>
</div>
<div class="row form-group">
<div class = "col-md">
<label for="nameonCard">Name on the Card</label>
<input type="text" class="form-control" id="nameonCard" name="nameonCard" placeholder="John Smith" required>
</div>
</div>
<div class ="row form-group">
<div class ="col-lg">
<label for="cardNumber">Card Number</label>
<input type="number" class="form-control" id="cardNumber" name="cardNumber" placeholder="1111 2222 3333 4444" required>
</div>
</div>
<div class = "row form-group">
<div class = "col-md">
<label for="expiryMonth">Expriy Month</label>
<input type="text" class="form-control" id="expiryMonth" name="expiryMonth" placeholder="mm" required>
</div>
<div class = "col-md">
<label for="expiry">Expriy Year</label>
<input type="text" class="form-control" id="expiryYear" name="expiryYear" placeholder="yy" required>
</div>
<div class = "col-md">
<label for="cvc">CVV</label>
<input type="text" class="form-control" id="cvc" name="cvc" placeholder="000" required>
</div>
</div>
<div class="card-footer text-center">
<button class="btn btn-warning btn-block" type="submit" onclick="savecard()">Pay Now</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
function savecard() {
console.log('do something ')
var name = document.getElementById("nameonCard").value
var cardNo = document.getElementById("cardNumber").value
var expiry_year = document.getElementById("expiryMonth").value
var expiry_month = document.getElementById("expiryYear").value
var cvv = document.getElementById("cvc").value
var body = `{"type":"card","card":{"name":"${name}","number":"${cardNo}", "expiry_month": "${expiry_month}", "expiry_year": "${expiry_year}","cvv": "${cvv}"}}`
return fetch("https://api.sumup.com/v0.1/customers/" + #(sumCustId) + "/payment-instruments", {
method: "POST"
headers: {
"Authorization": "Basic " + #(auth),
"Content-Type": "application/json"
},
data: body,
})
.then(function(response){
document.getElementById("response").value = response.text()
return response.text();
})
.then(function(data){
console.log(data)//text version
var data_obj = JSON.parse(data);
document.getElementById("data_obj").value = data_obj
return data_obj
})
}
</script>
</body>
</html>
I have finally managed to get a function that works, which is below.
<script>
function savecard() {
let customerId = document.getElementById("customerId").value;
let url = "https://api.sumup.com/v0.1/customers/" + customerId + "/payment-instruments"
let auth = " Basic " + document.getElementById("auth").value;
alert(auth);
let cardBody = {
type:"card",
card: {
name: document.getElementById("nameonCard").value,
cardNo: document.getElementById("cardNumber").value,
expiry_year: document.getElementById("expiryMonth").value,
expiry_month: document.getElementById("expiryYear").value,
cvv: document.getElementById("cvc").value
}
};
alert(cardBody.card.name);
let options = {
//mode: 'no-cors',
method: 'POST',
body: JSON.stringify(cardBody),
headers: {
'Content-Type': 'application/json',
'Authorization': auth
}
}
fetch(url, options)
.then(res => res.json())
.then(res => alert(res))
.catch(err => alert(`Error with message: ${err}`));;
}
</script>
However I am now getting an error in the catch
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Seems like this is a simple typo, but I've been looking at it to long to see what it is.
In the end this worked. I thin by placing it in the head of the leaf file and removing any leaf tags fixed the issues. Instead of using leaf tags I added hidden form inputs with the values set by the leaf tag then accessed that value in the function.
<script>
function savecard() {
let customerId = document.getElementById("customerId").value; // for testing hard code value in form
let url = "https://api.sumup.com/v0.1/customers/" + customerId + "/payment-instruments"
let auth = " Basic " + document.getElementById("auth").value; // for testing hard code value in form
let cardBody = {
type:"card",
card: {
name: document.getElementById("nameonCard").value,
cardNo: document.getElementById("cardNumber").value,
expiry_year: document.getElementById("expiryMonth").value,
expiry_month: document.getElementById("expiryYear").value,
cvv: document.getElementById("cvc").value
}
};
let headers = {
'Authorization': auth,
'Content-Type': 'application/json'
}
let options = {
//mode: 'no-cors',
method: 'POST',
body: JSON.stringify(cardBody), //
headers: headers
}
fetch(url, options)
.then(res => res.json())
var token = res.token
document.getElementById("token").value = token
.then(res => console.log(res))
.catch(err => alert(`Error with message: ${err}`));;
document.getElementById("paymentForm").submit()
}
</script>
Hopefully that helps someone.
I'm not getting any errors but I think I'm just missing something that I cannot see.
My API's are all working. I just wanted to be able to have a search bar to search the names and then a <select> element for searching through departments. Pretty sure my problem is something to do with the filteredList().
Employees.vue
<script>
<template>
<div class="container">
<div class="form-row align-items-center justify-content-center">
<div class="col-md-6">
<label>Name</label>
<input v-model="search" id="inputKeyword" name="inputKeyword" type="text" class="form-control mb-2 form-control-lg">
</div>
<div class="col-md-4">
<label>Department</label>
<select v-model="selectedDepartment" id="inputfilter" name="inputfilter" class="form-control mb-2 form-control-lg select-department">
<option v-for="department in departments" v-bind:key="department.name">
{{ department.name }}
</option>
</select>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-10">
<ul class="list-unstyled">
<employee v-for="employee in filteredList" :employee="employee" :key="employee.id"></employee>
</ul>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
search: '',
selectedDepartment: '',
employees: [],
meta: null,
departments: [],
}
},
computed: {
filteredList() {
if(this.selectedDepartment == this.employees.department){
return this.employees == this.employees.filter(employees => {
return employees.department.toLowerCase().includes(this.selectedDepartment.toLowerCase())
})
}else{
return this.employees.filter(employees => {
return employees.name.toLowerCase().includes(this.search.toLowerCase())
})
}
}
},
methods: {
getEmployees(page){
axios('/employees').then((response) => {
this.employees = response.data.data
this.meta = response.data.meta
})
},
getDepartments(){
axios('/departments').then((response) => {
// console.log(response.data)
this.departments = response.data
})
},
},
mounted() {
this.getEmployees()
this.getDepartments()
}
}
</script>
I'm trying to post a new object to my api array using axios and Vue.js. I'm trying to add the functionality to add a new object and display it on the timeline. I can see that when I post a new title I get a console.log of the object but it is not added to the correct array from the api, there is no new id associated with the new object.
Index.html
<body>
<div id="app">
<template>
<form #submit.prevent>
<input type="text" v-model="postBody"/>
<button type="button" class="btn btn-primary pull-right" data-toggle="modal" #click="postPost()">Post Title</button>
</form>
<ul v-if="errors && errors.length">
<li v-for="error of errors">
{{error.message}}
</li>
</ul>
</template>
<br>
<!-- <p>{{ status }}</p> -->
<template v-for="(results, index) in result">
<div class="card" style="width: 20rem; display:inline-block;">
<div class="card-block">
<p>{{ results.id }}</p>
<p>{{ results.title }}</p>
<!-- <button type="button" class="btn btn-danger pull-right" data-toggle="modal" v-on:submit.prevent="deleteData(index)" #click="deleteData(results, index) in result">Delete</button> -->
<button type="button" class="btn btn-danger pull-right" data-toggle="modal" #click="deleteData(results, index)">Delete</button>
<h1> {{ results.comments}} </h1>
</div>
</div>
</template>
</div>
</body>
Main.js
var vm = new Vue ({
el: '#app',
data: {
result: '',
title: '',
data: '',
postBody: '',
User: { title: '' },
errors: []
},
created: function(){
this.getResult();
},
methods: {
getResult: function() {
// this.results = 'Loading...';
axios.get('https://my-json-server.typicode.com/shaneogrady/json/db')
.then(response => {
// console.log(response.data);
this.result = response.data.posts;
console.log(this.result);
});
},
deleteData: function(result, id) {
axios.delete('https://my-json-server.typicode.com/shaneogrady/json/posts/' + result.id)
.then(response => {
this.result.splice(id, 1)
console.log(this.result);
});
},
postPost() {
axios.post('https://my-json-server.typicode.com/shaneogrady/json/posts/', {
// id: 4,
// title: 'Shane',
body: this.postBody
})
.then(response => { console.log(response.data); this.result.push(response.data) })
.catch(e => {
this.errors.push(e)
})
}
}
});
Try adding #submit.prevent on the form element
<div id="app">
<form #submit.prevent>
<h4> Add Title</h4>
<div class="form-group">
<label class="pull-left"> Title </label>
<input type="text" class="form-control" placeholder="Title " v-model="User.title">
</div>
<button type="submit" class="btn btn-large btn-block btn-primary" #click="postPost">Submit</button>
</form>
...
if u need to get results after creation of new object u just need to call ur getResult function inside postPost function
like this :
postPost() {
axios.post('https://my-json-server.typicode.com/shaneogrady/json/posts/', {
// id: 4,
// title: 'Shane',
body: this.postBody
})
.then(response => {
this.getResult();
console.log(response.data);
})
.catch(e => {
this.errors.push(e)
})