这篇文章主要讲解了vue如何实现商品列表的添加删除,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

我们首先来看下代码:

<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如何实现商品列表的添加删除有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。