In pure JS it is possible to modify an Array in place:
a = ["a", "b"]
a.forEach((e, i, a) => {
a[i] = e + " hello"
})
console.log(a)
I tried to port this code to Vue but the modification does not happen:
new Vue({
el: "#app",
data: {
a: ["a", "b"]
},
mounted() {
this.a.forEach((e, i, a) => {
a[i] = e + " hello"
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
{{ a }}
</div>
Is it possible to make such modifications in reactive data in Vue?
In your case, I mean with the array mutation in place, you should use the beforeMount
lifecycle hook: since mounted
is executed after the DOM updates, you do not see the result of your forEach operation.
See the Lifecycle Diagram on the official documentation here.
However, as suggested in a comment above
"reactive" and "in place" don't play well together.
Make it immutable whenever it is possible. I mean something like:
new Vue({
el: "#app",
data: {
a: ["a", "b"]
},
beforeMount() {
this.a = this.a.map(x => x + " hello")
}
})