Vue basic syntax: calculated, watch, and filters

1. Vue instance options

When instantiating Vue objects, you need to provide a series of configuration information for the constructor of Vue. The code is as follows:

new Vue({
	//option
})

When creating a Vue instance using the new operator, you can pass in an option object for the instance. There are many types of data in the option object. The details are as follows:

  • Data options: data, props, propsData, computed, methods, watch
  • DOM options: el, template, render, renderError
  • Lifecycle options: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed, activated, deactivated, errorCaptured
  • Resource options: directives, filters, components
  • Combination options: parent, mixins, extends, provide, inject
  • Other options: name, delimiters, functional, model, inheritAttrs, comments

For the learning of options, you can refer to the API documents on the Vue official website. In this chapter, the tutorial only explains the three core options of Vue: calculation attribute, filter and listener.

2. Calculated attribute

2.1 basic usage of computed

The calculated attribute is calculated in the Vue instance option. The calculated value is an object type. The attribute value in the object is a function, and the function cannot receive parameters. If you want to transfer parameters for a calculated attribute, you can use the closure method.

It should be noted here that the calculation attribute cannot be declared as an arrow function! Because this in the arrow function points to this in the context, the Vue instance object this cannot be obtained in the function that calculates the attribute.

Calculation attributes have the following characteristics:

  • Too much logic in the template will make the template too heavy and difficult to maintain. Using calculation attributes can make the template more concise.
  • Computed properties are cached based on their responsive dependencies.
  • computed is more suitable for returning a result value after processing multiple variables or objects, that is, if a value in several variables changes, the value we monitor will also change.

Example code:

<div id="app">
	<p>{{ total }}</p>
</div>
<script type="text/javascript">
	new Vue({
		el: '#app',
		data: {
			a: 1
		},
		computed: {
			total(n) {
				return this.a + 5
			}
		}
	})
</script>

The results of running in the browser are as follows:

2.2. Pass calculated as a function parameter

Although the attribute value of the calculated object is declared as a function, the usage of calculated is the same as that of data. It is used as an attribute. If you want to use calculated as a function, you can return a closure function. The example code is as follows:

<div id="app">
	<p>{{ total(6) }}</p>
</div>
<script type="text/javascript">
	new Vue({
		el: '#app',
		data: {
			a: 1
		},
		computed: {
			total() {
				return (n) => {
					return this.a + n
				}
			}
		}
	})
</script>

The effect of running in the browser is as follows:

2.3 differences between calculation attributes and functions

Although the declaration process of calculated attributes and functions is very similar, there are still functional differences. The biggest difference is that the calculated attributes can be cached according to the responsive data they depend on. In short, in the function calculating the attribute declaration, if the returned value depends on the responsive data declared in data, Only when the data in the dependent data changes, the current calculation attribute function will be re executed. Otherwise, the cached results after the last execution will be directly obtained. The advantage of this is that it can improve performance and reduce unnecessary repeated operations.

The example code is as follows:

<div id="app">
     <!--  
        When called multiple times reverseString  When 
        Just the inside num If the value does not change, it will return the result of the first calculation directly
    until data Medium num The calculation will not occur again until the value changes
     -->
    <div>{{reverseString}}</div>
    <div>{{reverseString}}</div>
     <!-- call methods He will call it again every time -->
    <div>{{reverseMessage()}}</div>
    <div>{{reverseMessage()}}</div>
  </div>
  <script type="text/javascript">
    /*
      The difference between calculation attributes and methods: calculation attributes are cached based on dependencies, while methods are not cached
    */
    var vm = new Vue({
      el: '#app',
      data: {
        msg: 'Nihao',
        num: 100
      },
      methods: {
        reverseMessage: function(){
          console.log('methods')
          return this.msg.split('').reverse().join('');
        }
      },
      //The declaration of the computed attribute is a peer relationship with the data attribute and methods attribute 
      computed: {
        //The reverseString property name is custom 
        reverseString: function(){
          console.log('computed')
          var total = 0;
          // When the value of num attribute in data changes, the reverseString function will automatically calculate  
          for(var i=0;i<=this.num;i++){
            total += i;
          }
         // return is required in the reverseString function, otherwise the calculated value cannot be obtained in the page    
          return total;
        }
      }
    });
  </script>

2.4. getter and setter functions for Calculating Properties

Although the calculation attribute can be valued like the data attribute, if you want to assign a value to the calculation attribute, you must use the setter method. The example code is as follows:

<div id="app">
	<p>{{ total }}</p>
	<button @click="reset()">Recalculate</button>
</div>
<script type="text/javascript">
	new Vue({
		el: '#app',
		data: {
			a: 1
		},
		computed: {
			total: {
				get() {
					return this.a + 5
				},
				set(num) {
					// Receive assignment in reset() function
					this.a = num
				}
			}
		},
		methods: {
			reset() {
				this.total = 10
			}
		}
	})
</script>

Before clicking the recalculate button:

After clicking the recalculate button:

If you assign a value to the calculation attribute total in the reset() function, it will be received by the set() function in the calculation attribute, and then pass the value to the a variable in data. At this time, the obtained calculation attribute value is the result after the updated a variable + 5.

3. Listener (watch)

3.1 basic usage of watch

Watch is a listener whose value is an object. The attribute values in the object can be functions, objects and arrays. When an attribute in data needs to change the internal value during the observation period, you can monitor the change of the data attribute through watch.

The basic usage of the watch listener is as follows:

  • Use watch to respond to changes in data
  • It is generally used for asynchronous or expensive operations
  • The attribute in the watch must be the existing data in the data
  • When it is necessary to monitor the changes of an object, the ordinary watch method cannot monitor the changes of the internal attributes of the object. Only the data in data can monitor the changes. At this time, the deep attribute is required to deeply monitor the object

Example code:

<!-- Verify user name -->
<div id="app">
  <div>
    Last name:<input type="text" v-model='lastName'>
  </div>
  <div>
    Name:<input type="text" v-model='firstName'>
  </div>
  <div>
  	Full name:{{fullName}}
  </div>
</div>

<script type="text/javascript">
  var vm = new Vue({
    el: '#app',
    data: {
      firstName: 'Zhang',
      lastName: 'three'
    },
    // Calculation properties
    watch: {
      firstName(val) {
        this.fullName = val + ' ' + this.lastName;
      },
      lastName(val) {
        this.fullName = this.firstName + ' ' + val;
      }
    }
  });
</script>

The firstName in the watch object corresponds to the firstName in data. When the firstName value changes, the execution of the firstName() function in the watch will be automatically triggered. Similarly, lastName in watch corresponds to lastName in data.

There are two parameters of the function attribute in the watch object. The first parameter is the new value corresponding to the modified attribute of the same variable name in data, and the second parameter is the old value before the modification of the data attribute.

3.2. Configuration item of listener

If the data attribute value to be monitored is an object or array, and if the object nesting level is deep, you need to turn on the deep monitoring of watch. The example code is as follows:

new Vue({
	el: '#app',
	data: {
		num: {
			a: 1,
			b: 2,
			c: {
				d: 3
			}
		}
	},
	watch: {
		num: {
			deep: true, // Turn on depth monitoring
			handler(val, oldVal) {
				//...
			}
		}
	}
})

4. filter

4.1 what is the use of filter

  • Vue.js allows custom filters that can be used for some common text formatting.
  • Filters can be used in two places: Double curly bracket interpolation and v-bind expressions.
  • The filter should be added at the end of the JavaScript expression, indicated by the "pipe" symbol

4.2. Global filter

Vue's global API provides the function Vue.filter() for registering global filters. After the global filters are registered, all components can use them.

Global filter example code:

<div id="app">
    <input type="text" v-model='msg'>
      <!-- upper Defined as a filter function that receives a single parameter, the expression  msg  The value of is passed into the function as an argument -->
    <div>{{msg | upper}}</div>
    <!--  
      Support cascading operation
      upper  Defined as a filter function that receives a single parameter, the expression msg The value of is passed into the function as an argument.
	  Then continue to call the filter also defined to receive a single parameter lower ,take upper Pass the results of to lower in
 	-->
    <div>{{msg | upper | lower}}</div>
    <div :abc='msg | upper'>test data</div>
  </div>

<script type="text/javascript">
  //  lower is the global filter     
  Vue.filter('lower', function(val) {
    return val.charAt(0).toLowerCase() + val.slice(1);
  });

  new Vue({
  	el: '#app'
  })
</script>

4.3 local filter

The local filter is declared in the filters in the Vue instance object option. It should be noted here that the global registration is filter without s, while the local filter is filters with S.

After the local filter is registered, it can only be used in the registered components. The example code is as follows:

var vm = new Vue({
  el: '#app',
  data: {
    msg: ''
  },
  filters: { 
    upper: function(val) {
      return val.charAt(0).toUpperCase() + val.slice(1);
    }
  }
});

The definitions of the filters attribute and data methods have been leveled, and the filters in filters are defined as local filters. upper in the above code is a custom filter name. upper is defined as a filter function that receives a single parameter. The value of the expression msg will be passed into the function as a parameter. The filter must have a return value so that the result can be obtained when the filter is used by the outside world.

4.4 filter in series

And the filter can be used in series. Here, the value of filter1 is taken as the parameter of filter2.

{{  data | filter1 | filter2  }}

4.5 filter transmission parameters

The example code is as follows:

<div id="box">
  {{ message | filterA('arg1', 'arg2') }}
</div>
<script>
	  Vue.filter('filterA',function(n,a,b){
		 if(n<10){
		   return n+a;
		 }else{
		   return n+b;
		 }
	});

	new Vue({
	  el:"#box",
	  data:{
	    message: "Ha ha ha"
	  }
	})
</script>

In the above code, filterA is defined as a filter function that receives three parameters. The value of message is the first parameter, the ordinary string 'arg1' is the second parameter, and the value of expression arg2 is the third parameter.

In the filter, the first parameter corresponds to the data n in front of the pipe character. At this time, it corresponds to message, the second parameter a corresponds to the argument arg1 string, and the third parameter b corresponds to the argument arg2 string.

Keywords: Vue Vue.js filter

Added by Mordred on Sun, 28 Nov 2021 19:35:05 +0200