使用Vue过滤器格式化日期时间

学习目标:

  • 掌握Vue过滤器,created()、mounted()、beforeDestory()等函数

学习内容:

Vue过滤器,created()、mounted()、beforeDestory()


实现思路:

(1)使用Vs code创建demo.html文件 

 <div id="app">
        <div class="banner">
            {{title | formatDate}}
        </div>
    </div>

(2)在demo.html文件中添加<div>标签设置id属性为app,再添加显示Banner<div>标签设置样式

  <style>
        #app{
            text-align: center;
            padding: 50px;
        }
        .banner{
            width: 600px;
            height: 150px;
            line-height: 150px;
            text-align: center;
            box-shadow: 5px 5px 10px #888888;
            font-size: 32px;
            font-weight: bolder;
            background-color: #033592;
            color: #FFF;
            margin: 0px auto;
            border-radius: 20px;
        }
    </style>
    <div id="app">
        <div class="banner">
            {{title | formatDate}}
        </div>
    </div>

(3)添加Vue.js的引用,再添<script>表标签,实例化Vue对象并设置Vue的参数选项对象,其中添加created()、mounted()和beforeDestory()函等函数,创建created()钩子函数中初始化当前日期,在mounted()钩子函数中创建定时器,在beforeDestroy()钩子函数中清除定时器,设置Vue的filter选项并创建formatDate()过滤器函数来格式化日期时间,最后在HTML标签中绑定数据并使用过滤器格式化当前时间。

<script src="./vue.min.js"></script>
<script>
    var padDate=function(val){
        return val<10?"0"+val:val;
    };
    var vm=new Vue({
        el:'#app',
        data:{
            date:null
        },
        created:function(){
            this.date=new Date();
        },
        mounted:function(){
            var _this=this;
            this.timer=setInterval(function(){
                _this.date=new Date();
            },1000);
        },
        beforeDestroy:function(){
            if(this.timer){
                clearInterval(this.timer);
            }
        },
        filters:{
            formatDate:function(val){
                var currdate=new Date(val);
                var year=currdate.getFullYear();
                var month=padDate(currdate.getMonth()+1);
                var day=padDate(currdate.getDate());
                var hours=padDate(currdate.getHours());
                var minutes=padDate(currdate.getMinutes());
                var seconds=padDate(currdate.getSeconds());
                return year+"-"+month+"-"+day+"-"+hours+"-"+minutes+"-"+seconds;
            }
        }
    });

</script>

(4)启动Chrome浏览器浏览demo.html

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值