2017-09-02 147 views
0

我在Vue.js中创建一个自定义组件。在我的组件中,我有一个列表,其中包含一个删除按钮。单击一个按钮时,它将删除该行。如果单击任何行,它将删除最后一行,因为索引为什么总是-1? 这里是我下面整个代码代码 https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview为什么index-of在vuejs中无法正常工作?

methods: { 
     deleteTodo:function (item) { 
      console.log(item) 
      var index = this.items.indexOf(item); 
      this.items.splice(index, 1); 
     } 
    } 

var MyComponent = Vue.extend({ 
    template:'#todo-template', 
    props:['items'], 
    computed: { 
     upperCase: function() { 
      return this.items.map(function (item) { 
       return {name: item.name.toUpperCase(),complete:item.complete}; 
      }) 
     } 
    }, 
    methods: { 
     deleteTodo:function (item) { 
      console.log(item) 
      var index = this.items.indexOf(item); 
      this.items.splice(index, 1); 
     } 
    } 
}) 
Vue.component('my-component', MyComponent) 

var app = new Vue({ 
    el: '#App', 
    data: { 
     message: '', 
     items: [{ 
      name: "test1", 
      complete:true 
     }, { 
      name: "test2", 
      complete:true 
     }, { 
      name: "test3", 
      complete:true 
     }] 
    }, 
    methods: { 
     addTodo: function() { 
      this.items.push({ 
       name:this.message, 
       complete:true 
      }); 
      this.message =''; 
     }, 
    }, 
    computed: { 
     totalCount:function() { 
      return this.items.length; 
     } 
    } 
}); 

回答

0

你的代码是假设如果它返回-1的indexOf会返回一个有效的索引

deleteTodo:function (item) { 
     console.log(item) 
     var index = this.items.indexOf(item); 
     this.items.splice(index, 1); 
    } 

,这意味着它不在列表中找到item。很可能this.items不是你认为的那样。

的防御性代码有一点会帮助你解决这个问题:

deleteTodo:function (item) { 
     console.log(item) 
     var index = this.items.indexOf(item); 
     if (index === -1) 
      console.error("Could not find item "+item in list: ",this.items); 
     else 
      this.items.splice(index, 1); 
    } 

这将告诉你什么this.items是在控制台输出

0

不是传递整个对象,你应该通过指数的项目。

更改for循环

<li v-for="(item, index) in upperCase" v-bind:class="{'completed': item.complete}"> 
     {{item.name}} 
     <button @click="deleteTodo(index)">X</button> 
     <button @click="deleteTodo(index)">Toggle</button> 
</li> 

和删除功能

deleteTodo:function (itemIndex) { 
    this.items.splice(itemIndex, 1); 
} 

更新的代码:Link

相关问题