-
-
过滤器只可以用在两个地方:mustache 插值表达式和 v-bind 表达式。
-
过滤器应该被添加在 JavaScript 表达式的尾部,由管道符指示;
全局过滤器
// main.js Vue.filter('dateFormat', function(originVal) { const dt = new Date(originVal) const y = dt.getFullYear() const m = (dt.getMonth() + 1 + '').padStart(2, '0') const d = (dt.getDate() + '').padStart(2, '0') const hh = (dt.getHours() + '').padStart(2, '0') const mm = (dt.getMinutes() + '').padStart(2, '0') const ss = (dt.getSeconds() + '').padStart(2, '0') return `${y}-${m}-${d} ${hh}:${mm}:${ss}` }) Vue.filter('String', function(originVal) { return '==' + originVal + '==' })
<template> <div class="detail"> <p>{{msg | dateFormat | String }}</p> <p>{{ msg }}</p> </div> </template>

过滤器传参
Vue.filter('dateFormat', function (originVal, pattern) {
console.log(pattern)
const dt = new Date(originVal)
const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + '').padStart(2, '0')
const d = (dt.getDate() + '').padStart(2, '0')
if (pattern === 'yyyy-mm-dd') {
return `${y}-${m}-${d}`
} else {
const hh = (dt.getHours() + '').padStart(2, '0')
const mm = (dt.getMinutes() + '').padStart(2, '0')
const ss = (dt.getSeconds() + '').padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
})
<template> <div class="detail"> <p>{{msg | dateFormat('yyyy-mm-dd')}}</p> <p>{{ msg }}</p> </div> </template>

注意:不传参默认的参数是undefined
私有过滤器
<template>
<div class="detail">
<!-- pattern就是传的yyyy-mm-dd参数,传参传的是条件! -->
<p>{{ msg | dateFormat('yyyy-mm-dd hh:mm:ss') }}</p>
<p>{{ msg }}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: +new Date()
}
},
filters: {
dateFormat: function(originVal, pattern) {
console.log(pattern)
const dt = new Date(originVal)
const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + '').padStart(2, '0')
const d = (dt.getDate() + '').padStart(2, '0')
if (pattern === 'yyyy-mm-dd') {
return `${y}-${m}-${d}`
} else {
const hh = (dt.getHours() + '').padStart(2, '0')
const mm = (dt.getMinutes() + '').padStart(2, '0')
const ss = (dt.getSeconds() + '').padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
}
}
}
}
</script>
<style lang="less" scoped>
</style>

当全局过滤器和私有过滤器重名时,优先使用私有过滤器