Make a non-reactive copy of a VueJS object

Vue.mixin({ methods: { makeNonReactiveCopy(original) { if (! _.isObject(original) || _.isArray(original)) { return original } let copy = {} let attributes = Object.keys(original) attributes.forEach(attribute => { let attributeValue = Object.getOwnPropertyDescriptor(original, attribute) Object.defineProperty(copy, attribute, { __proto__: null, value: attributeValue.get() }) }) return copy }, backup(original) { return this.makeNonReactiveCopy(original) } } })
This is a simple mixin to make a non-reactive copy of a VueJS Object.

It does not disable reactivity on the original object, instead it returns a non-reactive copy of the original.

By default, VueJS objects are reactive throughout the application, meaning, if an object changes its values, these changes are made in all instances of this object. Sometimes, this is undesirable, as when you are editing an object and wants to return it to its original value. That's when this mixin comes to save you!

Of course, anyone could have their classes return a JSON object of themselves to create a non reactive copy, but this code makes it available globally in your Vue Application and you don't have to duplicate this logic in your objects.

Requires lodash library (npm install lodash --save-dev)

Make sure you set lodash in the window DOM object
E.g. window._ = require('lodash')

2 Responses

You don't need to use lodash to corroborate if you have an array or and object. You could use Array.isArray(object) or typeof object !== 'object'.
Regards
if we use lodash the simple way to get non-reactive object is use clone or cloneDeep method of lodash library

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.