1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>Document</title>
    8. <script src="./lib/vue.js"></script>
    9. </head>
    10. <body>
    11. <div id="app">
    12. <h1>{{currentDate | dateformat}}</h1>
    13. </div>
    14. <script>
    15. // 定义一个过滤器,名字叫做dateformat,可以接受一个参数,判断参数要什么格式,如果是yyyy-mm-dd,就会显示年月日,否则显示具体时间.
    16. Vue.filter("dateformat", function (datestr, patten = "") {
    17. dt = new Date(datestr);
    18. y = dt.getFullYear();
    19. m = dt.getMonth() + 1
    20. d = dt.getDate()
    21. if (patten.toLocaleLowerCase === 'yyyy-mm-dd') {
    22. return `${y}-${m}-${d}`
    23. } else {
    24. hh = dt.getHours()
    25. mm = dt.getMinutes()
    26. ss = dt.getSeconds()
    27. return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
    28. }
    29. })
    30. var vm=new Vue({
    31. el:'#app',
    32. data:{
    33. currentDate: new Date()
    34. },
    35. methods:{},
    36. // filters过滤器,如果全局过滤器跟局部过滤器一样,那么就近原则,先用局部过滤器,再用全局过滤器
    37. filters:{
    38. dateformat:function(datestr, patten = ""){
    39. dt = new Date(datestr);
    40. y = dt.getFullYear().toString().padStart(2, '0');
    41. // .padStart(2, '0') 填充两位,从开头填充
    42. // .padEnd(2, '0') 填充两位,从尾部填充
    43. m = (dt.getMonth() + 1).toString().padStart(2, '0')
    44. d = dt.getDate().toString().padStart(2, '0')
    45. if (patten.toLocaleLowerCase === 'yyyy-mm-dd') {
    46. return `${y}-${m}-${d}`
    47. } else {
    48. a = new Date()
    49. hh = dt.getHours().toString().padStart(2, '0')
    50. mm = dt.getMinutes().toString().padStart(2,'0')
    51. ss = dt.getSeconds().toString().padStart(2, '0')
    52. return `${y}-${m}-${d} ${hh}:${mm}:${ss} ~~~~~~~~~~~~~~~~~~`
    53. }
    54. }
    55. }
    56. });
    57. </script>
    58. </body>
    59. </html>

    image.png