Vue.js Ice Breaker Series-4 Computing Properties, Monitors and Filters

1 computed compute attribute

The general format of instructions mentioned in the previous chapter is:

Instruction name [: parameter arg] [. modifiers] [= expression]

Where expression is parsed as js code in the scope of the instance to which it belongs. As I mentioned earlier in v-on event monitoring, there are three ways to handle events:

  • Add js code to the expression of instructions
  • Encapsulate event processing logic into methods and bind methods to events
  • Call methods in expressions using introverted statements

These three approaches are executed as js code in the instance scope to which the binding element belongs. When the logic of the js code in an expression is too complex, the previous approach is to use method references. Here we introduce a way to use computational attributes as the content of the expression.

1.1 Definition of computational attributes

Computing attributes are placed in the computed option. Since they are attributes, there are getter and setter methods, so the normal way to define them is as follows:

<div id="app">
  <!-- Use js Statements and computational attributes as instruction expressions -->
  <h4 v-text='`${this.firstName} ${this.lastName}`'></h4>
  <h4 v-text='fullName'></h4>
</div>
<script>
var vm = new Vue({
  el:"#app",
  data:{
    firstName:"Michael",
    lastName:"Jackson",
  },
  computed:{
    fullName:{
      get:function(){
        return `${this.firstName} ${this.lastName}`;
      },
      set:function(name){
        let tmp = name.split(' ');
        this.firstName = tmp[0];
        this.lastName = tmp[1];
      }
    }
  }
});
</script>

It defines fullName as a computational property and its getter and setter methods. The compute attribute is called directly in the expression of the instruction, which calls the getter method of fullName. When assigning fullName, vue calls its setter method. In general, setter methods are rarely used, so vue provides us with a short form of computational attributes that are only getter methods.

var vm = new Vue({
  computed:{
    fullName:function(){
       return `${this.firstName} ${this.lastName}`;
    }
  }
});

The abbreviation is that the attribute name is followed directly by an anonymous function, which is the getter function. You can also define getter function in object after attribute name, but not setter function. This method is not often used, so there is no code demonstration here.

1.2 Differences between Computational Attributes and Methods

As in the example above, if we can also define a getFullName() method, return the same character format, and then use this method in the expression of instructions, we can achieve the same goal. In this way, the definition of computational attributes is much more troublesome than that of methods.

In fact, the biggest difference between calculating attributes and methods is that calculating attributes has caching function. When using methods, the results will be calculated and returned every time, while calculating attributes will only be recalculated when the lazy items inside them change, and the results will be returned and cached. When the internal dependencies do not change, they belong to Sex returns cached results directly, so calculating attributes is slightly more efficient than the method. The internal lazy items here are firstName and lastName.

2 watch monitor

2.1 Definition of Monitor

Vue uses watch to monitor changes in data, where "data" refers to a wide range of values, either in the data option, or in the props option, or in third-party plug-ins (such as changes in the middle route of the routing plug-in vue-route).

Vue uses the watch option to define the listener, which is followed by an object whose key is the data or expression to be observed, and whose value is that the key liberates the changed processing logic in the form of the following:

  • This function is also called a callback function. When the listener key changes, the vue calls the function. The callback function has two parameters: the value after the change (new value) and the value before the change (old value).
  • Method Name Form, which defines a processing method in addition to the watch option, specifies the method in the watch by the form of a string
  • Object form, in addition to specifying callback functions, object form can also use other options to define listeners in this form, the function is the most complete. Object keys include:
    • handler key: specify callback function
    • Deep key: bool value, which indicates whether or not deep listening is true. If the watch listens on an object, then any property of the object changes (no matter how many layers the property is nested), the handler callback function will be called.
    • IMmediate key: Indicates whether the listener is called immediately. Normally, the listener object should have a value first. When the value changes, watch is triggered. However, when an immediate is set, the listener callback will also be triggered when the object is first assigned.
  • Array form, as mentioned above, whether in function form, method name form or object form, they can only define a callback function. Array form is to encapsulate the above form into an array, so that when the value changes, there can be multiple callback functions.
<script>
	var vm = new Vue({
    el:"#app",
    data:{
    	a: 1,
    	b: 2,
    	c: {
      	c1: 3
    	},
      d:4
  	},
    watch:{
      //Functional Form
      a:function(newValue,oldValue){},
      //Method Name Form
      b:"callback",
      //Object Form
      c:{
        handler:function(newValue,oldValue){},
        deep:true,//Optional
        immediate:true,//Optional
      },
      //Array form, which can define multiple callback functions
      d:[
        //Functional Form
        function(newValue,oldValue){},
        //Method Name Form
        "callback",
        {
          //Use method name form in object
          handler:"callback",
          deep:true,
          immediate:true,
        }
      ]
    },
    methods:{
      callback(newValue,oldValue){}
    }
  });
</script>

2.2 Monitor Example

When using vue-route plug-in to do front-end routing, it can monitor routing changes in breadcrumb components and change the value of breadcrumbs. Vue-route is injected through the plug-in function of vue. After injection, vue-route provides us with two objects, $router and $route. We can access the router through this.$router in any component and the current route through this.$route. The following chapters will introduce route.

We need to listen for the $route object and make a response change when the routing changes.

var vm = new Vue({
  watch:{
   '$route':function(to, from) {
      // Response to routing changes...
    }
  }
});

3 filters filter

Filters are often used for display formatting. For example, when we retrieve user information from the server, gender fields represent user gender, 0 for female, 1 for male, and 2 for unknown. If the value of 012 is displayed directly on the interface, the user will not know the meaning of these numbers. At this time, we can use filters to format the display.

3.1 Definition of filter

vue uses the filter option to define the filter, which is followed by the object, and defines the filter function in the object. In HTML templates, pipe | is used in js expressions to add filters. Note that when defining a filter function, the first parameter of the function is the calculated result value of the expression before the pipe symbol.

<body>
  <div id="app">
    <!-- Expression Pipeline Character Filter -->
    <span>{{gender | genderFilter}}</span>
  </div>
  <script>
  	var vm = new Vue({
      el:"#app",
      data:{
        gender:0,
      },
      filters:{
        //Define the filter, value is the result of the expression before the pipe symbol
        genderFilter:function(value){
          let strGender = "";
          switch(value){
            case 0:
              strGender = "female";
              break;
            case 1:
              strGender = "male";
              break;
            default:
              strGender = "Unknown";
              break;
          }
        }
      }
    });
  </script>
</body>

The filter function can set any number of parameters, but the first parameter must be the result of the expression in front of the pipeline. As follows, we define a filter A, which has two parameters. When called, the first parameter is passed invisibly.

<body>
  <div id="app">
    <!-- The filter defines two parameters, the first is implicit transfer, the second is display transfer, so here's the foo The second parameter -->
    <span>{{gender | genderFilter("foo")}}</span>
  </div>
  <script>
  	var vm = new Vue({
      el:"#app",
      data:{
        gender:0,
      },
      filters:{
        //The filter can define multiple parameters, but the first must be the result of the expression before the pipe character
        filterA:function(value,arg1){}
      }
    });
  </script>
</body>

After the filter can also be connected to the filter, here is no longer in-depth.

3.2 Examples of Filters

Enumeration filter

In practical development, we can use enumeration filters to simplify the use of filters. Here we define an enumeration of bool type. There is no enumeration in js. We use arrays to define:

//enums.js
export const BoolEnum = [
  {key:0,value:"no"},
  {key:1,value:"yes"},
]

Define filter function

//filters.js
export const enumFilter function(value,enums){
  for (let i = 0; i < enums.length; i++) {
        let item = enums[i];
        if (item.key == key) {
            return item.value;
        }
    }
    return "N/A";
}

Use in HTML templates

<body>
  <div id="app">
    <span>Whether to enable:{{isActive | enumFilter(boolEnum)}}</span>
  </div>
  <script>
    import {BoolEnum as boolEnum} from 'enums.js'
    import {enumFilter} from 'filters.js'
  	var vm = new Vue({
      el:"#app",
      data:{
        isActive:0,
      },
      filters: {
    		enumFilter
  		},
    });
  </script>
</body>

Format Money Filter

When we customize instructions, we introduced formatting numbers by instructions. Now we use filters to achieve this function:

//filters.js
export const moneyFilter function(value){
  value = value + "";
  let hasDot = /\./g;
  let patt = /\B(?=(\d{3})+\.)/g
  if (!hasDot.test(value)) {
    //Regular expressions without decimal points
    patt = /\B(?=(\d{3})+$)/g
  }
  return value.replace(patt, ",");
}

Use in HTML templates

<body>
  <div id="app">
    <input type="text" v-model="total">
    <br>
    <span>Total price:{{total | moneyFilter}}</span>
  </div>
  
  <script>
    import {moneyFilter} from 'filters.js'
  	var vm = new Vue({
      el: "#app",
      data: {
        total: 1234567890,
      },
      filters:{
        moneyFilter,
      }
    });
  </script>
</body>

Tags: Vue Attribute

Posted on Tue, 03 Sep 2019 00:31:09 -0700 by troinfo