gpt4 book ai didi

javascript - 来自 Axios GET 响应的 VueJs 中的数组为空 | VUEJS/Laravel

转载 作者:行者123 更新时间:2023-12-03 00:43:19 27 4
gpt4 key购买 nike

我正在学习如何通过 udemy 类(class)制作单页应用程序,同时尝试做一个大学项目。问题是,在我的 Controller 中,我将数据库查询作为 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" 不起作用,因为 [ ]truthyalunos 初始化为 []。我相信 v-if="alunos.length" 就是你想要的。

关于javascript - 来自 Axios GET 响应的 VueJs 中的数组为空 | VUEJS/Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com