vuejs2:事件发生时重置变量

vuejs2 : reset variable when a event happened

我需要在 vuejs2 中发生事件时重置一个变量

这里我的代码有两个函数:"add" 和 "reset": https://jsfiddle.net/uo19p71m/

var ggroupc = [
    {id: 1, country: "Francia", pj: 0, pg: 0, pe: 0, pp: 0, gf: 0, gc: 0, dg: 0, pt: 0},
    {id: 2, country: "Australia", pj: 0, pg: 0, pe: 0, pp: 0, gf: 0, gc: 0, dg: 0, pt: 0},
    {id: 3, country: "Peru", pj: 0, pg: 0, pe: 0, pp: 0, gf: 0, gc: 0, dg: 0, pt: 0},
    {id: 4, country: "Dinamarca", pj: 0, pg: 0, pe: 0, pp: 0, gf: 0, gc: 0, dg: 0, pt: 0}
];

var app = new Vue({
    el: '#app',
    data: {
        challenges: [[1, 2], [3, 4], [1, 3], [2, 4], [1, 4], [2, 3]],
        groupc: ggroupc
    },
    methods: {
        add: function () {
            this.groupc[0].pj++;
            this.groupc[1].pg++;
            this.challenges[0][0]++;
        },
        reset: function () {
            this.groupc = ggroupc;
        }
    }
});

我想重置 "groupc" 变量但不想 "challenges" 变量。

有什么想法吗?

数组在JavaScript中不是按值赋值,而是按引用赋值。这个很重要。举个例子:

var array_original = ['a', 'b', 'c'];
var array_copy = array_original;

array_copy[0] = 'd';

您所做的似乎假设 array_original 仍将包含 ['a', 'b', 'c'],但它实际上将包含 ['d', 'b', 'c'],就像 array_copy 一样!

如果你想修复你的代码,你将需要显式克隆数组。此外,您需要确保将其设为深度克隆,否则出于同样的原因您仍然会遇到内部对象的问题!

使用 jQuery 的深度克隆示例:

var array_original = ['a', 'b', 'c'];
var array_copy = $.extend(true, [], array_original);

如果您不想使用 jQuery,请对对象数组的深度克隆做一些额外的研究。或者,不要在全局范围内定义 ggroupc——而是在本地分配这些值并使用 mounted 生命周期挂钩!

var app = new Vue({
  el: '#app',
  data: {
    challenges: [[1,2],[3,4],[1,3],[2,4],[1,4],[2,3]],
    groupc : ggroupc
  },
  mounted: function() {
    this.reset();
  },
  methods: {
    add : function() {
      this.groupc[0].pj++;
      this.groupc[1].pg++;
      this.challenges[0][0]++;
    },
    reset : function() {
      this.groupc = [
        {id:1, country:"Francia", pj:0, pg:0, pe:0, pp:0, gf:0, gc:0, dg:0, pt:0},
        {id:2, country:"Australia", pj:0, pg:0, pe:0, pp:0, gf:0, gc:0, dg:0, pt:0},
        {id:3, country:"Peru", pj:0, pg:0, pe:0, pp:0, gf:0, gc:0, dg:0, pt:0},
        {id:4, country:"Dinamarca", pj:0, pg:0, pe:0, pp:0, gf:0, gc:0, dg:0, pt:0}
      ];
    }
  }
});

因为变量是link到内存中的某个地方

你必须清除计数器

查看更正 fiddle https://jsfiddle.net/simati/h6dt3t6n/

*我还添加了使用 Object.assign() 创建新对象,也许你需要它

例如:

  1. 打开控制台 (chrome: ctr + shift + i)
  2. 点击按钮登录查看结果
  3. 单击按钮 添加 然后单击按钮 log 查看结果
  4. 单击按钮 重置 然后单击按钮 log 查看结果

更新:

方法Object.assign()无效,已更改为JSON.parse(JSON.stringify())

也重新设计了方法 resetIndex() 以在原始计数器上重置