vue中的过滤器及其时间格式化问题

2020-06-16 06:57:01易采站长站整理

三、局部过滤器

定义一个局部的过滤器,格式化当前时间

【 代码示例 】


<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="winowh=device-winowh, initial-scale=1.0">
<title>过滤器学习2</title>
<script src="js/vue.js"></script>
</head>

<body>
<div id="app">
<div>当前时间是: {{ dateTime }}</div>
<div>格式化后的时间是: {{ dateTime | dateFormat }}</div>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
dateTime: new Date(),
},
// 定义一个局部的过滤器,格式化当前时间
filters: {
dateFormat: (dateTime) => {
var now = new Date(dateTime)
var y = now.getFullYear()
var m = (now.getMonth() + 1).toString().padStart(2, '0')
var d = now.getDate().toString().padStart(2, '0')
var hh = now.getHours().toString().padStart(2, '0')
var mm = now.getMinutes().toString().padStart(2, '0')
var ss = now.getSeconds().toString().padStart(2, '0')
// 过滤器中要有返回值
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
}
})
</script>
</body>

</html>

测试结果:

在这里插入图片描述

注意:

当有两个名称相同的全局过滤器和局部过滤器的时候,会以就近原则进行调用过滤器,局部过滤器的优先级高于全局过滤器。

【 知识拓展 】

padStart() 可以在字符串的开头进行字符补全。

① 语法:

str.padStart(targetLength [, padString])

② 参数:

③ 返回值:

在原字符串开头填充指定的填充字符串直到目标长度所形成的新字符串。

借鉴网上的常用方法格式化时间


<body>
<div id="app">
<div>当前时间是: {{ dateTime }}</div>
<div>格式化后的时间是: {{ dateTime | dateFormat('yyyy-MM-dd hh:mm:ss') }}</div>
</div>
<script>
Date.prototype.format = function (format) {
var dateMap = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"h+": this.getHours(), // 小时
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度