Cover image for How can I refactor this code snippet?

How can I refactor this code snippet?

yeahch profile image C & H ・1 min read

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);


Editor guide
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.

yeahch profile image
C & H Author

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.

donsalvador profile image

You can use this.$data

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

I guess you should clone $data before emit it

yeahch profile image
C & H Author

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