1. Calculate attributes

  1. define

    • Computed attributes: The attributes you want to use do not exist. To compute the attributes, you need a new computed configuration item
    • For Vue, the data in data are attributes. As long as the data in Vue changes, the template will be re-parsed, and the methods in interpolation syntax will be re-invoked
  2. The principle of

    • The bottom layer is usingObjcet.definepropertyGetters and setters provided by the method.
  3. When is the get function executed?

    • It is executed once on the first read.
    • whenDependent dataIt will be called again when changes occur.
  4. advantage

    • Compared with methods implementation, internal cache mechanism (reuse), higher efficiency, convenient debugging.
  5. note

    • The calculated properties will eventually appear on the VM (Vue instance) and can be read and used directly.
    • If the calculated property is to be modified, the set function must be written in response to the change, and the data on which the calculation depends must be changed.

    Grammar: 1.

 computed: {
     "Compute attribute name" () {
         return "Value"}}Copy the code

Requirement: Find the sum of 2 numbers to display on the page

<template> <div> <p>{{ num }}</p> </div> </template> <script> export default { data(){ return { a: 10, b: 20}}, // Calculate attributes: // Scenario: The value of a variable needs to be computed using another variable /* Syntax: computed attribute name () {return value}} */ / Note: Computed attributes and data attributes are both variables - cannot be the same name // Note 2: Variable changes within the function automatically recalculate results to return computed: { num(){ return this.a + this.b } } } </script> <style> </style>Copy the code

When a fullName is read, get is called and the return value is used to calculate the property. When is get called? 1. Read fullName for the first time. 2. When the dependent data changes.

 get(){
                console.log('Get is called')
                // console.log(this) // This is vm(Vue instance)
                return this.firstName + The '-' + this.lastName
            },
            
Copy the code

Set: The parameter called when the value of the evaluated property is modified receives the new value passed in

.computed: {fullName: {// What does get do? When someone reads the fullName, get is called and the return value is the fullName value
          // When is get called? 1. Read fullName for the first time. 2. When the dependent data changes.
          get(){
              console.log('Get is called')
              // console.log(this) // where this is vm
              return this.firstName + The '-' + this.lastName
          },
          // When is set called? When the fullName is modified.
          set(value){
              console.log('set',value)
              const arr = value.split(The '-')
              this.firstName = arr[0]
              this.lastName = arr[1]}}}})Copy the code

2. Monitor properties

<! @xxx="yyy" yyy can write some simple statements -->
<button @click="isHot = ! isHot">Switch the weather</button>
Copy the code

1. Monitoring property Watch:

  • When the monitored property changes, the handler callback function is automatically invoked to perform the related operation
  • Monitoring properties must exist in order to monitor!!
. Watch :{ishot :{immediate:true, // When the handler is called. When isHot changes. Handler (newValue,oldValue){console.log('isHot modified ',newValue,oldValue)}}}}) $watch('isHot',{immediate:true,}) $watch('isHot',{immediate:true,}) When isHot changes. Handler (newValue,oldValue){console.log('isHot changed ',newValue,oldValue)}})Copy the code

2. Deep monitoring

  • Deep monitoring:

    1) Watch in Vue does not monitor changes in internal values of objects by default (layer 1).

    2) Configure deep:true to detect internal value changes (multiple layers).

  • Remark:

1) Vue itself can monitor the change of the internal value of the object, but the watch provided by Vue cannot by default!

2) When using Watch, decide whether to adopt deep monitoring according to the specific structure of data.

data:{
	isHot:true.numbers: {a:1.b:1}},watch: {// Monitor the change of an attribute in a multilevel structure.
	/ * 'Numbers. A' : {handler () {the console. The log (' a changed ')}} * /
	// Monitor all attribute changes in the multilevel structure
	numbers: {deep:true.// Check if the address of numbers changes
		handler(){
			console.log('Numbers have changed')}}}Copy the code
  1. Monitoring properties – Short for

    This abbreviation is used when only handler() is in the monitoring property and no other configuration items need to be enabled

    watch:{
    	isHot(newValue,oldValue){
    		console.log('isHot has been modified ',newValue,oldValue,this)}}$watch('isHot',function (newValue,oldValue) {console.log('isHot modified ',newValue,oldValue,this)}) */
    Copy the code

3. Differences and principles

  1. The difference between computed and Watch
    • The watch can do what computed can do.
    • For example, with computed, the watch can perform asynchronous operations.
  2. Two important little rules
    • All functions managed by Vue are best written as normal functions, like thisThis points to the VM or component instance object.
    • All functions not managed by Vue (timer callbacks, Ajax callbacks, Promise callbacks, etc.) are best written as arrow functions, like thisThis points to the VM or component instance object.
watch:{
	firstName(val){
		setTimeout(() = >{
			console.log(this) // Vue instance object, which returns Window if normal functions are used
			this.fullName = val + The '-' + this.lastName
		},1000);
	},
	lastName(val){
		this.fullName = this.firstName + The '-' + val
	}
}
Copy the code