【问题标题】:Mutate a computed property with in a method in vue用 vue 中的方法改变计算属性
【发布时间】:2022-01-04 02:05:34
【问题描述】:

我有一系列年份 [2016,2017,2018,2019,2020,2021] 我用这个函数用computed得到当年的索引

getSelectedYearIndex(){
  return this.getYears.length - 1
},

这个函数返回 5

然后用select 选择跨过新的一年,并在methods 的这个函数中用$emit 接收新值

 onSelect({ selectedIndex }) {
  this.getSelectedYearIndex = selectedIndex
}

什么都没有发生。

是否有可能改变计算属性?

【问题讨论】:

  • 这意味着它不应该首先被计算。但这也取决于如果数组发生变化它应该如何表现。
  • 这是computed properties 的文档。请注意此声明... “默认情况下,计算属性仅限 getter”

标签: javascript vue.js vuejs2


【解决方案1】:

看来您需要使用另一个变量来存储所选索引的值。

// Added variable selectedYearIndex
let selectedYearIndex;
getSelectedYearIndex() {
    // Here I set the value of selectedYearIndex if it hasn't been been set yet
    if (this.selectedYearIndex === undefined) {
        this.selectedYearIndex = this.getYears.length - 1;
    }
    return this.selectedYearIndex;
}

然后就可以设置backing field的值了

onSelect({ selectedIndex }) {
   this.selectedYearIndex = selectedIndex
}

你的赋值没有做任何事情的原因是因为this.getSelectedYearIndex = selectedIndex 正在将this.selectedYearIndex 变成一个数字,而不是把值赋给一个变量。

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 2021-12-16
    • 2020-12-01
    • 2020-02-03
    • 2019-01-27
    • 2019-09-30
    • 1970-01-01
    • 2021-05-04
    • 2022-11-11
    相关资源
    最近更新 更多