DEV Community

Cover image for How can I refactor this code snippet?
ch
ch

Posted on

How can I refactor this code snippet?

While developing vuejs project, I often meet a situation like the following:
Here "this" is the vue component.
I would love to refactor this code to look it very nice.
Please share your idea with me.
Thank you.

const newReportPart = { id: this.id, title: this.title, description: this.description, product_id: this.product_id, product_title: this.product_title, rate: this.rate, saved: this.saved, attachments: this.attachments, }; this.$emit('submitReportPart', this.index, newReportPart); 
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
bias profile image
Tobias Nickel

what about this?

const newReportPart = { ... this }; 

are there other props you on this that should not get added o the event? maybe you want to checkout underscore js with its pick or omit methods.

Collapse
 
yeahch profile image
ch

I see what you are meaning. but 'this' is Vue Component, and I want to pass only those parameters into newReportPart.
So I will take a look at pick or omit methods.
Thank you.

Collapse
 
donsalvador profile image
Salvador • Edited

You can use this.$data

 this.$emit('submitReportPart', this.index, this.$data); 

I guess you should clone $data before emit it

Collapse
 
yeahch profile image
ch

this.$data is a object, and is a reference.
So emitting with this.$data incurs some reference error while running.
In order to pass value as a clone, I refactored it like the following.

const reportPartData = { ...this.$data }; this.$emit('submitReportPart', this.index, reportPartData); 

And it works well.
Thank you for all your commenting here. :heart