gpt4 book ai didi

javascript - Vue watch() 输出相同的 oldValue 和 newValue

转载 作者:行者123 更新时间:2023-12-05 00:31:59 29 4
gpt4 key购买 nike

在做我的前端 Vue 项目时,当元素被插入 data 中的列表时,我需要执行某些步骤。 .但是,当我将一些初始值插入 mounted() 中的列表时, console.log()在相应的watch()newVal 输出相同的值和 oldVal参数值。
Javascript/Vue 代码:

let app = new Vue({
el: "#app",
data: {
testList: [],
},
mounted: function() {
this.testList.push('a');
this.testList.push('b');
this.testList.push('c');
},
watch: {
testList: {
handler: function(newVal, oldVal) {
console.log("new", newVal);
console.log("old", oldVal);
},
},
}
});
控制台日志信息:
Console logging information
  • 为什么newValoldVal保持相同的值(value)?
  • 为什么不是 watch()函数被执行了三次(因为我在 mounted() 中推送了三次)?
  • 最佳答案

    我改变了两件事

  • 在 watch 中进行克隆
  • 添加计算

  • 它现在工作正常。

    console.clear();

    let app = new Vue({
    el: "#app",
    data: {
    testList: ['old'],
    },
    mounted: function() {
    this.testList.push('a');
    this.testList.push('b');
    this.testList.push('c');
    },
    watch: {
    testListClone: { //<-- Edited
    handler: function(newVal, oldVal) {
    console.log("new", newVal);
    console.log("old", oldVal);
    },
    },
    },
    computed:{ //<-- Added
    clonedItems: function(){
    return JSON.parse(JSON.stringify(this.testList))
    }
    }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

    <div id="app"></div>

    关于javascript - Vue watch() 输出相同的 oldValue 和 newValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62729380/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com