1

I'm trying to change the value of the data within computed property, but if I use map to change it, the original value in data property changed too.

I read documentation about computed property and it don't change original value.

I read documentation about map and it return a new object with the changes.

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  computed: {
    todos_computed() {
        return this.todos.map((todo) => {
        todo.text += ' - Changed'
        return todo
        })
    },
  },
})

jsfiddle : https://jsfiddle.net/hkqm6f30/1

BTL
  • 4,311
  • 3
  • 24
  • 29
  • You are modyfing the original text object, look [here](https://stackoverflow.com/a/35922654/10781526) for further information – Andreas Oct 18 '19 at 15:46

2 Answers2

1

Actually when you do todo.text += ' - Changed' you mutate the actual object.

What you should do is first do a deep copy of the array of object and then mutate this copy.

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  computed: {
    todos_computed() {
        const todos = JSON.parse(JSON.stringify(this.todos))
        return todos.map((todo) => {
        todo.text += ' - Changed'
        return todo
        })
    },
  },
})

See this SO answer : https://stackoverflow.com/a/10869248/3956205

BTL
  • 4,311
  • 3
  • 24
  • 29
1

Return a new object insted of mutating the old one.

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript", done: false },
      { text: "Learn Vue", done: false },
      { text: "Play around in JSFiddle", done: true },
      { text: "Build something awesome", done: true }
    ]
  },
  computed: {
    todos_computed() {
        return this.todos.map((todo) => {
        return { text: todo.text + ' - Changed', done: todo.done }
        })
    },
  },
})
artoju
  • 1,612
  • 12
  • 12