【问题标题】:Iterate through Vue component fields遍历 Vue 组件字段
【发布时间】:2019-12-18 23:50:50
【问题描述】:

我有一个具有很多属性 (> 40) 的 Vue 组件。它是用于编辑某些业务实体的表格。流程如下:

  1. 在mounted() 时,将数据作为json 从服务器加载并初始化组件属性
  2. 根据需要编辑数据
  3. 将所有属性放入json结构中并发回服务器更新数据

我的组件中的属性命名与 json 结构中的完全相同。我想遍历组件中的属性并使用 1 行代码创建 json 结构,而不是执行以下操作:

var data = {
 field1 = this.field1,
 field2 = this.field2,
 field3 = this.field3
 ...
 field40 = this.field40
}

我用的是TS和vue-class-component,所以组件代码是这样的:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  template: ...
})
export default class MyComponent extends Vue {
  field1: Number = null;
  field2: Date = null;
  field3: String = null;
  ...
  field40: Number = null;

  mounted() {
    axios.get(..., response => {
      this.field1 = response.data.field1
      this.field2 = response.data.field2
      this.field3 = response.data.field3
      ...
      this.field40 = response.data.field40
    }
  }

  submit() {
    const data = {
      field1 = this.field1,
      field2 = this.field2,
      field3 = this.field3,
      ...
      field40 = this.field40,
    };

    axios.put(..., data);
  } 
}

【问题讨论】:

    标签: json typescript vue.js


    【解决方案1】:

    您可以将字段包装在数据中的模型字段中:

    data:{ model:{}}
    

    然后在挂载时,您可以在模型中设置反应性道具

      mounted(){
            for(let field in YOUR_JSON_OBJ){
               Vue.set(this.model, field , YOUR_JSON_OBJ[field])
            }
       }
    

    然后当你需要提交表单时,只需传递你的 vue model prop

    YOUR_SUBMIT_METHOD(JSON.stringify(this.model))
    

    【讨论】:

    • 我会尽快试试这个
    • 我忘了说我使用 typescript 和 vue-class-component。请查看更新后的问题
    【解决方案2】:

    我可以看到两种方法来做到这一点。

    如果您事先知道,请提供数组中的属性列表(这是更好的做法,因为data 属性以正确的方式启动):

    const props=['field1','field2', ...];
    export default {
      async mounted(){
         //load the data and ensure only the expected properties are mounted
         //this avoids any unexpected behaviour.
         const result = await loadMyData();
         for(let prop of props) this[prop]=result[prop];
      }
      data(){
        //instantiate the data object to ensure all the properties are reactive
        const data={};
        for(let prop of props) data[prop]=null;
        return data;
      }
      methods:{
        async updateServer(){
           //build the data object to send back to the server then send it.
           const data={};
           for(let prop of props) data[prop]=this[prop];
           await sendUpdate(data);
        }
      }
    }
    

    第二种方法是在您使用Object.keys() 从服务器加载数据时存储属性列表并将其存储为数据属性。然后,您需要使用vm.$set 来确保所有属性都具有正确的反应性,并且您将无法在根级别拥有这些属性,而是需要嵌套它们(请参阅the vue docs)。但是我假设如果您的视图对象旨在对这些属性做出反应,那么您必须提前知道它们。

    【讨论】:

    • 好主意,但我不想带这个 props 数组,因为我已经将我的所有属性都列为组件字段
    • 我忘了说我使用 typescript 和 vue-class-component。请查看更新后的问题
    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2014-10-01
    • 2016-02-27
    • 1970-01-01
    • 2018-05-30
    • 2019-09-04
    相关资源
    最近更新 更多