ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 过滤器的使用 1. 双花括号表达式 ``` {{ msg | format }} ``` 2. v-bind 中 ``` <HelloWorld :msg="appMsg | format"></HelloWorld> ``` 3. 全局定义过滤器 ``` Vue.filter('format', (value) \=> { return `${value} qq 音乐` }) new Vue({ ... }) ``` 4. 串联使用,将 format 执行的结果当作参数传递给 format2 ``` <HelloWorld :msg="appMsg | format | format2"></HelloWorld> ``` 5. 给过滤器传递参数,appMsg的值是第一个参数,传递的参数是第二个参数 ``` <HelloWorld :msg="appMsg | format | format2('稻香')"></HelloWorld> ``` ![](https://img.kancloud.cn/14/5f/145f334b6bbdd800573fc048589e8fb1_1580x1740.png) ## 原理 1. 模版中的过滤器是如何变成这样的 _s(_f("format")(msg)) 代码字符串的 ``` function parseFilters (exp) { let filters = exp.split('|') let expression = filters.shift().trim() let i if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i].trim()) } } return expression } function wrapFilter(exp, filter) { const i = filter.indexOf('(') if(i < 0){ return `_f(${filter})(${exp})` }else{ const name = filter.slice(0, i) // format const args = filter.slice(i+1) // '123', '456', '789') return `_f(${name})(${exp}, ${args})` } } // 调用 parseFilters(`msg | format`) 结果 "_f(format)(msg)" // 多个参数的情况 parseFilters(`msg | format('123', '456', '789')`) // 结果 _f(format)(msg, '123', '456', '789')) ``` ![](https://img.kancloud.cn/8a/d4/8ad4bc34fb60db04c206872be945d2c6_2784x886.png) ![](https://img.kancloud.cn/aa/47/aa47acae5152c8bac7ec63333c38c325_2128x795.png) ### resloveFilter 是如何找到 $options 中的 filters的 ``` function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } ``` ![](https://img.kancloud.cn/fd/0c/fd0cb1c359c0004d52e564ede97b5a13_1862x1419.png) * 判断过滤器 id 是不是 string 类型 * 获取过滤器集合 * 检查过滤器集合是否存在 传入的 id 属性 -- 有则直接返回 * 把id转换成驼峰,在检查过滤器集合是否存在这个属性 -- 有则直接返回 * 把id转换成首字母大写,在检查过滤器集合是否存在这个属性 -- 有则直接返回 * 否则检查原型链 疑问: 1.app组件里的 filters 、 全局 filters 是什么时候挂在原型上的 _init 时, 调用 mergeOptions,合并vue默认和传入的options数据 2. resolveAsset查找filter时,为什么要尝试多种格式的id,驼峰、首字母大写,是因为filter注册和使用的时候可以不一致吗 ![](https://img.kancloud.cn/6e/a8/6ea8277a472eb856a7d2669fd7aebe0f_1593x329.png) ![](https://img.kancloud.cn/c2/c3/c2c3e0776b4df1a3a6c96db1e159c98e_1128x192.png) 3. filters 和 computed 的区别在哪里 ### 串联过滤器原理 ``` <HelloWorld :msg="appMsg | globalFormat | appFormatMsg2"></HelloWorld> ``` ![](https://img.kancloud.cn/91/5b/915bcdabeec1587a441a8708736983ff_2652x356.png) ### 带有参数的过滤器 ``` <HelloWorld :msg="appMsg | globalFormat | appFormatMsg2('稻香')"></HelloWorld> ``` ![](https://img.kancloud.cn/44/3d/443d9143bb34f0afe8c7d1bdcb26abd5_2379x358.png)