前言
公司技术栈围绕react为主,然而工夫无限钻研较少,本文以vue中自定义指令为切入点,具体介绍directive的作用和如何实现自定义指令。
vue自定义指令顾名思义,就是vue给咱们提供的一个编写各种指令的入口。比方v-for,v-if ,v-show等,依据理论业务需要 时会用到自定义指令,肯定水平上能够解决过滤器并承当局部组件性能的作用。
然而总体而言,因为指令须要操作dom,因而能用组件就不必指令。言归正传:
比方写一个v-focus,任何input或者textarea绑定该属性可间接获取焦点
自定义指令v-focus
<body> <div id="app"> <input type="text" v-focus > </div> <script> Vue.directive('focus',{ inserted:function(el){ el.focus() } }) var app = new Vue({ el:'#app' }) </script> </body>
上述directive绝对简略,上面来看一下高级的自定义指令应用。比方当遇到上面场景时:秒杀流动中有许多个商品,其中每个商品都有着倒计时,要想实现页面上倒计时的实时更新,传统做法莫过于应用filter,外面绑定个计时器。而自定义指令则大大不同:
依据须要封装一个time.js
var Time = { // 以后工夫戳 getUnix: function() { return new Date().getTime() }, // 明天0点工夫戳 getTodayUnix: function() { var date = new Date() date.setHours(0); date.setMinutes(0); date.setMilliseconds(0); date.setMilliseconds(0); return date.getTime(); }, //获取往年1月1日零时工夫戳 getYeaderUnix: function() { var date = new Date() date.setMonth(0) date.setDate(1) date.setHours(0); date.setMinutes(0); date.setMilliseconds(0); date.setMilliseconds(0); return date.getTime(); }, //获取规范年月日 getLastDate: function(time) { var date = new Date(time); var month = date.getMonth()+1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1; var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); return date.getFullYear() + '-' + month + '-' + day; }, // 开始转换 getFormatTime: function(timestamp) { var now = this.getUnix(); var today = this.getTodayUnix(); var year = this.getYeaderUnix(); var timer = (now - timestamp) / 1000; var tip = '' if (timer <= 0) { tip = '刚刚' } else if (Math.floor(timer / 60) <= 0) { tip = '刚刚' } else if (timer < 3600) { tip = Math.floor(timer / 60) + '分钟前'; } else if (timer >= 3600 && (timestamp - today >= 0)) { tip = Math.floor(timer / 3600) + '小时前'; } else if (timer / 86400 <= 31) { tip = Math.ceil(timer / 86400) + '天前'; } else { tip = this.getLastDate(timestamp); } return tip; }}
高级自定义指令v-time
<div id="app"> <div class="list" v-time="item" v-for="(item,index) in list" :key="index"> {{item }} </div> </div> </body> Vue.directive('time',{ bind:function(el,binding){ el.innerHTML = Time.getFormatTime(binding.value*1000) el._timeout_ = setInterval(()=>{ el.innerHTML = Time.getFormatTime(binding.value*1000) },60000) }, unbind:function(el){ clearInterval(el._timeout_); delete el._timeout_ } })
只须要为每个列表绑定一个v-time 即可实现倒计时实时扭转