How can I make a value in Vue.js non-reactive?
In my Vue.js app, I have an array value that should only be updated when a user completes a specific "refresh" action. However, as soon as I assign a new value to that array value, the array value becomes reactive and changes instantly as the data in the assigned value changes. The array value should remain un-reactive.
For example, I have a method, refresh()
, which when triggered is meant to update displayedData
, which should not be reactive, with currentData
, which should be reactive. displayedData
should only update when refresh is called.
methods: {
refresh: function() {
this.displayedData = this.currentData;
}
}
Solution 1:
To make a value not reactive without making it static, you can make a "copy" of it by using JSON to encode and then decode it.
this.displayedData = JSON.parse(JSON.stringify(this.currentData));
This assigns the current state of one value to another value, and no changes to the first value will change the second value until this code is triggered again.
Solution 2:
If you DON'T add the currentData to the data() method then it will not be reactive.
export default {
currentData: [],
data() {
return {
}
},
methods: {
refresh: function() {
this.displayedData = this.currentData;
}
}
}
You can then still reference currentData in the section using {{ $options.currentData }}
Solution 3:
An approach (WITHOUT disabling reactivity) is to use a different array for your temporary data and move stuff over in to the good array when the user presses refresh.
You could copy the values in the first array into the temp array like this.temp = this.permanent.slice()
in the created
or mounted
life-cycle function.
Slice would make a shallow copy of the array. If you need to also clone the items in the array, then maybe use some deep copy library or the JSON.parse(JSON.stringify(...))
method.