美文网首页
Vue.js 过滤器

Vue.js 过滤器

作者: Rinaloving | 来源:发表于2019-07-31 15:44 被阅读0次
Vue.js 支持在{{ }} 插值的尾部添加一个管道符“(|)” 对数据进行过滤,经常用于格式化文本,比如字母全部大写、货币千位使用逗号分隔符。过滤的规则则是自定义的,通过给Vue 实例添加选项filters来设置,例如显示当前时间,可以对时间进行格式化处理:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>过滤器</title>
</head>
<body>
<div id="app">
    {{ date | formatDate }}
</div>
<!--自动识别最新稳定版本的Vue.js-->
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
    // 在月份、日期、小时等 小于10 时前面补 0
    var padDate = function(value){
        return value < 10 ? '0' + value : value;
    };

    var app = new Vue({
        el:'#app',
        data:{
            date:new Date()
        },
        filters:{
            formatDate:function(value){ // 这里的value就是需要过滤的数据
                var date = new Date(value);
                var year = date.getFullYear();
                var month = padDate(date.getMonth() +1);
                var day = padDate(date.getDate());
                var hours = padDate(date.getHours());
                var minutes = padDate(date.getMinutes());
                var seconds = padDate(date.getSeconds());
                // 将整理好的数据返回出去
                return year + '-' + month + '-'+ day + ' '+hours+':'+minutes+':'+seconds;
            }

        },
        mounted:function(){
            var _this = this; // 声明一个变量指向 Vue 实例this,保证作用域一致
            this.timer = setInterval(function(){
                _this.date = new Date(); // 修改数据date
            },1000);

        },
        beforeDestory: function(){
            if(this.timer){
                clearInterval(this.timer); // 在Vue实例销毁前,清除我们的定时器
            }
        }

    })

</script>


</body>
</html>
过滤器.png

相关文章

网友评论

      本文标题:Vue.js 过滤器

      本文链接:https://www.haomeiwen.com/subject/purtdctx.html