这是我第一次与Vue合作,我正在尝试使用Spring作为后端做一个简单的任务。我的问题是,当我向演员发送带发布请求的邮件时,我尝试发出get请求以获取新的演员列表时,直到刷新页面后,该更新才会更新。
这是我要显示的html的一部分。只是表格和我从数据库中带走的演员列表。
<v-flex>
<v-text-field
v-model="newActor.firstName"
label="Nombre"
prepend-icon="person"
></v-text-field>
</v-flex>
<v-flex>
<v-text-field class="ml-5"
v-model="newActor.lastName"
label="Apellido"
> </v-text-field>
</v-flex>
<v-flex>
<v-btn :class="['white--text','green']" @click="addActor">Enviar</v-btn>
</v-flex>
<li v-for="actor in actors" v-bind:key="actor.id" :class="['mt-5']">
id = {{actor.actorId}}
<br>
name = {{actor.firstName}}
<br>
apellido = {{actor.lastName}}
<br>
lastUpdate = {{actor.lastUpdate}}
</li>
这是我的Vue脚本。
export default {
data() {
return {
alert: false,
alertMessage: '',
alertType: 'success',
urlBase: 'http://localhost:8081/',
newActor:
{
firstName: '',
lastName: '',
lastUpdate: ''
},
background: 'yellow',
actors: []
}
},
methods:
{
getActors: function()
{
this.actors = []
let self = this
fetch(this.urlBase+'actors/all')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
for (var variable of myJson) {
self.actors.push(variable);
}
});
},
addActor: function()
{
if (this.newActor.firstName != '' && this.newActor.lastName != '')
{
let self = this
fetch(this.urlBase+'actors/add', {
method: 'POST',
body: JSON.stringify(this.newActor),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
this.alert = true;
this.alertMessage = "Usuario agregado con éxito";
this.getActors(); //Here is where I tried to get the actors again.
console.log(this.actors);
}
else
{
this.alert = true;
this.alertType = 'error';
this.alertMessage = "Usuario no registrado";
}
}
},
created: function()
{
this.getActors()
}
}
答案 0 :(得分:0)
这是因为在完成this.getActors();
方法之前调用了fetch
。这就是javascript的工作方式。
您可以尝试将this.getActors();
放在then
中。
示例:
if (this.newActor.firstName != '' && this.newActor.lastName != '')
{
let self = this
fetch(this.urlBase+'actors/add', {
method: 'POST',
body: JSON.stringify(this.newActor),
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => {
console.log('Success:', response);
this.alert = true;
this.alertMessage = "Usuario agregado con éxito";
this.getActors(); //Here is where I tried to get the actors again.
console.log(this.actors);
})
}