A
A
Artem00712017-09-14 12:03:03
JavaScript
Artem0071, 2017-09-14 12:03:03

How to deal with reactivity (with passing by reference and object deep copying)?

There is some constant block:

const block = {
  title: '',
  hash: '',
  end: {
    is_end: 0,
    type: 0
  }
}

So, when I create an object, I do something like this:
import empty_block from '../../data/empty_block';
let block = {...empty_block}; // пытаюсь избавиться от реактивности

block.title = this.title;
block.hash = Math.floor(Date.now() / 1000);

this.$store.commit('addBlock', block);

Good works, adds everything normally
BUT!
When I try to change an object, it turns out that ALL objects change in the place where end{...}!
And if I made an empty block like this:
const block = {
  title: '',
  hash: '',
  is_end: 0,
  type: 0
}

That all worked fine!!!
I just don't know what to do anymore...
help mi pliz kind people, tell me how to get rid of reactivity where it is not needed

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Kramov, 2017-09-14
@Artem0071

The easiest option is to do it the way the Vue developers recommend.
In the empty_block module, instead of exporting an object, you can export a function that returns an object.

export default function () {
  return {
    title: '',
    hash: '',
    end: {
      isEnd: 0,
      type: 0
    }
  }
}

In other modules, respectively, just write:
import emptyBlock from 'emptyBlock'
let block = emptyBlock()

Why does your object remain reactively linked, because objects in JS are passed by reference, and not by value, respectively, even if you reassembled the object using { ...someObject }, the objects that it contained someObjectremain the same and with any mutation of all owners of the object reference he is changing.
By the way, I want to note that in JS it is not customary to write in snake_case, camelCase is preferable.

I
Igor Koch, 2017-09-14
@amux

//let block = {...empty_block};
let block = _.cloneDeep(empty_block);

https://lodash.com/docs/#cloneDeep

E
Evgeny Kulakov, 2017-09-14
@kulakoff Vue.js

You can try like this:

let block = JSON.parse(JSON.stringify(empty_block))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question