<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>過(guò)濾器</title>
</head>
<body>
<div id="root">
<h2>顯示格式化后的時(shí)間</h2>
<h3>現(xiàn)在是:{{time}}</h3>
<h3>現(xiàn)在是:{{fmtTime}}</h3>
<h3>現(xiàn)在是:{{getFmtTime()}}</h3>
<h3>現(xiàn)在是:{{time | timeFormater}}</h3>
<h3>現(xiàn)在是:{{time | timeFormater('YYYY_MM_DD') | mySlice }}</h3>
<h2 :title="msg | mySlice">{{msg}}</h2>
</div>
<script src="../js/vue.js"></script>
<script src="../js/dayjs.min.js"></script>
<script type="text/javascript">
const vm = new Vue({
el: '#root',
data: {
time: 1646619724277,
msg:'你好呀,阿牛牛'
},
computed: {
fmtTime() {
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss');
}
},
methods: {
getFmtTime() {
return dayjs(this.time).format('YYYY-MM-DD HH:mm:ss');
}
},
filters: {
timeFormater(value, str = 'YYYY-MM-DD HH:mm:ss') {
return dayjs(value).format(str);
},
mySlice(value) {
return value.slice(0, 4);
}
}
})
</script>
</body>
</html>
知識(shí)點(diǎn)
1:Date.now()可以獲取當(dāng)前時(shí)間的時(shí)間戳益兄。
2:過(guò)濾器:
(1):對(duì)要顯示的內(nèi)容進(jìn)行特定格式化后再顯示箩祥。
(2):注冊(cè)過(guò)濾器:Vue.filter(name,callback)或者new Vue(filters:{})
(3):使用過(guò)濾器{{xxx | 過(guò)濾器}} 或者 v-bind:屬性="xxx | 過(guò)濾器"
(4):過(guò)濾器可以接收額外參數(shù)银酬,同時(shí)也可以串聯(lián)呛谜。
(5):使用過(guò)濾器并沒(méi)有改變?cè)镜臄?shù)據(jù)冰木,是產(chǎn)生新的對(duì)應(yīng)數(shù)據(jù)柬甥。