[英]Array is empty in VueJs from Axios GET response | VUEJS/LARAVEL
我在尝试做一个uni项目的同时学习了如何用udemy课程做一个单页应用程序。 问题是,在我的控制器中,我将数据库查询作为json“ alunos”发送到前端。 现在,在Vue中,如果仅放置axios.get和console.log(response),我可以看到来自db的数据,但是当我尝试将这些数据推入数组以便可以在模板上显示时,它仍然为空,控制台不返回任何错误。 我到处搜索,但仍然无法正常工作。
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"
不起作用,因为[]
是真实的 ,并且alunos
初始化为[]
。 v-if="alunos.length"
是您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.