当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Vue filter 过滤当前时间 实现实时更新效果

Vue filter 过滤当前时间 实现实时更新效果

2020年03月09日  | 移动技术网IT编程  | 我要评论

过滤器

过滤器是处于客户端与服务器资源文件之间的一道过滤网,在访问资源文件之前,通过一系列的过滤器对请求进行修改、判断等,把不符合规则的请求在中途拦截或修改。也可以对响应进行过滤,拦截或修改响应。

下面通过代码给大家介绍vue filter 过滤当前时间 实现实时更新,具体代码如下所示:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>document</title>
  <script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script>
</head>
<body>
  <div id="ssl">
    {{currenttime|filtertime}}
  </div>
</body>
<script>
  var em = new vue({
    el: "#ssl",
    data: {
      currenttime: new date(), // 获取当前时间
    },
    filters: {
      filtertime(val) {
        var y = val.getfullyear()
        var m = val.getmonth()
        var d = val.getdate()
        var h = val.gethours()
        var mi = val.getminutes()
        var s = val.getseconds()
        return y + "年" + m + "月" + d + "日" + h + "时" + mi + "分" + s + "秒"
      }
    },
    //声明周期函数 是最早使用data数据的函数
    created() {
      var _this = this; //声明一个变量指向vue实例this,保证作用域一致
      setinterval(function () {
        _this.currenttime = new date()//修改数据让他可以实时更新
      }, 1000);
    }
  })
</script>
</html>

这里使用了created生命周期函数 created是最早操作date数据的

代码逻辑:先让当前时间可以实时更新 在created里面

然后在filters里面更改时间格式

ps:vue 时间过滤器

vue里的 时间过滤器:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>document</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<div>
 {{ message | formattime('ymd')}}
</div>
<div>
{{ message | formattime('ymdhms')}}
</div>
  <div>
  {{ message | formattime('hms')}}
  </div>
  <div>
  {{ message | formattime('ym')}}
  </div>
  </div>

元素的补零计算:

<script>
//元素的补零计算
function addzero(val){
 if(val < 10){
 return "0" +val;
 }else{
 return val;
 }
};

console.log(addzero(9))

//实现vue中的过滤器功能 先定义过滤器 在使用    value是过滤器前面的值,type是过滤器中定义的字段
vue.filter("formattime",function(value,type){
var datatime="";
var data = new date(); 
       data.settime(value); 
   var year  = data.getfullyear(); 
       var month = addzero(data.getmonth() + 1); 
       var day  = addzero(data.getdate()); 
       var hour  = addzero(data.gethours());
var minute = addzero(data.getminutes());
var second = addzero(data.getseconds());
if(type == "ymd"){
datatime = year + "-"+ month + "-" + day;
}else if(type == "ymdhms"){
datatime = year + "-"+month + "-" + day + " " +hour+ ":"+minute+":" +second;
}else if(type == "hms"){
datatime = hour+":" + minute+":" + second;
}else if(type == "ym"){
datatime = year + "-" + month;

}
return datatime;//将格式化后的字符串输出到前端显示
});


var app = new vue({
 el: '#app',
 data: {
  message: '1501068985877'
 }
     });
</script>

总结

以上所述是小编给大家介绍的vue filter 过滤当前时间 实现实时更新,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网