【问题标题】:Add a response data into an object - Vue.js将响应数据添加到对象中 - Vue.js
【发布时间】:2021-06-25 14:26:00
【问题描述】:

我创建了一个这样的模型:

export class Model{
    data1: string
    data2: string
    data3: string
    data4: string

    constructor(data1: string, data2: string, data3: string, data4: string){
        this.data1 = data1
        this.data2 = data2
        this.data3 = data3
        this.data4 = data4
    }
}

在我的组件中,我正在执行 axios 请求,并且我想将 axios 响应“添加”到该对象中。但是我的 axios 数据没有相同的标题(例如:我的模型中的 data1/我的响应中的 dataName)。

这是我的 component.vue

import { Model } from '@/models/Model'

export default Vue.extend({
  data: () => ({
    data: [] as Model[]
  }),
  created() {
    apiService.getDataList().then(response =>{ //ApiService.getDataList() is an method coming from another component
      //I search what to do here
    })

  }
})

有人知道怎么做吗?

PS:我正在使用 TypeScript

【问题讨论】:

    标签: typescript vue.js axios


    【解决方案1】:

    假设没有其他隐藏需求,您只需将响应数据映射到您声明的模型中:

    import { Model } from '@/models/Model'
    
    export default Vue.extend({
      data: () => ({
        data: [] as Model[]
      }),
      created() {
        apiService.getDataList().then(response => {
          for(const item in response.data) {
             this.data.push(new Model(item.dataName, item.foo, item.bar /* etc. */))
          }
        })
    
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 2019-07-17
      • 1970-01-01
      • 2019-05-16
      • 2011-06-08
      • 2018-09-21
      • 2019-07-01
      • 2021-12-31
      • 2020-05-12
      相关资源
      最近更新 更多