Vue系列之 => 全局,私有过滤器

时间:2023-12-04 16:43:50

私有过滤器也称局部过滤器

 <script>
// 全局过滤器
Vue.filter("datatime",function(timestr){
var tm = new Date(timestr);
var yy = tm.getFullYear();
// ES6新方法padStart,填充两位,以0填充。
var mm = (tm.getMonth() + 1).toString().padStart(2,"0");
var dd = tm.getDate().toString().padStart(2,"0");
var hh = tm.getHours().toString().padStart(2,"0");
var min = tm.getMinutes().toString().padStart(2,"0");
var ss = tm.getSeconds().toString().padStart(2,"0");
return `${yy}-${mm}-${dd} ${hh}:${min}:${ss}`
}) var vm = new Vue({
el: "#app",
data: {
id : "",
name : "",
keywords : "",
list: [{
id: 1,
name: "nameA",
Ctime: new Date()
},
{
id: 2,
name: "nameB",
Ctime: new Date()
},
{
id: 3,
name: "nameC",
Ctime: new Date()
},
{
id: 4,
name: "nameD",
Ctime: new Date()
},
]
},
methods: {
add(){
add_dict = {id : this.id , name : this.name , Ctime : new Date()};
this.list.push(add_dict);
this.id = this.name = "";
},
del(id){
// this.list.some( (item,index) => {
// if(id == item.id){
// this.list.splice(index,1);
// }
// })
var index = this.list.findIndex(item => {
if(item.id == id){
return true;
}
});
this.list.splice(index,1);
},
search(keyword){
return new_list = this.list.filter( item => {
if(item.name.includes(keyword)){
return item;
}
})
}
},
// 局部过滤器
filters : {
time : function(timestr){
var tm = new Date(timestr);
var yy = tm.getFullYear();
var mm = tm.getMonth() + 1;
var dd = tm.getDate();
var hh = tm.getHours();
var min = tm.getMinutes();
var ss = tm.getSeconds(); return `${yy}-${mm}-${dd} ${hh}:${min}:${ss}`
}
}
})
</script>