如何在Vue前端展示Django API返回的ManyToMany数组文本
问题:将Django API返回的ManyToMany数组在Vue中按行展示
调用Django API后得到如下格式的数组:
[ {"interest_name":"Money"}, {"interest_name":"Django"}, {"interest_name":"Test"} ]
需要在HTML中展示为每行一个名称的形式,而非原始JSON结构:
Money Django Test
当前Vue代码中,projects.interest_category对应这个数组,直接渲染会显示原始结构,以下是两种可行的解决方案:
方案1:模板内直接遍历数组
直接在模板中用v-for循环遍历interest_category数组,逐个渲染interest_name字段,每个名称单独占一行。
修改原模板中的对应部分:
<div> <h5 class="card-title">{{projects.project_description}}</h5> <!-- 替换原来的 <p>{{projects.interest_category}}</p> --> <div v-for="(interest, idx) in projects.interest_category" :key="idx"> {{ interest.interest_name }} </div> </div>
如果希望用换行符而非独立元素实现换行,也可以这样写:
<p> <span v-for="(interest, idx) in projects.interest_category" :key="idx"> {{ interest.interest_name }}<br> </span> </p>
方案2:通过计算属性预处理数据(适用于需额外处理的场景)
如果需要对数组做更多格式化处理,可以在组件中添加计算属性,将每个项目的兴趣类别转换为换行分隔的字符串,再在模板中渲染。
修改组件脚本部分:
<script> import { getAPI } from '../../axios-api' export default { name: 'ProjectDashboard', data () { return { ProjectsAPI: [] } }, computed: { processedProjects() { return this.ProjectsAPI.map(project => ({ ...project, // 将兴趣类别数组转为换行分隔的字符串 interestNames: project.interest_category.map(item => item.interest_name).join('\n') })) } }, created () { getAPI.get('api/v1/projects') .then(response => { this.ProjectsAPI = response.data console.log('API Data Received') }) .catch(err => { console.log(err) }) } } </script>
修改模板部分:
遍历预处理后的processedProjects数组,渲染interestNames时添加white-space: pre-line样式以保留换行:
<div v-for="project in processedProjects" :key="project.id" class="container"> <div class="card mt-2"> <div class="card-header"><strong>Task Made By: {{ project.project_title }}</strong></div> <div class="card-body d-flex flex-row justify-content-between"> <div> <h5 class="card-title">{{project.project_description}}</h5> <p style="white-space: pre-line;">{{ project.interestNames }}</p> </div> </div> <div class="card-footer text-muted"> Task Made At: {{project.created_at}} </div> </div> </div>
内容的提问来源于stack exchange,提问作者ckcAdmin
相关产品推荐
相关产品推荐

