Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

js 多个对象插入同样的两个值,怎么操作,vue

在vue中data里面有三个对象

data(){
 return{
   select1:{id:1012589435413},
   select1:{id:5487496874987},
   NoticeForm:{},
   Archives:{},
   ...... // 多个
 }
},
methods:{
    setItem(){
      let NoticeForm = this.NoticeForm;
      NoticeForm.data3 = this.select1.Id;
      NoticeForm.data4 = this.select2.Id;

      let Archives = this.Archives;
      Archives.data3 = this.select1.Id;
      Archives.data4 = this.select2.Id;
      
      ...... // 多个
    }
},

上面的这是最常见的操作,有没有更简便的方法可以实现,尽量不循环


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

DRY(Don’t Repeat Yourself)原则的目的是减少信息的重复,那怎么做到DRY,那就是代码和逻辑的重用,将代码和逻辑划分为更小的可重用单元,并通过在需要的地方调用代码来使用这些单元代码。不要编写过于冗长的方法,要进行逻辑拆分,并尽量使用现有方法中已经写好的逻辑。

针对你的代码,想要减少代码量,不用循环的话,可以把值写好,用Object.assign浅拷贝。想要再少,那就肯定是循环,循环的本质就是减少代码量

methods:{
    setItem(){
        let data = {data3: this.select1.Id, data4: this.select2.Id}
        Object.assign(this.NoticeForm, data)
        Object.assign(this.Archives, data)
        //...
        
        [this.NoticeForm, this.Archives, /*...*/].forEach(item => Object.assign(item, data))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...