【问题标题】:pass a variable inside an array to update that variable dynamically - in Vue.js在数组中传递一个变量以动态更新该变量 - 在 Vue.js 中
【发布时间】:2017-08-02 05:51:51
【问题描述】:

我正在尝试动态更改变量,以免使用太多 switch 语句。我希望这样做:

this.variable1 = 2
this.variable2 = 3

var array1 = [this.variable1, this.variable2]

然后再做

array1[0] = 25
array1[1] = 12

console.log(array1[0]) //would output 25
console.log(array1[1]) // would output 12

当然,这不是正常的情况,但我怎样才能动态地实现呢?我肯定有办法。

【问题讨论】:

  • 会发生什么?请添加完整代码。
  • 我该如何改进这个问题。我被禁止了,但我似乎无法解决这个问题。
  • 您可以从不忽略要求更多信息的 cmets 开始。
  • 当然,但没有其他代码可以显示,这是我试图理解的示例。为什么我会因为无法提供的东西而受到惩罚?
  • 但是您发布的示例完全符合您的要求。所以没有人能够重现这个问题,因此你被要求提供观察到的行为和你的确切代码(不仅仅是一个错误的例子)。

标签: javascript vue.js vuejs2


【解决方案1】:

我想这就是你要找的东西:http://jsfiddle.net/yMv7y/3067/

var array1
var demo = new Vue({
  el: '#demo',
  data: {
    variable1: 2,
    variable2: 3
  },
  mounted() {
    array1 = [this.variable1, this.variable2]
  },
  methods: {
    test() {
      array1[0] = 25
      array1[1] = 12

      console.log(array1[0]) //would output 25
      console.log(array1[1]) // would output 12
    }
  }
})

【讨论】:

  • 你好,Potray,好的,所以我没有明白情况的微妙之处。您的答案是正确的,实际上我的问题与我意识到的不同。我也试图以这种方式从数组中访问文本字段。 var demo = new Vue({ el: '#demo', data: { textfield_phone: 'phonetextfield', }, methods: { selecttextfield1() { this.focusInput(this.textfield_phone, 1000) //这有效 }, } } )
  • 我没有弄明白情况的微妙之处。您的答案是正确的,实际上我的问题与我意识到的不同。我也试图以这种方式从数组中访问文本字段。 variable1: false, function1() { this.variable1 = true //这当然可以 console.log(this.variable1) prints true }, function2() { var temparray1 = [this.variable1] temparray1[0] = true / /不像我想要的那样工作,它是数组中的值发生了变化,而不是 this.variable1 console.log(this.variable1) //prints still false console.log(temparray1[0]) //prints true
  • Potray,那么你如何解决这个在javascript中指向对象的问题呢?当您可以提供说明时,您通常不需要在js中创建某种表格吗?我的意思是如果你有这个结果改变这个变量。一个表将是完美的,而不是一个大的 switch 语句。
  • 如果您需要解决其他问题,请发布另一个问题。我无法真正理解您评论中的代码,因为有些 cmets 我看不到它们的结尾。
  • 我怎样才能改进这个问题以摆脱我的禁令,当我试图提出一个真正的问题时,我得到了一个-1。
猜你喜欢
  • 2020-08-08
  • 2023-01-19
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 2020-07-23
  • 2016-11-24
相关资源
最近更新 更多