vue接收json数据_Vue项目获取后端传递json数据并在前端给json数组添加自定义数据...

时间:2025-02-16 12:15:57

因为项目前后端分离,前端需要获取后端传过来的json数据,并显示到页面上,但因为页面的内容是在data()函数里动态生成,有些内容是后端的json没有的,所以在把json数组的数据添加进data()函数里的数组的时候动态的添加一些数据。

1.首先获取后端的json数据:

var jsonObj = (());

1

successResponse是服务器响应内容,其中包含json数据。这里涉及到一个json格式转化问题,因为响应内容successResponse是个对象,所以我们需要先用stringify函数把json转成字符串形式。但因为后面要获取json里面指定的key对应的value,并且自定义添加一些数据,所以我们还需要用parse函数转成Json对象形式(也叫json序列化)。有的朋友就会问了,为什么不直接使用?还要转来转去?因为原本不是json对象。是HttpServletResponse对象。

2.遍历json数组对象,添加自定义数据

for (var i = 0; i < ; i++) {

jsonObj[i].index='table'

}

1

2

3

给json数组对象的每个位置添加自定义内容index:‘table’。

这里数组对象里原来是没有index这个key的,但是会自己添加进去。

3.将改造后的json数组对象传给data()里声明的数组。

[1].subs=jsonObj;

1

最后贴上组件的完整代码:

<>

import bus from '../common/bus';

export default {

data() {

return {

responseResultData: [],

// menuName: '',

collapse: false,

items: [{

icon: 'el-icon-lx-home',

index: 'dashboard',

menuName: '系统首页'

},

{

icon: 'el-icon-lx-cascades',

index: '1',

menuName: '基础表格',

subs: []

},

{

icon: 'el-icon-lx-copy',

index: 'tabs',

menuName: 'tab选项卡'

},

{

icon: 'el-icon-lx-calendar',

index: '3',

menuName: '表单相关',

subs: [{

index: 'form',

menuName: '基本表单'

},

{

index: '3-2',

menuName: '三级菜单',

subs: [{

index: 'editor',

menuName: '富文本编辑器'

},

{

index: 'markdown',

menuName: 'markdown编辑器'

},

]

},

{

index: 'upload',

menuName: '文件上传'

}

]

},

{

icon: 'el-icon-lx-emoji',

index: 'icon',

menuName: '自定义图标'

},

{

icon: 'el-icon-lx-favor',

index: 'charts',

menuName: 'schart图表'

},

{

icon: 'el-icon-rank',

index: '6',

menuName: '拖拽组件',

subs: [{

index: 'drag',

menuName: '拖拽列表',

},

{

index: 'dialog',

menuName: '拖拽弹框',

}

]

},

{

icon: 'el-icon-lx-warn',

index: '7',

menuName: '错误处理',

subs: [{

index: 'permission',

menuName: '权限测试'

},

{

index: '404',

menuName: '404页面'

}

]

}

]

}

},

computed: {

onRoutes() {

return this.$('/', '');

}

},

created() {

// 通过 Event Bus 进行组件间通信,来折叠侧边栏

bus.$on('collapse', msg => {

= msg;

});

();

},

methods: {

getMenu() {

this.$axios

.get('/api/admin/system/menu/list')

.then(successResponse => {

//获取json中的data部分

if ( === 200) {

var jsonObj = (());

var newArray= new Array()

for (var i = 0; i < ; i++) {

jsonObj[i].index='table'

}

[1].subs=jsonObj;

([1].subs);

}

})

.catch(failResponse => {}).catch(error => {

()

})

},

}

}

>

.sidebar {

display: block;

position: absolute;

left: 0;

top: 70px;

bottom: 0;

overflow-y: scroll;

}

.sidebar::-webkit-scrollbar {

width: 0;

}

.sidebar-el-menu:not(.el-menu--collapse) {

width: 250px;

}

.sidebar>ul {

height: 100%;

}

---------------------

作者:古今

原文:/csonst1017/article/details/85710904

版权声明:本文为博主原创文章,转载请附上博文链接!