过滤器
过滤器实例
将英文字符串的第一个字母转为大写
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <p>{{ massage | capi }}</p> <p></p> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> const vm = new Vue({ el: "#app", data: { massage: 'hello world' }, filters: { capi(val) { const first = val.charAt(0).toUpperCase(); const other = val.slice(1); return first+other; } } }) </script> </body> </html>
私有过滤器和全局过滤器
全局过滤器:
Vue.filter('capi', function(val){ const first = val.charAt(0).toUpperCase(); const other = val.slice(1); return first+other; })
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> Vue.filter('capi', function(val){ const first = val.charAt(0).toUpperCase(); const other = val.slice(1); return first+other; }) const vm = new Vue({ el: "#app", data: { massage: 'hello world' }, filters: { capi(val) { const first = val.charAt(0).toUpperCase(); const other = val.slice(1); return first+other; } } }) </script>
过滤器注意点
1.过滤器函数必须写到filters节点之下
2.过滤器的本质为函数
3.过滤器中一定要有一个返回值
4.在过滤器的形参中就可以获得管道符前面待处理的那个值
5.如果全局过滤器和私有过滤器的名字一致,按照就近原则
时间格式化
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <p>{{ massage | capi }}</p> <p>{{ time | dateFormat }}</p> </div> <!-- CDN example (unpkg) --> <script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script> Vue.filter('capi', function(val){ const first = val.charAt(0).toUpperCase(); const other = val.slice(1); return first+other; }) Vue.filter('dateFormat', function(time){ const dateStr = dayjs(time).format("YYYY--MM--DD HH:mm:ss"); return dateStr; }) const vm = new Vue({ el: "#app", data: { massage: 'hello world', time: new Date() }, filters: { capi(val) { const first = val.charAt(0).toUpperCase(); const other = val.slice(1); return first+other; } } }) </script> </body> </html>
连续调用多个过滤器
过滤器的兼容性