js如何封装一个对象?

// 职业照
if(res.data.posterUrl){
    this.ruleForm.jobImg.push(
        {
            file: {},
            src: res.data.posterUrl,
            isShowDel: true,
            load: "ok"
        }
    );
}
// 身份证正面
if(res.data.idCardFrontPic){
    this.ruleForm.id1.push(
        {
            file: {},
            src: res.data.idCardFrontPic,
            isShowDel: true,
            load: "ok"
        }
    );
}
// 身份证反面
if(res.data.idCardBackPic){
    this.ruleForm.id2.push(
        {
            file: {},
            src: res.data.idCardBackPic,
            isShowDel: true,
            load: "ok"
        }
    );
}

获取数据后我会做以上处理,但中间有很多是重复了,我不知道该怎么封装它们 这怎么封装比较好呢?

阅读 2.2k
2 个回答

这样?:

methods:{
    pushData(res,ruleForm,prop1,prop2){
        if(res.data[prop1){
            ruleForm[prop2].push({
                file: {},
                src: res.data[prop1],
                isShowDel: true,
                load: "ok"
            });
        }
        return ruleForm;
    }
}

然后调用:

this.pushData(res,this.ruleForm,'posterUrl','jobImg'); 


let pushSrc=res.data.posterUrl||res.data.idCardFrontPic||res.data.idCardBackPic;
this.ruleForm.id2.push({
   file: {},
   src: pushSrc,
   isShowDel: true,
   load: "ok"
});

这样子?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题