0

I'm trying to have a component which can change some elements in it. In reality, a change will be like swapping the object in a given position. I did some POC and tried to do the reverting method to be able to leave it how it was before.

export default {
  name: 'Landing',
  data () {
    return {
      items: [
        {
          id: 1,
          category: 'Something something'
        },
        {
          id: 2,
          category: 'Something something'
        }
      ]
    };
  },
  created() {
    this.originals = this.items.slice(0);
  },
  methods: {
    change() {
      this.items[0].category = 'Changed';
    },
    revert() {
      // ??
    }
  }
};

I've tried a couple of things especially after reading this: https://vuejs.org/2016/02/06/common-gotchas/#Why-isn%E2%80%99t-the-DOM-updating

while (this.snacks.length) {
  this.items.pop();
}

this.originals.slice(0).forEach(o => this.items.push(o));

But it doesn't work. If I delete the pushing part, I get an empty list correctly but if I try somehow to push it back, it won't work.

What am I missing here?

0

1 Answer 1

2

If you give a working fiddle I can show you what happened.

Basically, because you are modifying the same array object. this.originals refers to the same array as this.items

Slice returns a shallow copy of the object. You should either take a deep copy or your revert should be the one initializing the object.

this.items.pop(); will remove the items from this.originals as well.

Sign up to request clarification or add additional context in comments.

4 Comments

You're partially right. this.items.pop() does not modify this.originals though but elements inside are the same.
this.originals and this.items refer to the same array. Wording were poor. :x
Thanks a lot for finding this!
Have encountered this issue multiple times. JS although it doesnt have pointers, arrays and objects work similar to the concept of pointers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.