解构赋值报错

组件中this.privacy是用mapState从state里面获取的数据 下面这样写一直报这个错 提示:Unexpected token我这个哪里写的不对?

组件中

data () {
    return {
      item1: '',
      item2: '',
      item3: '',
      item4: ''
    }
},
mounted () {
    if (this.privacy) {
      let { this.item1, this.item2, this.item3, this.item4 } = { ...this.privacy }
    }
  }

state里面的数据

privacy: {
    item1: 1,
    item2: 1,
    item3: 1,
    item4: 1
}

图片描述

阅读 6.4k
4 个回答
{ this.item1, this.item2, this.item3, this.item4 } = { ...this.privacy }

这里this.item1是什么?是个数字或者字符串之类的。
官方说了:

解构赋值语法是一个 Javascript 表达式,这使得可以将值从数组或属性从对象提取到不同的变量中。

注意后面,变量
this.item1取到的显然不是个变量。

1 . 左边与右边要有映射关系 你这 左边 this.item 跟右边怎么 映射
2 . 一般情况解构的左边要有声明 var let const,大括号开头会被解析成代码块 {xxx} 不是一个完整的表达式,要用 () 包起来

const o = {};

({name: o.n} = {name:'123'});

console.log(o); // {n:'123'}
...; // 此表达式需要添加一个分号
({ item1: this.item1, item2: this.item2, item3: this.item3, item4: this.item4 } = { ...this.privacy })

建议用Object.assign,非得这么写的话 就是这个({item1:this.item1}=this.privacy)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题