有这样一个问题:
项目是vue+element-ui+springboot,后端接口传过来的数据是List<Hobby>类型数据,Hobby是实体类,里面只有两个字段(id和name)。controller有@RestController注解:
public Result all() { List<Hobby> hobbyCache = ...; return Result.OK().data("items", hobbyCache); }
前端有一个 el-checkbox-group 想在页面创建时就向后端请求有关hobby的数据用于展示:
<el-form-item label="爱好"> <el-checkbox-group v-model="form.hobby"> <el-checkbox v-for="(h,index) in hobbyCheckbox" :key="index" :label="h.id">{{h.name}}</el-checkbox> </el-checkbox-group> </el-form-item>
js
... data() { return { form: { ..., hobby }, hobbyCheckbox:[] } }, created(){ this.getHobbyCheckBox() }, methods:{ getHobbyCheckBox(){ request({ //axios的实例 url: `/hobby/all`, method: 'get' }) .then(response => { // 怎么操作才可以将response.data.data.items赋值给this.hobbyCheckbox? }) .catch(error => { console.log(error) }) } }
直接console.log(response.data.data.items),输出:
直接赋值this.hobbyCheckbox=response.data.data.items,报错:
尝试过其他一些方法也没能成功,在后端把list通过fastjson的api中的JsonArray将list格式化:
return Result.OK().data("items", JSONArray.parseArray(JSON.toJSONString(hobbyCache)));
有点搞不懂了,希望有别的方法可以解决这个问题,或者是不是哪里想错了写错了?谢谢大家。
非常感谢回答
已解决
悬赏分:30
- 解决时间 2022-01-04 21:44
点赞 0反对 0举报 0
收藏 0
分享 0
回答2
最佳
-
console.log(response.data.data.items) 是在 then 中输出的吗?
如果是的话那么 this.hobbyCheckbox = response.data.data.items 就可以,至于你所谓的报错。
看上去是触发了 null.length,这就需要更多的内容了
http://jsrun.net/3b2Kp/edit
成功的复现了你的 bug,hobby你初值是null了
支持 0 反对 0 举报2022-01-04 09:08