过滤器
定义:
对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)
语法:
1.注册过滤器:Vue.filter(name,callback) 或 new Vue(filters:{})
2.使用过滤器:{{xxx | 过滤器名}} 或 v-bind:属性 = “xxx | 过滤器名”
备注:
1.过滤器也可以按收额外参数、多个过滤器也可以串联
2.并没有改变原本的数据,是产生新的对应的数据
案例:
<html>
<head>
<meta charset='UTF-8'>
<title>过滤器</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="/js/day.js"></script>
</head>
<body>
<div id='root'>
<h2>显示格式化之后的时间</h2>
<!-- 计算属性实现-->
<h3>现在是:{{fmtTime}}</h3>
<!-- methods方法实现-->
<h3>现在是:{{getFmtTime()}}</h3>
<!-- 过滤器方法实现-->
<h3>现在是:{{time | timeFormater}}</h3>
<!-- 过滤器方法实现(传参)-->
<h3>现在是:{{time | timeFormater('YYYY_MM_DD')}}</h3>
<!-- 过滤器方法实现(串联)-->
<h3>现在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
<!-- 过滤器方法实现(绑定属性中的使用)-->
<h3 :x="msg | mySlice">你好</h3>
<!-- 注意过滤器不能使用在v-model里-->
</div>
<div id="root2">
<h2>msg:{{msg | mySlice}}</h2>
</div>
</body>
<script>
Vue.config.productionTip = false;
Vue.filter('mySlice',function(value){ //全局过滤器
return value.slice(0,4)
})
const vm = new Vue({
el:'#root',
data:{
time:Date.now(), // 时间戳
msg:'nihao',
},
computed:{
fmtTime(){
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss');
}
},
methods:{
getFmtTime(){
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss');
}
},
//局部filter
filters:{
timeFormater(value,str='YYYY-MM-DD HH:mm:ss'){
return dayjs(value).format(str)
}
},
})
const vm2 = new Vue({
el:'#root2',
data:{
msg:'hello,cf'
}
})
</script>
</html>
2385

被折叠的 条评论
为什么被折叠?



