【问题标题】:Unexpected behavior when use map inside computed property在计算属性中使用地图时的意外行为
【发布时间】:2019-10-18 15:25:33
【问题描述】:

我正在尝试更改计算属性中数据的值,但如果我使用 map 更改它,数据属性中的原始值也会更改。

我阅读了有关计算属性的文档,它不会改变原始值。

我阅读了有关地图的文档,它返回了一个带有更改的新对象。

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

【问题讨论】:

  • 你正在修改原始文本对象,查看here了解更多信息

标签: vue.js


【解决方案1】:

实际上,当您执行todo.text += ' - Changed' 时,您会改变实际对象。

你应该做的是首先做一个对象数组的深拷贝,然后改变这个拷贝。

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
        })
    },
  },
})

看到这个答案:https://stackoverflow.com/a/10869248/3956205

【讨论】:

  • 你是对的,如果地图内的数据发生变化,实际对象会得到变化。谢谢。
【解决方案2】:

返回一个改变旧对象的新对象。

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 }
        })
    },
  },
})

【讨论】:

    猜你喜欢
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2018-12-12
    • 2016-09-16
    • 2018-11-29
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多