vue获取当前时间

 <h2>{{presentTime}}h2>
<script>
export default {
  data(){
  		return{
  		 clearInterval:'',
  		 presentTime:'',
  		}
  	},
  created() {
    this.currentTime();
  },
  methods: {
    currentTime() {
        // 当前时间
        this.clearInterval = setInterval(() => {//定时器一秒调用一次
          //年
          let year = new Date().getFullYear();
          year = year < 10 ? "0" + year : year;
          //月份是从0月开始获取的,所以要+1;
          let month = new Date().getMonth() + 1;
          month = month < 10 ? "0" + month : month;
          //日
          let day = new Date().getDate();
          day = day < 10 ? "0" + day : day;
          //时
          let hour = new Date().getHours();
          hour = hour < 10 ? "0" + hour : hour;
          //分
          let minute = new Date().getMinutes();
          minute = minute < 10 ? "0" + minute : minute;
          //秒
          let second = new Date().getSeconds();
          second = second < 10 ? "0" + second : second;
          this.presentTime = year + "-" + month + "-" + day +  " " + hour + ":" + minute + ":" + second;
        }, 1000);
    },
  },
  beforeDestroy(){
    clearInterval(this.clearInterval);//销毁定时器
 },
}
</script>

你可能感兴趣的:(vue.js,javascript,前端)