vue允許定義過濾器,對于一些文本常見格式化。過濾器可以用在兩個(gè)地方
-(1)v-bind 表達(dá)式
-(2){{}}插值表達(dá)式
使用:使用過濾器:{{ xxx | 過濾器名}} 或 v-bind:屬性 = "xxx | 過濾器名"
注冊:Vue.filter(name,callback) 或 new Vue{filters:{}}
<!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>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
</head>
<body>
<!-- 準(zhǔn)備好一個(gè)容器-->
<div id="root">
<h2>顯示格式化后的時(shí)間</h2>
<!-- 計(jì)算屬性實(shí)現(xiàn) -->
<h3>現(xiàn)在是:{{ fmtTime }}</h3>
<!-- methods實(shí)現(xiàn) -->
<h3>現(xiàn)在是:{{ getFmtTime() }}</h3>
<!-- 過濾器實(shí)現(xiàn) -->
<h3>現(xiàn)在是:{{time | timeFormater}}</h3>
<!-- 過濾器實(shí)現(xiàn)(傳參) -->
<h3>現(xiàn)在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
<h3 :x="msg | mySlice">尚硅谷</h3>
</div>
<script type="text/javascript">
//全局過濾器
Vue.filter('mySlice',function(value){
return value.slice(0,4)
})
new Vue({
el:'#root',
data:{
time:Date.now(), //時(shí)間戳
msg:'你好,尚硅谷'
},
// 計(jì)算屬性
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'){
// console.log('@',value)
return dayjs(value).format(str)
}
}
})
</script>
</body>
</html>
?
(1)filters和methods配置方法是一樣的,在過濾器實(shí)現(xiàn)中<h3>現(xiàn)在是:{{time | timeFormater}}</h3>
會(huì)把time傳遞給timeFormater這個(gè)過濾器,獲取的第一個(gè)參數(shù)就是出入的time值,如果在使用過濾器時(shí)傳入?yún)?shù),需要定義一個(gè)變量接收。
(2)<h3>現(xiàn)在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
過濾器還可以串聯(lián)使用,time傳遞給timeFormater獲取得到2023年04月15日 12:00:58,再繼續(xù)將結(jié)果傳送給全局注冊的mySlice()方法。文章來源:http://www.zghlxwxcb.cn/news/detail-414177.html
過濾器:并沒有改變原本的數(shù)據(jù), 是產(chǎn)生新的對應(yīng)的數(shù)據(jù)文章來源地址http://www.zghlxwxcb.cn/news/detail-414177.html
到了這里,關(guān)于vue-過濾器的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!