过滤器
文章发布较早,内容可能过时,阅读注意甄别。
# 代码
<!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>过滤器</title>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="../js/dayjs.min.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>格式化后的时间戳</h2>
<!-- 计算属性实现 -->
<h3>现在是:{{fmtTime}}</h3>
<!-- methods实现 -->
<h3>现在是:{{getFmtTime()}}</h3>
<!-- 过滤器实现 -->
<h3>现在是:{{time | timeFormater}}</h3>
<!-- 过滤器实现 (传参)-->
<h3>现在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
<h3 :x="msg | mySlice">二丫讲梵</h3>
</div>
<div id="root2">
<h2>{{msg | mySlice}}</h2>
</div>
<script type="text/javascript">
Vue.config.productionTip = false; // 禁用提示
Vue.filter("mySlice", function (value) {
return value.slice(0, 4);
});
new Vue({
el: "#root",
data: {
time: 1658808711412, // 时间戳
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);
},
},
});
new Vue({
el: "#root2",
data: {
msg: "hello,eryajf",
},
});
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# 笔记
视频弹幕有网友说 filter 在 vue3 已经移除了。
- 过滤器:
- 定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。
- 语法:
- 注册过滤器:
Vue.filter(name,callback)
或new Vue{filters:{}}
- 使用过滤器:
{{ xxx | 过滤器名}}
或v-bind:属性 = "xxx | 过滤器名"
- 注册过滤器:
- 备注:
- 过滤器也可以接收额外参数、多个过滤器也可以串联
- 并没有改变原本的数据, 是产生新的对应的数据 :::


上次更新: 2025/02/20, 20:53:45