【问题标题】:How to pass Vue JS 'this.somestate' as a literal 'this.somestate'如何将 Vue JS 'this.somestate' 作为文字'this.somestate' 传递
【发布时间】:2020-08-20 16:34:49
【问题描述】:

假设在一个 Vue JS 应用程序中,我有一些状态

data () {
    optionA: {
        xaxis: { categories: ['DD'] }
    }
}

还有一个像这样使用状态作为参数的方法:

modifyOption (optionName, xAxisCategory, dataLabelsEnabled) {
  optionName = {
    ...optionName,
    ...{
      xAxis: { categories: xAxisCategory },
      dataLabels: { enabled: dataLabelsEnabled }
    }
  }
}

注意optionName 参数,它应该是一个状态名称,例如当该方法被调用时

this.mofifyOption(this.optionA, 'DD MMM', true)

我希望它运行为

modifyOption (this.optionA, 'DD MMM', true) {
  this.optionA = {
    ...this.optionA,
    ...{
      xAxis: { categories: 'DD MMM' },
      dataLabels: { enabled: true }
    }
  }
}

我不希望 this.optionA 的值,只是文字 this.optionA。有没有办法做到这一点?

【问题讨论】:

    标签: javascript vue.js methods this


    【解决方案1】:

    不,没有。最好和最简单的解决方案是返回新对象:

    modifiedOption(option, xAxisCategory, dataLabelsEnabled) {
      return {
        ...option,
        xAxis: { categories: xAxisCategory },
        dataLabels: { enabled: dataLabelsEnabled },
      };
    }
    

    被称为this.optionA = this.modifiedOption(this.optionA, 'DD MMM', true);

    另一种方法是将属性名称(字符串)作为参数传递并使用括号语法访问属性:

    modifyOption(name, xAxisCategory, dataLabelsEnabled) {
      this[name] = {
        ...this[name],
        xAxis: { categories: xAxisCategory },
        dataLabels: { enabled: dataLabelsEnabled },
      };
    }
    

    被称为this.modifiedOption('optionA', 'DD MMM', true);

    【讨论】:

    • 嗨!感谢您的回答。我刚刚尝试了您的解决方案,第二个解决方案看起来很有希望。但不幸的是我收到了这个错误Possible Unhandled Promise Rejection: TypeError: i.reduce is not a function
    • @loremdimsum 这不是来自此问题/答案中的代码。
    • 哦,对了,这个错误来自我使用的库。但是您的代码可以正常工作,谢谢!
    猜你喜欢
    • 2021-04-25
    • 2022-01-25
    • 2021-02-24
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多