Quite new to Vue, I cannot figure out how to automatically render my updated array.
I have a very basic page including an input, and a button. When the button is clicked, the data is saved in a MongoDB via my server.
Right below the form, I'm displaying the fetched data from Mongo.
But, when I create a new item, I need to reload the page to see the updated list. How should I proceed to see the table updating "live"?
Here is my Vue Code:
<template>
<div >
<h1>Hello</h1>
<form submit.prevent="">
<input v-model="newItem" type="text">
</form>
<button @click="createItem">Create</button>
<div>
<table>
<tr>
<th>Name</th>
</tr>
<tr v-for="(item, index) of items" :key="index">
<td>{{ item.name }}</td>
</tr>
</table>
</div>
</div>
</template>
<script>
import CrudService from '../services/crud.service';
import { ref } from 'vue';
export default {
data(){
return{
newItem: '',
items: [],
}
},
async mounted(){
await this.readItems();
},
methods: {
async readItems(){
const results = await CrudService.readItems();
results.data.forEach(element => {
ref(this.items.push(element));
});
},
async createItem(){
await CrudService.createItem({ item: this.newItem });
}
}
}
</script>
CodePudding user response:
Try like following snippet (uncomment for api calls) :
new Vue({
el: "#demo",
data(){
return{
newItem: {
name: ''
},
items: [],
}
},
async mounted(){
await this.readItems();
},
methods: {
async readItems(){
// const results = await CrudService.readItems();
const results = [{name:1},{name:2},{name:3}]
this.items = results
},
createItem(){
// await CrudService.createItem({ item: this.newItem });
this.items.push({...this.newItem})
this.newItem.name = ''
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div >
<h1>Hello</h1>
<form submit.prevent="">
<input v-model="newItem.name" type="text">
</form>
<button @click="createItem">Create</button>
<div>
<table>
<tr>
<th>Name</th>
</tr>
<tr v-for="(item, index) of items" :key="index">
<td>{{ item.name }}</td>
</tr>
</table>
</div>
</div>
</div>
CodePudding user response:
You could call the readitems() method after created item to update your view without refreshing.
<script>
import CrudService from '../services/crud.service';
import { ref } from 'vue';
export default {
data(){
return{
newItem: '',
items: [],
}
},
async mounted(){
await this.readItems();
},
methods: {
async readItems(){
const results = await CrudService.readItems();
this.items = [];//add this line to clear items firstly
results.data.forEach(element => {
ref(this.items.push(element));
});
},
async createItem(){
await CrudService.createItem({ item: this.newItem });
await this.readItems();//add this line
}
}
}
</script>
