过滤器
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <script src="js/mui.min.js"></script> <link href="css/mui.min.css" rel="stylesheet"/> </head> <body> <header class="mui-bar mui-bar-nav"> <h1 class="mui-title">自己没事写个vue双向绑定表格</h1> </header> <div class="mui-content"> <div id="app"> <div class="mui-row" style="margin-top: 10px;"> <div class="mui-col-sm-2 mui-col-xs-2"> <label>Id: <input v-model="id" type="text" style="height: 30px; 60%;text-align: left;"></label> </div> <div class="mui-col-sm-4 mui-col-xs-4"> <label>name:<input v-model="name" type="text" style="height: 30px; 50%;"></label> </div> <div class="mui-col-sm-2 mui-col-xs-2"> <input type="button" value="Add" @click="add()" style="background-color: cornflowerblue;"> </div> <div class="mui-col-sm-4 mui-col-xs-4"> <label style="margin-left: -5px;">Search:<input v-model="keywords" type="text" style=" 50%;height: 30px;"></label> </div> </div> <table border="1" style="margin: 0 auto;"> <caption>数据展示 <tr> <th>ID</th> <th>Name</th> <th>Creatime</th> <th>Operation</th> </tr> <tr v-for="item in search(keywords)" :key="item.id"> <td>{{item.id}}</td> <td v-text="item.name"></td> <td>{{item.ctime | dateFormat()}}</td> <td><a href="" @click.prevent="del(item.id)">Delete</a></td> </tr> </caption> </table> </div> <div id="app2"> <h3 style=" 100%;"> {{dt | dateFormat('')}} </h3> </div> </div> <script src="js/vue.js"></script> <script type="text/javascript" charset="utf-8"> mui.init(); //全局过滤器--进行时间的格式化 Vue.filter('dateFormat',function(dateStr){ var dt = new Date(dateStr) var y = dt.getFullYear() var m = dt.getMonth()+1 var d = dt.getDate() //return y+"-"+m+"-"+d //这个不是英文半角引号,是左上角那个1旁边那个符号撇号 return `${y}-${m}-${d}` }) var vm = new Vue({ el:'#app', data:{ id:"", name:"", keywords:"", list:[ {id:1,name:"宝马",ctime:new Date()}, {id:2,name:"奔驰",ctime:new Date()}, ] }, methods:{ add(){ var car = {id:this.id,name:this.name,ctime:new Date()} this.list.push(car) this.id=this.name='' }, del(id){ this.list.some((item,i)=>{ if(item.id==id){ this.list.splice(i,1) return true; } }) }, search(keywords){ var newList = [] this.list.forEach(item=>{ if(item.name.indexOf(keywords)!=-1){ newList.push(item) } }) return newList } } }); //定义一个自有的过滤器 var vm2 = new Vue({ el:'#app2', data:{ dt: Date() }, methods:{ }, //定义私有的过滤器 filters:{ dateFormat:function(dateStr,pattern) { var dt = new Date(dateStr) var y = dt.getFullYear() var m = (dt.getMonth()+1).toString().padStart(2, '0') //用String的padStart方法补齐 var d = (dt.getDate()).toString().padStart(2,'0') if (pattern.toLowerCase()=='yyyy-mm-dd') { return `${y}-${m}-${d}` }else { var hh = dt.getHours() var mm = dt.getMinutes() var ss = dt.getSeconds() return `${y}-${m}-${d} ${hh}:${mm}:${ss} 私有` } } } }) </script> </body> </html>