2017-09-02 134 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

相關問題