什么是过滤器
过滤器对将要显示的文本,先进行特定格式化处理,然后再进行显示
注意:过滤器并没有改变原本的数据, 只是产生新的对应的数据
使用方式
1. 定义过滤器:
全局过滤器:
局部过滤器:在Vue实例中使用 fifilter 选项 , 当前实例范围内可用
梦
学
谷
mengxuegu.com
第五章 Vue 过滤器和插件
5.1 过滤器
5.1.1 什么是过滤器
过滤器对将要显示的文本,先进行特定格式化处理,然后再进行显示
注意:过滤器并没有改变原本的数据, 只是产生新的对应的数据
5.1.2 使用方式
1. 定义过滤器:
全局过滤器:
Vue.filter('过滤器名称',function(value1,[value2,...]){
// 数据处理逻辑
})
局部过滤器:在Vue实例中使用 fifilter 选项 , 当前实例范围内可用
new Vue({
filters: {
'过滤器名称': function(value1,[value2,...]){
// 数据处理逻辑
}
}
})
2. 过滤器可以用在两个地方:双花括号 {{}} 和 v-bind 表达式
案例演示
- 需求:
- 实现过滤敏感字符,如当文本中有 tmd、sb 都将进行过滤掉
- 过滤器传入多个参数 ,实现求和运算
- 实现:
- 新建 vue-04-过滤器和插件 目录, 安装 vue.js 模块
- 在 vue-04-过滤器和插件 目录下创建 01-过滤器.html
<!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>
</head>
<body>
<div id="app">
<h3>过滤器接收单个参数</h3>
<p>{{content | contentFilter}}</p>
<input type="text" :value="content | contentFilter">
<h3>过滤器接收多个参数</h3>
<p>{{englishScore | add(mathScore,chinaScore)}}</p>
<input type="text" :value="englishScore | add(mathScore,chinaScore)">
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script>
// Vue.filter('contentFilter',function(val){
// if(!val){
// return ''
// }
// return val.toString().toUpperCase().replace('TMD','***').replace('SB',"***")
// })
new Vue({
el: '#app',
data: {
content: '小伙子,你tmd就是个SB',
englishScore: 98,
mathScore: 89,
chinaScore: 100
},
filters:{
contentFilter(val){
if(!val){
return ''
}
return val.toString().toUpperCase().replace('TMD','***').replace('SB','**')
},
add(num1,num2,num3){
return num1 + num2 + num3
}
}
})
</script>
</body>
</html>
gitee源码:https://gitee.com/cyzgw/vue_demo.git