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?

Antonio Laguna
  • 8,973
  • 7
  • 36
  • 72

1 Answers1

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.

user1496463
  • 410
  • 3
  • 14