前言
公司技術(shù)棧圍繞react為主镊尺,但是時間有限研究較少朦佩,本文以vue中自定義指令為切入點,詳細介紹directive的作用和如何實現(xiàn)自定義指令庐氮。
vue自定義指令顧名思義语稠,就是vue給我們提供的一個編寫各種指令的入口。比如v-for,v-if ,v-show等弄砍,根據(jù)實際業(yè)務(wù)需求 時會用到自定義指令仙畦,一定程度上可以解決過濾器并承擔部分組件功能的作用输涕。
但是總體而言,由于指令需要操作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相對簡單占贫,下面來看一下高級的自定義指令使用。比如當遇到下面場景時:秒殺活動中有許多個商品先口,其中每個商品都有著倒計時型奥,要想實現(xiàn)頁面上倒計時的實時更新,傳統(tǒng)做法莫過于使用filter,里面綁定個計時器碉京。而自定義指令則大大不同:
根據(jù)需要封裝一個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;
},
// 開始轉(zhuǎn)換
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 即可實現(xiàn)倒計時實時改變