Watching array mutation using length #8912
Unanswered
TEAndyTirt
asked this question in
Help/Questions
Replies: 1 comment
-
<script lang="ts" setup>
import { ref, watch } from 'vue';
import type { Book } from './types';
const bookList = ref<Book[]>([]);
watch(
() => bookList.value,
(val, oldVal) => {
console.log('book list changed');
},
{ deep: true },
);
function changeBook() {
bookList.value = [/* ... */];
bookList.value[3] = { /* ... */ };
}
</script> |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello,
I have a question regarding array watching.
For context, currently we're in the process of migrating our product from Vue 2 to 3, and encounter some issues, but so far we managed to solve them. However, we have a doubt regarding array watching.
According to the migration guideline, we should use deep watcher to watch for array mutation. However, from our understanding, deep watcher means in case we have an array of objects, any changes done in the inner objects themselves (and by extension all nested objects under them), will also trigger the handler, and this is a behavior that will have negative performance impact for our app client.
To minimize the impact of that, we tried using deep watcher and compared the length between new value and old value. However, we found out that since there is no actual object replacement, both these values are actually referring to the same array.
After a few more testing, we found out that it's actually possible to just watch the array's length directly, and it will even return the correct new value and old value. This seems like and easier and more efficient approach for watching array's mutation.
So the question is, why is this not the recommended way to watch for array mutation, or there is no mention of it. Are there any specific reasons or caveats that we're not aware of?
Apologies for the long post and thank you for taking the time to answer.
Kind regards,
Andy
Beta Was this translation helpful? Give feedback.
All reactions