【问题标题】:Unable to copy an array to an array using vue.js无法使用 vue.js 将数组复制到数组
【发布时间】:2020-10-29 08:04:56
【问题描述】:

我有一个使用 vuetify 选择组件的多选框。我正在获取选定项目的数组,我想将状态合并为选定项目的真实状态,例如[ { "ward": 1, "status": true }, { "ward": 2, "status": true} ] 我正在尝试将选定的数组项复制到另一个数组但无法成功。在控制台中,我得到了如下所示的 selectedFruits。

 methods: {
    save() {
      console.log(this.selectedFruits);
      debugger;    
      this.selectedIndex.push({ ward: this.selectedFruits, status: true });
      console.log(this.list);
    },

【问题讨论】:

  • 何时调用 save 方法,this.selectedfruitsthis.list 包含什么
  • 当我从 selectbox 中选择并提交表单时,会调用 save 方法。 @deceze
  • 你想要[ { "ward": 1, "status": true }, { "ward": 2, "status": true} ] in this.list 吗?

标签: vue.js vuetify.js


【解决方案1】:

你可以试试这个

save(){
  this.list = []
  this.selectedFruits.forEach(e => {
      this.list.push({ ward: e, status: true });
    });
    console.log(this.list)
}

【讨论】:

    【解决方案2】:

    如果你想复制一个数组或对象而不通过引用传递它,这样做

    const newArray = JSON.parse(JSON.stringify(oldArray));
    

    【讨论】:

      【解决方案3】:

      您可以为此使用Spread-Operator

      这里是一个例子:

      const existingArr = [{ hi: 'foobar' }];
      const arr = [{ a: 'foo', b: 'bar'}, { a: 'hello',  b: 'world'}]
      const newArr = [...existingArr, ...arr]
      
      console.log(newArr)

      【讨论】:

      • 当我执行 const newData = [({ ward: this.selectedFruits, status: true })] 时,我得到的 newData 未定义。 @S.Visser
      • 为什么里面有( )
      • 当我删除 ( ) 时,我仍然不确定。 @S.Visser
      • 请用一个例子做一个jsfiddle。
      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多