-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
面试官:Vue中的过滤器了解吗?过滤器的应用场景有哪些? #22
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
面试官:Vue中的过滤器了解吗?过滤器的应用场景有哪些?
一、是什么
过滤器(
filter
)是输送介质管道上不可缺少的一种装置大白话,就是把一些不必要的东西过滤掉
过滤器实质不改变原始数据,只是对数据进行加工处理后返回过滤后的数据再进行调用处理,我们也可以理解其为一个纯函数
Vue
允许你自定义过滤器,可被用于一些常见的文本格式化ps:
Vue3
中已废弃filter
二、如何用
vue
中的过滤器可以用在两个地方:双花括号插值和v-bind
表达式,过滤器应该被添加在JavaScript
表达式的尾部,由“管道”符号指示:定义filter
在组件的选项中定义本地的过滤器
定义全局过滤器:
注意:当全局过滤器和局部过滤器重名时,会采用局部过滤器
过滤器函数总接收表达式的值 (之前的操作链的结果) 作为第一个参数。在上述例子中,
capitalize
过滤器函数将会收到message
的值作为第一个参数过滤器可以串联:
在这个例子中,
filterA
被定义为接收单个参数的过滤器函数,表达式message
的值将作为参数传入到函数中。然后继续调用同样被定义为接收单个参数的过滤器函数filterB
,将filterA
的结果传递到filterB
中。过滤器是
JavaScript
函数,因此可以接收参数:这里,
filterA
被定义为接收三个参数的过滤器函数。其中
message
的值作为第一个参数,普通字符串'arg1'
作为第二个参数,表达式arg2
的值作为第三个参数举个例子:
小结:
三、应用场景
平时开发中,需要用到过滤器的地方有很多,比如单位转换、数字打点、文本格式化、时间格式化之类的等
比如我们要实现将30000 => 30,000,这时候我们就需要使用过滤器
四、原理分析
使用过滤器
在模板编译阶段过滤器表达式将会被编译为过滤器函数,主要是用过
parseFilters
,我们放到最后讲首先分析一下
_f
:_f 函数全名是:
resolveFilter
,这个函数的作用是从this.$options.filters
中找出注册的过滤器并返回关于
resolveFilter
内部直接调用
resolveAsset
,将option
对象,类型,过滤器id
,以及一个触发警告的标志作为参数传递,如果找到,则返回过滤器;resolveAsset
的代码如下:下面再来分析一下
_s
:_s
函数的全称是toString
,过滤器处理后的结果会当作参数传递给toString
函数,最终toString
函数执行后的结果会保存到Vnode
中的text属性中,渲染到视图中最后,在分析下
parseFilters
,在模板编译阶段使用该函数阶段将模板过滤器解析为过滤器函数调用表达式小结:
parseFilters
将过滤器编译成函数调用(串联过滤器则是一个嵌套的函数调用,前一个过滤器执行的结果是后一个过滤器函数的参数)resolveFilter
函数找到对应过滤器并返回结果toString
函数,而toString
执行后,其结果会保存在Vnode
的text
属性中,渲染到视图参考文献
The text was updated successfully, but these errors were encountered: