vue实现商品列表的添加删除实例讲解

Faye ·
更新时间:2024-09-20
· 938 次阅读

我们首先来看下代码:

<div id="app"> <div class="container"><form class="form-inline"> <div class="form-group"><label for="exampleInputName2">ID:</label> <input id="exampleInputName2" class="form-control" type="text" /></div> <div class="form-group"><label for="exampleInputEmail2">Name:</label> <input class="form-control" type="text" /></div> <button class="btn btn-primary" type="button">提交</button></form> <table class="table table-hover table-striped"> <tbody> <tr> <td>ID</td> <td>品牌名称</td> <td>添加时间</td> <td>操作</td> </tr> <tr> <td>{{item.id}}</td> <td>{{item.pp_name}}</td> <td>{{item.add_time | getTime()}}</td> <td><a>删除</a></td> </tr> </tbody> </table> </div> </div> <script type="text/javascript">// <![CDATA[ var app = new Vue({ el: '#app', data: { id : '', name : '', list : [ {id : 1, pp_name : '安踏', add_time : new Date()}, {id : 2, pp_name : '李宁', add_time : new Date()}, {id : 3, pp_name : '捷豹', add_time : new Date()}, {id : 4, pp_name : '悍马', add_time : new Date()} ] }, methods: { add : function(){ // 数据插入数组操作 this.list.push({id : this.id, pp_name : this.name, add_time : new Date()}); this.id = this.name = '' }, /* 根据id删除数据 分析: 先要找到这一项数据的id,然后根据id删除索引 找到索引之后直接调用数组的splice方法 */ del : function(id){ this.list.some((item,i) =>{ if(item.id === id){ this.list.splice(i,1); // 在数组some中 如果返回值为true,则会立即终止后续的循环 return true; } }) } }, // 时间的过滤 filters:{ getTime:function(value){ let date = new Date(value), Y = date.getFullYear(), m = date.getMonth() + 1, d = date.getDate(), h = date.getHours(), min = date.getMinutes(), s = date.getSeconds(); if(m<10){m = '0' +m;} if(d<10){d = '0' +d;} if(h<10){h = '0' +h;} if(min<10){min = '0' +min;} if(s<10){s = '0' +s;} let t = Y + '-' + m + '-' + d + ' | ' + h + ':' + min + ':' + s; return t; } } }) // ]]></script>

内容补充:

vue中注册组件,实现列表的添加删除效果

1、首先在html的<code><head>标签中</code>导入vue.js

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

2、在body中创建一个应用vue模板的容器

// vue起作用的区域root <div id="root"> // input与mesg数据绑定 <input v-model="mesg" /> <button @click="handle">提交</button> <ul> <todo-item v-for='(item,index) in list' :key='index' :index='index' :content='item' @delete='deletes'></todo-item> </ul> </div>

3、在script标签中创建并注册名为todo-item的组件

Vue.component('todo-item', { props: ['content', 'index'], template: '<li @click="handelClick">{{content}}</li>', methods: { handelClick: function() { //点击li元素就触发delete方法 this.$emit('delete', this.index); } } })

4、在script标签中初始化vue实例

new Vue({ el: '#root', data() { return { list: [], mesg: '' } }, methods: { //点击提交按钮,输入文本信息就加入列表 handle: function() { if(this.mesg==''){ return; } this.list.push(this.mesg); this.mesg = '' }, deletes: function(index) { alert(index) this.list.splice(index, 1); } } })

到此这篇关于vue实现商品列表的添加删除实例讲解的文章就介绍到这了,更多相关vue商品列表添加删除内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



VUE 商品列表 列表

需要 登录 后方可回复, 如果你还没有账号请 注册新账号