最简单的一步当数据1显示男,2显示女
html: <div>{{ tlist | sectext}}</div> js: data(){ return { tlist:'1', } } filters: { sectext: function(value) { if (value == 1) { return "男"; } if (value == 2) { return "女"; } }, },截取逗号拼接的第n个
html: <div>{{list | splitVc(2)}}</div> js: data(){ return { list:'1,2,3,4,5,6' } } filters: { splitVc:function(value,index){ if(!value) return ""; return value.split(",")[index]; } }同理可以将数据split在根据要求分别显示
html: <div>{{list | splitVc(2)}}</div> js: data(){ return { list:'1,2,3,4,5,6' } } filters: { splitVc:function(value,index){ if(!value) return ""; const tylp = value.split(",")[index]; if(tylp==3){ return '截取逗号第3个' } } }常见的毫秒转化成标准时间
html: <div>{{time | timeclik}}</div> js: <script> export default { name: "index", data() { return { time: 1572485662000,//时间 }; }, filters: { timeclik: function(value) { if (!value) return ""; var date = new Date(value); //时间戳为10位需*1000,时间戳为13位的话不需乘1000 var Y = date.getFullYear() + "-"; var M =(date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1): date.getMonth() + 1) + "-"; var D = date.getDate() + " "; var h = date.getHours() + ":"; var m = date.getMinutes() + ":"; var s = date.getSeconds(); return Y + M + D + h + m + s; } }, }; </script>中体展现:
当然我们也可以封装一下统一放在一个模块方便管理还可以重复使用 新建文件filters-〉custom.js 首先要买main.js添加全局过滤器
import * as custom from './filters/custom'//注意路径 Object.keys(custom).forEach(key => { Vue.filter(key, custom[key]) })在custom.js封装方法
export const guideTypeVc = value => { if (!value) return ''; let content = ""; switch (parseInt(value)) { case 1: content = "1显示男"; break; case 2: content = "2显示女"; break; } return content; }在你要过滤的页面引用效果一样
<div>{{tlist | guideTypeVc }}</div> import { guideTypeVc } from "@/filters/custom";过滤输入的是否是邮箱 在custom.js代码
export const validataEmail = (obj) => { return !/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(obj) }在调用代码:
aclick:function(){ const qqlist="1641767484@qq.com" if (validataEmail(qqlist)) { console.log("请输入正确的邮箱") }else{ console.log("输入的邮箱正确") } }封装一个方法判断是否为空 引用方法和邮箱一样
export const isNull = str => { return (str == '' || str == "" || str == null || str == undefined || str == "undefined"); }封装一个验证手机号是否正确:
export const shouji = (obj) => { return !/^[1][3,4,5,7,8,9][0-9]{9}$/.test(obj) }调用:
aclick:function(){ if(shouji(this.ww)){ console.log("请输入正确的手机号") return; }else{ console.log("手机号正确") } },时间转换:
export const time = (value) => { if (!value) return ""; var date = new Date(value); //时间戳为10位需*1000,时间戳为13位的话不需乘1000 var Y = date.getFullYear() + "-"; var M =(date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1): date.getMonth() + 1) + "-"; var D = date.getDate() + " "; var h = date.getHours() + ":"; var m = date.getMinutes() + ":"; var s = date.getSeconds(); return Y + M + D + h + m + s; }