vue 前后端交互(解决新手的尴尬)

前后端交互

一、请求时,要求携带参数或者请求头怎么写
二、获取后端数据,如何按照格式获取

一、
1.1 每个请求都要求携带上token, 位置:请求头
那么可以进行全局配置,在上次的博客中有详细说到如何配置。

1.2 个别请求要求携带userId, 位置:请求头
一般来说,userId都是在登录成功的时候,存放在localStorage中,那么我们去那里提取就好啦~

      let userId = localStorage.getItem('userId')
      let config = {
        headers: { 'userId': userId }
      }

注意:携带的是请求头的时候不管是get还是post,都直接把变量名用逗号隔开写在尾部,如:{…,config}

1.3 携带必填参数, 位置:body
获取数据的方法中:
1)、创建一个变量,如 let data = {
today: 1, scppe:‘d’
}
2)、在连接后端数据的时候,把变量名用逗号隔开写到尾部 如:

const { data: res } = await this.$http.get('api接口', { params: data })

注意:get请求带上params,post不用带。get请求:(…,{params:data}) post请求:(…,data)

1.4在地址的中间带上参数的(拼接地址)
1.5 在地址的尾部带上参数名和值的

例子写一块啦~

const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )

1.6,get请求一般多放在地址后面拼接,此刻请求参数不能是数组,可以用逗号分隔代替数组;post等放在body上的请求体则可以使用任何格式的参数

二、
2.1、后端数据为数组格式,前端data已有固定的一个属性名,那么获取数据方式为直接赋值,因为是数组,因此赋值时要写上[0]
案列:
后端数据格式:

{
    "code": 20000,
    "message": "deserunt velit aliquip proident",
    "data": [
        {
            "frieMsg": 83,
            "leave": 74,
            "date": "1975-12-12",
            "malfunction": 82
        }
    ]
}

前端中的data写法:

today: {
        frieMsg: 0,
        malfunction: 0,
        leave: 0
      }

存储数据方法:

        this.today.frieMsg = res.data[0].emg
        this.today.malfunction = res.data[0].Battery
        this.today.leave = res.data[0].offState

2.2、后端数据为数组格式,前端data只给出了一个空数组,属性名和属性值都没写
步骤:
1)、创建一个空数组,用于存放获取的数据
2)、把后端数据push进空数组
3)、把填充好的数组的值赋给data

案例:
后端数据格式

{
"code":20000
"message":"业务请求成功"
"data":{
    "data":[
        0:{
           "latitude":23.04678
           "longitude":113.736929
           "code":"441988106"
           "name":"啦啦镇"
           "value":2
           }
        1:{...}
        2:{...}
       ]
   }
}

前端的要求格式:

captals:[{
        'name': '北京市',
        'center': [116.407394, 39.904211]
      },....]

前端的data写法:

capitals:[]

存储数据方法:

 let _this = this
      let formData = []
      res.data.data.forEach(function (elem, index) {
        let data = {
          name: elem.name,
          center: [elem.longitude, elem.latitude]
        }
        formData.push(data)
      })
      _this.capitals = formData

2.3、后端数据传过来的是对象,但是前端的格式要求为数组(由于用了第三方插件的硬性规定)
需求:把从后端拿来的对象替换掉前端数组里面原有的数据
案列:
后端数据格式(此是后台打印的):

{
    adImageName: "adve/11.jpg"
	adLink: "www.baidu.com"
	adName: "11.jpg"
	adOrder: 5
	adType: 1
	idBanner: 51
}

前端格式要求:

fileList: [{........}]

前端的data写法:

fileList: []

存储数据方法:

 let _this = this
 let { data: res } = await this.$http.get(`/ban/${url}`)
 data.push({
              url: `图片地址`,
              name: res.data.adName,
              link: res.data.adLink,
              order: res.data.adOrder,
              banner: res.data.idBanner,
              type: res.data.adType
            })
  _this.fileList = data

2.4、 后端数据:后端返回来的为数组,内含多个对象,对象里面又包含多个对象,具体描述如下代码:
前端要求:把里面的多对象拆开,并分别合并到外层的共同数组中,具体描述如下代码:

后端数据格式:

 "list":[
        {
            "maintainId":"订单",
            "hitchInfo":"说明",
            "addressPhone":"手机",
            "provinceCode":"行政码",
            "cityCode":"行政码",
            "countyCode":"行政码",
            "townCode":"行政码",
            "maintainHitchList":[
                {
                    "hitchId":"1342376174348464130",
                    "hitchType":"类型",
                    "productName":"SD",
                    "maintainId":"20201225N337C6BB2"
                },{
                    "hitchId":"1342376174348464130",
                    "hitchType":"类型",
                    "productName":"TM",
                    "maintainId":"20201225N337C6BB2"
                }
            ]
        }, {
            "maintainId":"订单2",
            "hitchInfo":"说明2",
            "provinceCode":"行政码",
            "cityCode":"行政码",
            "countyCode":"行政码",
            "townCode":"行政码",
            "maintainHitchList":[
                {
                    "hitchId":"1342376174348464130",
                    "hitchType":"类型",
                    "productName":"SD",
                    "maintainId":"20201225N337C6BB2"
                },{
                    "hitchId":"1342376174348464130",
                    "hitchType":"类型",
                    "productName":"SD",
                    "maintainId":"20201225N337C6BB2"
                }
            ]
        },
    ],

前端要求的数据格式:

 "list":[
        {
            "maintainId":"订单",
            "hitchInfo":"说明",
            "addressPhone":"手机",
            "provinceCode":"行政码",
            "cityCode":"行政码",
            "countyCode":"行政码",
            "townCode":"行政码",
            "hitchId":"1342376174348464130",
            "hitchType":"类型",
            "productName":"SD",
            "maintainId":"20201225N337C6BB2"       
        },{
        	"maintainId":"订单",
            "hitchInfo":"说明",
            "addressPhone":"手机",
            "provinceCode":"行政码",
            "cityCode":"行政码",
            "countyCode":"行政码",
            "townCode":"行政码",
            "hitchId":"1342376174348464130",
            "hitchType":"类型",
            "productName":"TM",
            "maintainId":"20201225N337C6BB2"
        },
        ....
    ],

具体实现:

 repairMaintain(formdata).then(response => {
        this.list = response.data.list; //把后端获取到的数据保存到list中
        const lists = []
        for (let i = 0; i < this.list.length; i++) {  
          for (let n = 0; n < this.list[i].maintainHitchList.length; n++) {
              const saveMsg = {
                maintainId: this.list[i].maintainId,
                hitchInfo: this.list[i].hitchInfo,
                clientName: this.list[i].clientName,
                addressPhone: this.list[i].addressPhone,
                addressDetailed: this.list[i].addressDetailed,
                updateTime: this.list[i].updateTime,
                createTime: this.list[i].createTime,
                hitchType: this.list[i].maintainHitchList[n].hitchType,
                productName: this.list[i].maintainHitchList[n].productName
              }
              lists.push(saveMsg)
          }
        }
        this.list = lists
        console.log(this.list, 'listlistlistlistlistlistlist')

2.5 需要把拿到的后端数据,放在对象里面的对象里,如:

  list:[
     a:1,
     b:2,
     c:{
     	c1:3,
     	c2:5
       }
   ]

具体实操:

   repairMaintain(formdata).then(response => {
        this.list = response.data.list; //从后端获取的数据存储再list中
        const lists = []
        for (let i = 0; i < this.list.length; i++) {
          for (let n = 0; n < this.list[i].maintainHitchList.length; n++) {
              const saveMsg = {
                maintainId: this.list[i].maintainId,
                hitchInfo: this.list[i].hitchInfo,
                clientName: this.list[i].clientName,
                selected: {    //这里可以直接嵌入对象的哦
                  province: this.list[i].provinceCode + '',
                  city: this.list[i].cityCode + '',
                  area: this.list[i].countyCode + '',
                  town: this.list[i].townCode + ''
                },
              }
              lists.push(saveMsg)
          }
        }
        this.list = lists
      });

2.5 后端的数据为对象里面包含多个数组,前端需要拿取每个数组里面的两个值,组合成键值对,放在一个对象里,具体如下
后端返回的数据为:

[
	{
	 productName: "TD"
	 profileImages: "["product/TD.png"]"
	 }
	 {
	 productName: "SD"
	 profileImages: "["product/SD.png"]"
	 }
	 {
	 productName: "ID"
	 profileImages: "["product/ID.png"]"
	 }
]

前端要求整合成:

let obj = {
			TD: product/TD.png,
			SD: product/SD.png,
			ID: product/ID.png
 		}

实现如下:

  let myImg = await getProduct();
          if (myImg.code === 200) {
            let b = {}
            myImg.data.forEach((e) => {
              b[e.productName] = e.profileImages
            })
            console.log(b, 6666);
          }

2.5 将多层的信息整合成一层,将同一属性名的属性值使用 , 分隔开,具体如下:

原数据为:

date2: "2020.5.15"
clientName: "迎冬"
addressPhone: "15788562369"
list: [{
	hitchInfo: '111',
    hitchTypes: '11111',
    productNames: '111111'},{
	hitchInfo: '222',
    hitchTypes: '22222',
    productNames: '222222'
	}
]

要求整合成:

date2: "2020.5.15"
clientName: "迎冬"
addressPhone: "15788562369"
hitchInfo: '111','222'         //使用逗号隔开
hitchTypes: '11111','22222'
productNames: '111111','222222'

实现方式如下:

  let b = {
        hitchInfo: '',
        hitchTypes: '',
        productNames: ''
      }
      this.form.list.forEach((key) => {
        for (let i in key) {
          //转换成json格式,去掉双引号,将空的数据使用null代替
          let data = key[i] && JSON.stringify(key[i]) !== '{}' ? JSON.stringify(key[i]).replace(/\"/g, "") : 'null'   
          //合并
           b[i] = b[i].length ? b[i].concat(`,${data}`) : b[i].concat(`${data}`)
        }
      })
  console.log(b)
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值