elementui组件大多都有自己特定的属性名,例如Select选择器以value作为选项的值,以label作为选项的标签。而后台的就不一定叫label,可能叫做name,或者别的。由此看来很多时候后台返回的数据不一定与前端所需的一一对应,这就需要想办法使其符合所需了。

我习惯用的方法:

当时的应用场景是用Select 选择器下拉菜单展示从后台获取的小区名,因为当时已经把下拉框封装好,只需将后台返回的数据修改到符合要求后赋值给options即可:
当时options在这里

formData: {
    labelWidth: '100px', inline: false, labelPosition: 'right', size: 'small',
    formItem: [
      { type: 'select', label: '小区', prop: 'communityId', size: 'small', isDisabled: false, multiple: false, tip: '', value: '', options: [] },
    ]
}

步骤
1、首先在data(){return{ }}里面初始化:

communityOptions: [], // 小区名称

2、想办法遍历换字段名
方法一:map遍历

// 选项:获取小区
    getCommunity() {
      listCommunityOptions(this.$store.getters.id).then(response => {
        this.communityOptions = response.data.map(function(val) {
          return { label: val.communityName, value: val.id }
        })
        this.formData.formItem[0].options = this.communityOptions
      })
    },

方法二:普通的for循环遍历

// 选项:获取小区
    getCommunity() {
      listCommunityOptions(this.$store.getters.id).then(response => {
        const communityList = response.data
        for (let i = 0; i < communityList .length; i++) {
          const community= communityList [i]
          this.communityOptions.push({ label: community.communityName, value: community.id})
        }
        this.formData.formItem[0].options = this.communityOptions
      })
    },

其他方法:

getCommunity() {
  listCommunityOptions(this.$store.getters.id).then(response => {
    this.communityOptions = JSON.parse(JSON.stringify(res.data).replace(/communityName/g, 'label').replace(/id /g, 'value'))
   this.formData.formItem[0].options = this.communityOptions
   })
}

拓展:(借鉴此处
后端给我返回格式是这样:[‘2018-8-14’, ‘2018-8-14’]
但是我是想要这样的格式:{date: “2018/08/13”, title: “”}
一段代码搞定:

let arr = res.data;
let newArr = arr.map(val => {
   let json = {};
   json.date = val.split('-').join('/');
   json.title = '';
   return json;
});
this.demoEvents = newArr;//这个是页面循环的值
Logo

前往低代码交流专区

更多推荐