Vue.js增删案例

品牌管理案例
数据的增删
<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">添加品牌</h3>
    </div>
    <div class="panel-body form-inline">
        <label>
            Id:<input type="text" v-model="id">
        </label>
        <label>
            Name:<input type="text" v-model="name">
        </label>
        <input type="button" value="添加" class="btn btn-primary" @click="add"/>
    </div>
</div>

<table class="table table-bordered table-hover table-striped">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Ctime</th>
            <th>Operation</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="item in list" :key="item.id">
            <td>{{item.id}}</td>
            <td v-text="item.name"></td>  
            <td>{{item.ctime}}</td>
            <td>
                <a href="" @click.prevent="del(item.id)">删除</a>
            </td>
        </tr>
    </tbody>
</table>

var vm=new Vue({
    el:'#app',
    data:{
        id:'',   总结,当v-model绑定数据时,要在data中声明
        name:'',
        list:[
           {id:1,name:'奔驰',ctime: new Date()},{id:2,name:'宝马',ctime: new Date()}
        ]
    }
    methods:{
        add(){
            //1:获取到id和name,直接从data上获取
              2:组织个对象
              3:把这个对象通过调用数组的相关方法,添加到data的list中
            var car={id:this.id,name:this.name,ctime:new Date()}
            this.list.push(car);
            this.id='',
            this.name=''
        }

        del(id){ 根据id来删除数据
        //分析:1如何根据id,找到要删除的这一项的索引
         2如果找到索引了,直接调用数组的splice方法
            this.list.some((item,i)=>{
                if(item.id==id){
                    this.list.splice(i,1);
            //在数组的some方法中,如果return ture,就会立即终止这个数组的后续循环
                    return true;
                }
            })


            this.list.findIndex(item=>{
                if(item.id==id){
                   return true;     
                }
            })
            console.log(index);
            this.list.splice(index,1);
        }
    }
})

总结
1:在Id和Name的输入数据时,要用v-model来绑定,记得在data中加上id:”,name:”
2:添加操作的步骤,删除操作的步骤

通过关键字实现数组过滤

之前,v-for中的数据都是直接从data上的list中直接渲染过来的
现在,我们自定义了一个search方法,同时把所有的关键家,都通过传参的形式
传递给search方法
在search方法内部,通过执行for循环,把所有符合搜索关键字的数据,保存到一个新数组中,返回

<tr v-for="item in search(keywords)" :key="item.id">

search(keywords){
    var newList=[];
    this.list.forEach(item=>{
        if(item.name.indexOf(keywords)!=-1){
            newList.push(item);
        }
    })
    return newList;
}

//注意:数组的新方法 forEach some filter findIntext 都会对数组中的每一项继续遍历,执行相关操作

return this.list.filter(item=>{
    if(item.name.includes(keywords)){
        return item;
    }
})

var newList=this.list.filter(item=>{
    if(item.name.includes(keywords)){
        return item;
    }
    return newList;
})

猜你喜欢

转载自blog.csdn.net/a3060858469/article/details/80632511
今日推荐