Axios GET响应|VueJs/LARAVEL中VueJs中的数组为空



我正在学习如何在尝试执行uni项目时使用udemy课程执行单页应用程序。问题是,在我的控制器中,我将数据库查询作为json"alunos"发送到前端。现在,在Vue中,如果我只放axios.get和console.log(响应(,我可以看到我来自db的数据在那里,但是当我试图将这些数据推送到我的数组以便在模板上显示时,它仍然是空的,console不会返回错误。我到处找,但还是找不到。

AlunoComponent.vue模板

<template>
<div>
<button class="btn btn-primary btn-block">Add Novo Aluno</button>
<table class="table" v-if="alunos">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">RGA</th>
<th scope="col">Nome</th>
<th scope="col">Instituição</th>
<th scope="col">Campus</th>
<th scope="col">Curso</th>
<th scope="col">Semestre</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr>
<th v-for="aluno in alunos" v-bind:key="aluno.id" scope="row" >1</th>
{{alunos}}
<td>{{aluno.id}}</td>
<td>{{aluno.rga}}</td>
<td>{{aluno.nome}}</td>
<td>{{aluno.instituicao}}</td>
<td>{{aluno.campus}}</td>
<td>{{aluno.curso}}</td>
<td>{{aluno.semestre}}</td>
<td><button class="btn btn-info">Edit</button></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>   
</tbody>
</table>
</div>

AlunoComponent.vue 内部的逻辑

<script>
export default {
data(){
return {
aluno:{
nome:'',
nascimento:'',
rga:'',
cpf:'',
rg:'',
instituicao:'',
campus:'',
curso:'',
semestre:''
},
//vetor pras infos
alunos:[],
uri: '/alunos'
}
},
methods:{
loadAlunos(){
axios
.get(this.uri)
.then(response=>{
//console.log(response.data)
this.alunos = response.data.alunos
}).catch(error => {
console.log(error)
});
}
},
mounted() {
this.loadAlunos();
console.log('Component mounted.')
}
}
</script>

有人能帮我吗?我仍然是vue js 的初学者

您的表模板看起来不正确。你想要这样的东西:

<tbody>
<tr v-for="aluno in alunos" :key="aluno.id" scope="row">
<td>{{aluno.id}}</td>
<td>{{aluno.rga}}</td>
<td>{{aluno.nome}}</td>
<td>{{aluno.instituicao}}</td>
<td>{{aluno.campus}}</td>
<td>{{aluno.curso}}</td>
<td>{{aluno.semestre}}</td>
<td><button class="btn btn-info">Edit</button></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>   
</tbody>

如果alunos:中有5个元素,则当前模板将生成类似的内容

<tbody>
<tr>
<th>1</th>
<th>1</th>
<th>1</th>
<th>1</th>
<th>1</th>
{{alunos}}
<td>{{aluno.id}}</td>
<td>{{aluno.rga}}</td>
<td>{{aluno.nome}}</td>
<td>{{aluno.instituicao}}</td>
<td>{{aluno.campus}}</td>
<td>{{aluno.curso}}</td>
<td>{{aluno.semestre}}</td>
<td><button class="btn btn-info">Edit</button></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>   
</tbody>

另一个提示是,如果您想在alunos数组为空时隐藏表,则v-if="alunos"不起作用,因为[]是truthy,而alunos初始化为[]。我相信v-if="alunos.length"就是你想要的。

最新更新