Recently, I met a very good candidate, who was experienced and had technical highlights, but failed to answer some minor questions well and was rejected. During the interview, I was particularly impressed by a question about the difference between filter and computed attributes in Vue. Unfortunately, the candidates did not answer it on the spot. Here is a summary:
The difference between filter and computed
1. Trigger timing is different
The processing logic behind computed attributes is complex. The data update notification mechanism of Vue is relied on, and the calculation is triggered again only when other data items dependent on attributes change. The advantage is that the calculation frequency is relatively low; Disadvantages are dependent on components, it is difficult to extract into independent logic, that is, low reusability.
Filter is much simpler and only fires when explicitly invoked, usually for template rendering. The advantage is that it is easy to abstract outside the component; The disadvantage is that the calculation needs to be recalculated each time the template is rendered. You can see the difference in call timing by using an example:
2. Different application scope
Computed is widespread and can be used in other computed, methods, lifecycle functions, and templates. Filter is usually only used for template rendering, but if you want to reuse it elsewhere, you need to use this._f:
Vue.component('HelloWorld', {
filters: {
hello() {
return 'hello'; }},methods: {
ping() {
return `The ${this._f('hello') (the)} world`; }}})Copy the code
In addition, filter supports chained calls in use, which increases its ability to combine concatenation:
<span> {{ name | normalize | capitalize }} </span>
Copy the code
3. Define the method
Finally, note that computed attributes can only be defined within a component or through a mixins object; There are two ways to define a filter: first, by using the filters attribute inside the component. The first is defined outside the component via vue. filter:
Vue.component('HelloWorld', {
filters: {
hello() {
return 'hello'; }}}); Vue.filter('hello', () = >'hello');
Copy the code
Application of the rules
In summary, filter cannot be cached and is called frequently, so it is particularly suitable for formatted output scenarios, such as date formatting. Filters have composite invocation capabilities, so you can define a set of basic, simple filters at the project architecture level that can be combined within components as needed.
Computed attributes have caching capabilities and are more universal within components, so they are suitable for complex data transformation, statistics, and other scenarios.