简体   繁体   English

尝试拼接对象的最后一个元素时出现Vue2错误

[英]Vue2 error when trying to splice last element of object

I have a Vue2 app wit a list of items which I can choose and show, or delete. 我有一个Vue2应用程序,有一个项目列表,我可以选择,显示或删除。

When deleting the last element in the list (and only the last one) - I get Vue warn - "[Vue warn]: Error when rendering root instance: " 当删除列表中的最后一个元素(并且只删除最后一个元素)时 - 我得到Vue警告 - “[Vue warn]:呈现根实例时出错:”

my HTML: 我的HTML:

<body >
  <div id="app">
    <ul>
      <li v-for="(item, index) in list" v-on:click = "selectItem(index)" >
        <a>{{ item.name }}</a>
        <div v-on:click="deleteItem(index)">X</div>
      </li>
    </ul>
    <div>
     <span>{{selectedItem.name}}</span>
    </div>
  </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</body>

The JS: JS:

var app = new Vue({
      el: '#app',
      data: {
        index: 0,
        selectedItem: {},
        list : [
            { id: 1, name: 'org1', desc: "description1"},
            { id: 2, name: 'org2', desc: "description2"},
            { id: 3, name: 'org3', desc: "description3"},
            { id: 4, name: 'org4', desc: "description4"}
        ]

      },

      methods: {
        deleteItem: function(index) {
           this.list.splice(index,1);
        },
        selectItem: function(index) {
            this.selectedItem = this.list[index];
       },
      }
    })

Can you please advise why does this happen and how to solve this issue? 你能否告诉我为什么会这样,以及如何解决这个问题?

The problem is happening as you have having selectItem bind at li level, so event when you click cross button, selectItem gets executed and that same item gets deleted as well, causing this error. 问题出现了,因为你在li级别有selectItem绑定,所以当你单击交叉按钮, selectItem被执行并且同样的项目也被删除时,会发生此错误。

One way to solve this problem can be moving the selectItem binding inside li as follows 解决此问题的一种方法是将liselectItem绑定移动,如下所示

  <li v-for="(item, index) in list">
    <a v-on:click = "selectItem(index)" >{{ item.name }}</a>
    <div v-on:click="deleteItem(index)">X</div>
  </li>

See working fiddle . 看工作小提琴

Another approach can be when printing selectedItem.name in your HTML, you put a null check, whether selectedItem exist or not like following: 另一种方法是在HTML中打印selectedItem.name时,进行空检查,无论selectedItem是否存在,如下所示:

 <span>{{selectedItem && selectedItem.name}}</span>

See Working fiddle . 见工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM