JS-Vue/基于Vue.js的时钟

来源:互联网 发布:android 8源码 编辑:程序博客网 时间:2024/05/16 21:52

MVVM框架的精髓是什么?我想【数据驱动视图】是一个很重要的组成部分。实现同一个特效,用原生js、jq写,与用框架写,思路上最大的不同点便在于【DOM操作上】。其中原生JS对于DOM的操作最为繁琐,而jq则极大地简化了DOM操作,替我们封装好了一大堆好用又靠谱的方法,诸如选择器,节点操作等等,链式调用附带兼容性处理,买一送一划算的很(笑)。而基于MVVM模式的前端框架(比如最火的那三小只),替我们把DOM操作也省略了,也就是说用框架做东西,我们只需要关心数据层面就可以了,至于【数据->DOM】的渲染,他会自动替我们完成,想想就觉得美翻!当然真的学习起来还是需要一定的时间成本的~下面向大家展示一个基于Vue2.0的时钟,老鸟轻拍~


html部分

<body><div id="app"><my-clock></my-clock></div></body>


js部分

var app = new Vue({el: '#app',components: {myClock: {data() {return {cssClock: {//整个钟的盒子position: 'absolute',width: '500px',height: '500px',border: '1px solid black',borderRadius: '50%'},cssDotWrap: {//装刻度的盒子transform: 'translateX(250px)'},cssDot: {//刻度们position: 'absolute',width: '2px',backgroundColor: 'black'},cssNeedle: {//三根针position: 'absolute',left: '250px',backgroundColor: 'black',transformOrigin: 'center bottom'},currTime: new Date()//当前日期对象}},computed: {sec() {//将当前秒数转化为秒针旋转的度数return this.currTime.getSeconds()*6;},min() {//将当前的分钟数转化为分针旋转的度数return this.currTime.getMinutes()*6 + this.currTime.getSeconds()/10 ;},hour() {//将当前的小时数转化为时针旋转的度数return this. currTime.getHours()*30 + this.currTime.getMinutes()/2;}},template: `<div :style="cssClock"><div :style="cssDotWrap"><div :style="Object.assign({},{transform: 'rotateZ('+i*6+'deg)',height: i%5==0?'30px':'10px',transformOrigin: '0px 250px'},cssDot)" v-for="(dot,i) in 60"></div></div><div :style="Object.assign({},{width: '8px',height: '200px',top: '50px',marginLeft: '-4px',transform: 'rotateZ('+hour+'deg)'},cssNeedle)"></div><div :style="Object.assign({},{width: '4px',height: '230px',top: '20px',marginLeft: '-2px',transform: 'rotateZ('+min+'deg)'},cssNeedle)"></div><div :style="Object.assign({},{width: '2px',height: '250px',marginLeft: '-1px',transform: 'rotateZ('+sec+'deg)'},cssNeedle)"></div></div>`,created() {setInterval(()=>{//钩子函数,在实例创建的时候运行定时器,我们只需要动态刷新当前的日期对象即可this.currTime = new Date();},1000)}}}})