Skip to content

Instantly share code, notes, and snippets.

@Den2016
Last active January 29, 2020 15:28
Show Gist options
  • Save Den2016/ccfbda8fc1cd6ade9089e7392f6aeab7 to your computer and use it in GitHub Desktop.
Save Den2016/ccfbda8fc1cd6ade9089e7392f6aeab7 to your computer and use it in GitHub Desktop.
deepCopy and generateElementId mixin for Vue.js
export default {
methods: {
/**
* Copying properties of one object to another while maintaining reactivity
*
* @param _from
* @param _to
*/
deepCopy(_from, _to) {
if (Array.isArray(_from)) {
_from.forEach(_f => {
let _t;
if (typeof _f === 'object') {
if (_f === null) {
_t = _f;
} else {
_t = Array.isArray(_f) ? [] : {};
this.deepCopy(_f, _t);
}
} else {
_t = _f;
}
_to.push(_t)
})
} else {
for (let prop in _from) {
if (typeof _from[prop] === 'object') {
//_to[prop]=Array.isArray(_from[prop])?[]:{};
if (_from[prop] === null) {
this.$set(_to, prop, _from[prop]);
} else {
if (!_to[prop]) { // object may contain this prop, merge it
this.$set(_to, prop, Array.isArray(_from[prop]) ? [] : {});
}
this.deepCopy(_from[prop], _to[prop]);
}
} else {
//_to[prop] = _from[prop];
this.$set(_to, prop, _from[prop]);
}
}
}
},
/**
* Generate page unique element ID
* checkin is additional array, which may contains any ids, possible to exclude by generator
* @param prefix
* @param checkin
* @returns {string}
*/
generateElementId(prefix = 'a', checkin = []) {
let id = prefix + Math.random().toString(36).substring(7);
while (document.querySelector('#' + id) || checkin.includes(id)) id = prefix + Math.random().toString(36).substring(7);
return id;
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment