Vue.js每天必学之过滤器与自定义过滤器
作者:i10630226 时间:2024-05-09 10:41:36
基础
类似于自定义指令,可以用全局方法 Vue.filter() 注册一个自定义过滤器,它接收两个参数:过滤器 ID 和过滤器函数。过滤器函数以值为参数,返回转换后的值:
Vue.filter('reverse', function (value) {
return value.split('').reverse().join('')
})
<!-- 'abc' => 'cba' -->
<span v-text="message | reverse"></span>
过滤器函数可以接收任意数量的参数:
Vue.filter('wrap', function (value, begin, end) {
return begin + value + end
})
<!-- 'hello' => 'before hello after' -->
<span v-text="message | wrap 'before' 'after'"></span>
双向过滤器
目前我们使用过滤器都是在把来自模型的值显示在视图之前转换它。不过也可以定义一个过滤器,在把来自视图(<input> 元素)的值写回模型之前转化它:
Vue.filter('currencyDisplay', {
// model -> view
// 在更新 `<input>` 元素之前格式化值
read: function(val) {
return '$'+val.toFixed(2)
},
// view -> model
// 在写回数据之前格式化值
write: function(val, oldVal) {
var number = +val.replace(/[^\d.]/g, '')
return isNaN(number) ? 0 : parseFloat(number.toFixed(2))
}
})
动态参数
如果过滤器参数没有用引号包起来,则它会在当前 vm 作用域内动态计算。另外,过滤器函数的 this 始终指向调用它的 vm。例如:
<input v-model="userInput">
<span>{{msg | concat userInput}}</span>
Vue.filter('concat', function (value, input) {
// `input` === `this.userInput`
return value + input
})
上例比较简单,也可以用表达式达到相同的结果,但是对于更复杂的逻辑——需要多于一个语句,这时需要将它放到计算属性或自定义过滤器中。
内置过滤器 filterBy 和 orderBy,根据所属 Vue 实例的当前状态,过滤/排序传入的数组。
本文已被整理到了《Vue.js前端组件学习教程》,欢迎大家学习阅读。
关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。
标签:vue.js,过滤器
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python运行脚本文件的三种方法实例
2022-07-08 11:10:21
![](https://img.aspxhome.com/file/2023/0/97300_0s.png)
深入理解JavaScript系列(28):设计模式之工厂模式详解
2024-05-06 10:08:17
JSP之表单提交get和post的区别详解及实例
2024-03-26 09:06:39
![](https://img.aspxhome.com/file/2023/8/97898_0s.png)
python实现ip代理池功能示例
2023-07-30 16:36:06
SQL Server的FileStream和FileTable深入剖析
2023-07-17 01:17:24
![](https://img.aspxhome.com/file/UploadPic/201211/30/20121130203621460s.jpg)
python中Switch/Case实现的示例代码
2021-09-18 22:03:39
JS 页面自动加载函数(兼容多浏览器)
2024-04-19 09:51:04
关于TypeScript开发的6六个实用小技巧分享
2024-04-16 08:59:26
![](https://img.aspxhome.com/file/2023/0/136730_0s.png)
Python实现自定义异常堆栈信息的示例代码
2021-10-29 14:27:47
![](https://img.aspxhome.com/file/2023/1/101221_0s.jpg)
用javascript控制iframe滚动的代码
2024-02-25 19:56:00
详解使用Nginx和uWSGI配置Python的web项目的方法
2021-06-28 00:24:47
![](https://img.aspxhome.com/file/2023/6/112496_0s.jpg)
详解selenium + chromedriver 被反爬的解决方法
2022-03-20 18:40:46
python3 求约数的实例
2023-12-29 03:18:59
推荐技术人员一款Python开源库(造数据神器)
2023-11-10 19:57:45
![](https://img.aspxhome.com/file/2023/6/93716_0s.jpg)
浅谈Python 递归算法指归
2023-01-12 06:27:50
![](https://img.aspxhome.com/file/2023/5/133395_0s.png)
JS中的public和private对象,即static修饰符
2023-08-29 21:53:13
python三种数据结构及13种创建方法总结
2021-03-23 04:46:52
![](https://img.aspxhome.com/file/2023/9/78799_0s.png)
SQL语句解析执行的过程及原理
2024-01-26 21:11:55
![](https://img.aspxhome.com/file/2023/1/127571_0s.png)
Python爬虫网页元素定位术
2023-07-25 16:28:00
![](https://img.aspxhome.com/file/2023/3/76113_0s.webp)
Python基于回溯法子集树模板解决旅行商问题(TSP)实例
2023-04-27 15:39:32
![](https://img.aspxhome.com/file/2023/5/82665_0s.jpg)