開始
在《如何開發(fā)自定義Vue組件(一)古话?》中已經(jīng)說明了如何開發(fā)一個自定義的進度條,自定義vue組件也在該文中有介紹锁施,所以直接進入本文主題陪踩,怎么開發(fā)一個自定義時間組件?
同樣是3方面的內(nèi)容:Template悉抵、Css肩狂、Component。
舉例說明:時間組件
part-time.png
Template
之前開發(fā)自定義進度條是在原生progress基礎(chǔ)上加上自定義樣式達到目的姥饰,這次自定義時間組件沒有原生組件做基礎(chǔ)傻谁,完全用div拼出來的。
<script type="x-template" id="part-datetime">
<div class="border-box" style="padding:25px;">
<div class="text-orion">當前時間</div>
<div>
<div class="row text-center">
<div class="col-md-2">
<div class="text-orion text-center" style="font-size:30px;" v-text="day"></div>
<div class="text-orion-light text-center">DAY</div>
</div>
<div class="col-md-2" >
<div style="font-size:30px;" class="text-center" v-text="hour"></div>
<div class="text-orion-light text-center">H</div>
</div>
<div class="col-md-1">
<div class="text-orion" style="font-size:30px;">:</div>
</div>
<div class="col-md-2">
<div style="font-size:30px;" class="text-center" v-text="minute"></div>
<div class="text-orion-light text-center">MIN</div>
</div>
<div class="col-md-1">
<div class="text-orion" style="font-size:30px;">:</div>
</div>
<div class="col-md-2">
<div style="font-size:30px;" class="text-center" v-text="second"></div>
<div class="text-orion-light text-center">SEC</div>
</div>
</div>
</div>
</div>
</script>
Css
基礎(chǔ)樣式是bootstrap.css列粪,再加上自定義樣式审磁。
.border-box {
height: 130px;
padding: 20px;
border: 1px solid rgb(45, 44, 60);
}
.text-orion {
color:#56BBCA;
}
.text-orion-light {
color:#5D858D;
}
Component
為了讓新組件成為vue的一員谈飒,所以需要注冊。
先注冊一個簡單的不會自動更新的時間組件态蒂。
Vue.component('part-datetime', {
data: function () {
return {}
},
props: {
day: {
type: Number,
default: 10
},
hour: {
type: Number,
default: 12,
},
minute: {
type: Number,
default: 15,
},
second: {
type: Number,
default: 30,
},
},
template: 'part-datetime'
})
然后再此基礎(chǔ)上在注冊一個會自動更新時間的組件杭措。
這次使用data來更新數(shù)據(jù)。
Vue.component('p-datetime', {
data: function () {
return {
dayValue:6,
hourValue:17,
minuteValue:31,
secondValue:50,
}
},
created() {
var self = this
function repeated() {
self.setTime()
setTimeout(repeated, 1000);
}
repeated()
},
methods: {
setTime: function() {
var self = this
var now = new Date()//獲取系統(tǒng)當前時間
self.dayValue = now.getDate() //獲取當前日(1-31)
self.hourValue = now.getHours() //獲取當前小時數(shù)(0-23)
self.minuteValue = now.getMinutes() //獲取當前分鐘數(shù)(0-59)
self.secondValue = now.getSeconds() //獲取當前秒數(shù)(0-59)
}
},
template: `
<part-datetime
:day="dayValue"
:hour="hourValue"
:minute="minuteValue"
:second="secondValue">
</part-datetime>
`
})
到此钾恢,新的時間組件就開發(fā)完成了手素,怎么應(yīng)用呢?
如何應(yīng)用自定義組件瘩蚪?
Html
像html普通組件一樣使用泉懦,因為已經(jīng)注冊了一個會自動更新的時間組件p-datetime,所以很簡單的使用即可募舟,無需賦值祠斧。
<div class="col-md-3 first">
<p-datetime></p-datetime>
</div>
這樣顯示的時間就會和當前電腦時間一樣,并自動更新時分秒的數(shù)值拱礁。
這和之前的自定義進度條有區(qū)別琢锋,傳值的方式不同:自定義進度條需要在當前頁面中傳相應(yīng)的值;自定義時間組件在構(gòu)建組件時已經(jīng)把傳值方法寫好呢灶,查看setTime方法吴超。