DEV Community

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

Posted on

3 2

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay