vue中filter(过滤器)的使用
1. 全局注册Vue.filter(过滤器的名称, 函数)html:<div id="app"><ul><li v-for="item in teachers" :key="item.id">{{ item.name }} 生于:{{ item.birthDay | dateFormat("YY...
·
1. 全局注册
Vue.filter(过滤器的名称, 函数)
html:
<div id="app">
<ul>
<li v-for="item in teachers" :key="item.id">
{{ item.name }} 生于:{{ item.birthDay | dateFormat("YY-MM-DD") }}
</li>
</ul>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/moment/moment.js"></script>
函数接收的参数就是 | 前面的数据
在使用过滤器的时候 只需要在数据后面加上 |
数据 | 过滤器名称
数据 | 过滤器名称(参数)
过滤器函数中第一个参数,就是要过滤的数据
Vue.filter("dateFormat", function(value, pattern){
// value就是用户给的时间对象
return moment(value).format(pattern)
})
2. 局部注册
const vm = new Vue({
el: "#app",
data: {
teachers: [
{
id: 1,
name: "aa",
birthDay: new Date("1992-05-08")
},
{
id: 2,
name: "bb",
birthDay: new Date("1992-06-08")
},
{
id: 3,
name: "cc",
birthDay: new Date("1993-05-08")
},
{
id: 4,
name: "dd",
birthDay: new Date("2002-05-08")
}
]
}
});
其它使用:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li v-for="item in students" :key="item.id">
<span>{{item.name}}</span>====<span>{{item.gender | genderFilter}}</span>
</li>
</ul>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
Vue.filter("genderFilter", function(value){
switch(value){
case 0:
return "female"
case 1:
return "male"
case -1:
return "unknow"
}
})
const vm = new Vue({
el: "#app",
data: {
students: [
{id: 1, name: "aa", gender: 1},
{id: 2, name: "bb", gender: 0},
{id: 3, name: "cc", gender: 1},
{id: 4, name: "dd", gender: -1},
{id: 5, name: "ee", gender: 0}
]
}
});
</script>
</body>
</html>
更多推荐
已为社区贡献4条内容
所有评论(0)