K
K
Kirill2021-10-23 02:30:12
Vue.js
Kirill, 2021-10-23 02:30:12

How to get the previous state of an array in watch?

https://codesandbox.io/s/mystifying-meadow-hnovr?f...

We want prevItems to keep the previous value of items. I googled the design that I depicted in the sandbox, but it does not work. I know that I can do this in a method, but this does not suit me, because in a real example, the items array is changed by several different methods at once, and changing the value of prevItems inside each seems like a bad idea.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-10-23
@Lirrr

watch: {
  cloneItems(old, cur) {
    this.prevItems = old;
  },

That's what happens when you don't read the documentation.
The parameters are mixed up in places - first the new value, then the old one.
computed: {
  cloneItems: () => this.items.slice(),

That's what happens when you don't know the language.
The context inside cloneItems is not a bean instance. Replace the arrow function with a regular one.
prev items:
<div v-for="item in items" :key="item">

This is what happens when you mindlessly copy-paste.
The title was changed, but the output data was forgotten.
this.items = [...this.items, Date.now()];

There is no need to create a new array, it is enough to push - calls to mutating methods are also tracked.
Well, if you still intend to continue to overwrite the entire array, then there is no need to make a copy - you can immediately follow the original, since it is replaced entirely.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question