vue实现时间实时更新显示

1,850 阅读1分钟

在vue项目总会有这样一功能,在页面中显示最新的实时事件,如图展示:

  • 在html部分,vue里也就是< template>定义一个div
<div class ="time">{{date}}</div>
  • 在< script>方法部分
export default {
    data:function(){
        return{
            date: new Date(),
        };
    },
    created(){
    },
    mounted(){
        let _this = this;
        this.timer = setInterval(function(){
        _this.date = new Date().toLocaleString();
        });
    },
    beforeDestroy:function(){
        if(this.timer){
            clearInterval(this.timer);
        }
    },
    methods:{
    }
}
  • 在< style scoped>写时间的样式即可