Vue對List的刪除和新增操作


 Vue對List的刪除操作

var vm = new vue({
    el: '#app'
    data: {
        id: ' ',
        name: ' ',
        list: [
            { id : 1, name : '奔馳', ctime: new Date() },
            { id : 2, name : '寶馬', ctime: new Date() }
        ]
    },
    methods: { 
        delete(id) { //根據傳入的ID來刪除數據
            // 1.根據ID來找到要刪除的這一項的索引
            // 2. 找到索引后,調用數組的splice方法
            // 方法一
            this.list.some((item, i) => {
                if (item.id == id ){
                        this.list.splice(i,1)
                        // 在數組的some方法中,如果return true,就會立即終止這個數組的后續循環,所以相比較foreach,如果想要終止循環,那么建議使用some
                        return true;
                }
            })
            // 方法二
            var index = this.list.findIndex(item => {
                if ( item.id == id) {
                    return true;
                    }
        })
            this.list.splice(index,1)
        }
        // 方法三(不推薦,因為無法被終止)
        this.list.forEach(item => {
            if (item.id == id){
                this.list.splice(i,1)
            }
        })
    }    
})

Vue對List的新增操作

var car = { id : this.id, name: this.name}
    this.list.push(car)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM