Unexpected side effect in a computed property
Have you ever received this error message when you try to write a computed property in your Vue apps and you are wondering why it happens?
Cause
The reason it happens is you're mutating the original data.
Example
For example, I have a Vue component that received an Array as a prop. The component needs to reverse the order of the array. What I do is write a computed
property and reverse the state that is coming from the props.
<template>
<ul v-for="command in reverseCommandOrder" :key="command.id">
<li>{{ command.text }}</li>
</ul>
</template>
<script>
export default {
props: {
commands: {
type: Array,
required: false,
default: () => []
}
},
computed: {
reverseCommandOrder() {
return this.commands.reverse()
}
}
}
</script>
As expected, I received the error. Why? Because I changed the original value of the props. It could be in terms of the order, value, key, etc.
In this case, I changed the order of the element in the array.
How to fix it
We will create a copy of the array and reverse it. We don't want the original value to be affected.
So we can utilize the spread operator to do a clone.
<template>
<ul v-for="command in reverseCommandOrder" :key="command.id">
<li>{{ command.text }}</li>
</ul>
</template>
<script>
export default {
props: {
commands: {
type: Array,
required: false,
default: () => []
}
},
computed: {
reverseCommandOrder() {
return [...this.commands].reverse()
}
}
}
</script>
Other way is , you can use JSON.parse(JSON.strigify(this.commands))
or Lodash method of deepClone.
Hope this explanation able to solve your problem.