vue自定义指令顾名思义,就是vue给我们提供的一个编写各种指令的入口。比如v-for,v-if ,v-show等,根据实际业务需求
有时会用到自定义指令,一定程度上可以解决过滤器并承担部分组件功能的作用。
但是总体而言,由于指令需要操作dom,因此能用组件就不用指令。言归正传:
写一个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>
当然指令可以很复杂,比如写一个v-time ,会自动将后端给我们的时间戳变为几前,几分钟前以及几小时前这种。
封装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;
}
}
页面中引入
<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_
}
})