【问题标题】:Vue - Destructuring object to this (data) [duplicate]Vue - 解构对象到这个(数据)[重复]
【发布时间】:2020-11-06 12:55:02
【问题描述】:

如何对我的 Vue 组件数据使用对象解构? 这是我的实际代码:

data: () => ({
  descricao: '',
  perfilBase: null,
  anotherField: '',
  otherOne: false
}),

mounted () {
  this.descricao = this.$route.query.descricao
  this.perfilBase = this.$route.query.perfilBase
}

我怎么能这样呢?有可能吗?

mounted () {
  { this.descricao, this.perfilBase } = ...this.$route.query
}

【问题讨论】:

  • 尝试去掉this前面的'...'。$route.query

标签: javascript vue.js ecmascript-6 destructuring


【解决方案1】:

要对简单变量以外的目标使用解构,您不能使用简写语法,但需要明确指定解构后的属性名称。在你的情况下:

mounted () {
  ({ descricao: this.descricao, perfilBase: this.perfilBase } = this.$route.query);
}

但是,如果 query 对象只包含这两个属性,Object.assign 是一个更简单的解决方案:

mounted () {
  Object.assign(this, this.$route.query);
}

【讨论】:

  • 我认为第一个示例在从一种案例样式更改为另一种案例样式时会很有用,如下所示:({ order_number: this.orderNumber, order_amount: this.orderAmount } = this.config);
【解决方案2】:

我认为没有一种方法可以像你想要的那样简洁。

你能做的最好的事情可能是

mounted () {
   const { descricao, perfilBase } = this.$route.query
   this.descricao = descricao
   this.perfilBase = perfilBase
}

【讨论】:

    【解决方案3】:

    检查这是否有效,我现在不在电脑后面。

    { a, b } = this.$route;
    [ this.a, this.b ] = [a, b];
    

    【讨论】:

    • 这确实有效,我验证了它。
    • 我必须声明才能在 chrome 上完成这项工作。 const { a, b } = this.$route;
    • 是的,你是对的@JamieMarshall
    • 它是两行而不是一行,但数组语法阻止您为提取的每个属性编写赋值。
    • @GiorgioTempesta 从技术上讲,第一行可以像这样[this.a, this.b] = [this.$route.a, this.$route.b] 与第二行结合使用,但我更喜欢两行版本
    猜你喜欢
    • 2016-05-11
    • 1970-01-01
    • 2021-03-28
    • 2019-09-25
    • 1970-01-01
    • 2020-04-11
    • 2021-01-17
    • 1970-01-01
    • 2018-04-12
    相关资源
    最近更新 更多