vue.js - vuejs2.0 多维数组操作?

查看:523
本文介绍了vue.js - vuejs2.0 多维数组操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

不知道为什么vue操作多维数组的时候,删除一个,所有的删除掉了.
html 如下

<div class="form-group" v-for='(tech,fatherIndex) in techs'>
    <tr v-for='(item,childIndex) in tech.items' @remove='console.log(childIndex)'>
        <td>
            <input type='checkbox' v-bind:true-value="2" v-bind:false-value="1" v-model='item.outside'>
        </td>
        <td>
              <a @click="$emit('remove')" class='btn btn-danger'>移除</a>
              <a @click="createItem(fatherIndex)" class='btn btn-success'>{{fatherIndex}} - {{childIndex}}新增</a>
        </td>
   </tr>
</div>


js代码如下

var app = new Vue({
  el: '#techs',
  data: {
      catTpl : {
          catId:0,
          items:[
              {
                  techId:0,
                  deviceId:0,
                  skillId:0,
                  receiveMemo:'',
                  workingMemo:'',
                  finishMemo:'',
                  ousite:1,
                  check:1
              }
          ],
      },
      itemTpl : {
          techId:0,
          deviceId:0,
          skillId:0,
          receiveMemo:'',
          workingMemo:'',
          finishMemo:'',
          ousite:1,
          check:1
      },
      catId:100,
      itemId:1000,
    techs : [
        {
            catId:1,
            items:[
                {
                    techId:1,
                    deviceId:1,
                    skillId:1,
                    receiveMemo:'',
                    workingMemo:'',
                    finishMemo:'',
                    outside:1,
                    check:1
                },
            ]
        },
    ]
  },
  methods: {
        addCategory:function(){
            this.techs.push(this.catTpl)
        },
        removeCategory:function(fatherIndex){
            this.techs.splice(fatherIndex,1)
        },
        removeItem:function(fatherIndex,sonIndex){
            this.techs[fatherIndex].items.splice(sonIndex,1)
        },
        createItem:function(fatherIndex){
            this.techs[fatherIndex].items.push(this.itemTpl)
        }
    }
})

父类的增减没有问题, 但是在父类下面增加子类的时候, 除了初始化的techs数据,增加的都会同步操作,如在console 运行如下代码 app.techs[1].items.push(this.itemTpl) ,所有的动态添加的父类都会自动加上一个子类。
app.techs[1].items.splice(sonIndex,1) 所有动态父类下的子类都会删除这个对象。
请问这是什么原因, 先行谢过!

代码演示

父类和子类都在上面注明了. 之前可能说的不大清楚

解决方案

因为你的push操作的和splice操作的都是同一个对象

这篇关于vue.js - vuejs2.0 多维数组操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆