过滤器
过滤器(对模板中显示的数据进行处理,然后返回一个新的数据)
声明
-
全局注册 不推荐
Vue.filter(name, function) 必须在new Vue()的前面声明
-
局部注册
new Vue({ ... filters: { 过滤器的名称 (value) {} } }) 只作用于定义的实例内部
-
模板中使用:
1. 没有参数的过滤器 <p>{{数据 | 过滤器1的名称 | 过滤器2的名称 ...}}</p> <img :src="数据 | 过滤器的名称" height="100">
2. 有参数的过滤器 <h3>{{item.title | substr(10, '..')}}</h3> 把需要过滤的数据当做过滤器的第一个参数
- 过滤器中不能使用this调用vue实例中的内容, 过滤器必须返回内容
利用过滤器实现新闻列表
代码实例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0" />
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="item of newsList" :key="item.id">
<h3>{{item.title | substr(20, '...')}}</h3>
<img :src="item.img" height="100">
<p>{{item.time | formatTime}}</p>
</li>
</ul>
</div>
<script>
Vue.filter('formatTime', function (time) {
const now = Math.round(Date.now() / 1000)
const times = now - time
let res = ''
if (times < 60) {
// 小于 60 显示 刚刚
res = '刚刚'
} else if (times >= 60 && times < 3600) {
// 小于 3600 显示 xx分钟前
res = Math.floor(times / 60) + '分钟前'
} else if (times >= 3600 && times < 86400) {
// 小于 86400 显示 xx小时前
res = Math.floor(times / 3600) + '小时前'
} else {
// xx天之前
res = Math.floor(times / 86400) + '天之前'
}
return res
})
// 多个参数的过滤器
// Vue.filter('substr', function(value, length = 20, suffix = '...') {
// if (value.length <= length) {
// // 判断value的长度没有超过length, 返回原始数据
// return value
// }
// // 判断value的长度超过length
// return value.substr(0, length) + suffix
// })
new Vue({
el: '#app',
data: {
newsList: [
{
id: 1,
title: '武汉市长周先旺已任湖北省政协党组成员',
img: 'http://inews.gtimg.com/newsapp_ls/0/13062034210_640330/0',
time: 1611120638
},
{
id: 2,
title: '村民祖坟夜间被挖、记者采访遭跟踪 “野蛮矿企”底气何来?',
img: 'http://inews.gtimg.com/newsapp_ls/0/13061803667_640330/0',
time: 1611124307
},
{
id: 3,
title: '野蛮抗疫执法的村官被停职,该!那违反防疫规定的老人呢?',
img: 'http://inews.gtimg.com/newsapp_ls/0/13061973214_640330/0',
time: 1611109907
}
]
},
filters: {
substr(value, length = 20, suffix = '...') {
if (value.length <= length) {
// 判断value的长度没有超过length, 返回原始数据
return value
}
// 判断value的长度超过length
return value.substr(0, length) + suffix
}
},
methods: {
formatTime(time) {
const now = Math.round(Date.now() / 1000)
const times = now - time
let res = ''
if (times < 60) {
// 小于 60 显示 刚刚
res = '刚刚'
} else if (times >= 60 && times < 3600) {
// 小于 3600 显示 xx分钟前
res = Math.floor(times / 60) + '分钟前'
} else if (times >= 3600 && times < 86400) {
// 小于 86400 显示 xx小时前
res = Math.floor(times / 3600) + '小时前'
} else {
// xx天之前
res = Math.floor(times / 86400) + '天之前'
}
return res
}
}
})
</script>
</body>
</html>