【Vue Family Bucket】Options API

【Vue Family Bucket】Options API

1. data

The data attribute is passed in a function, and the function needs to return an object:

  • In Vue2 ,You can also pass in an object(although the official recommendation is a function);
  • In Vue3 ,A function must be passed in, otherwise an error will be reported directly in the browser;
  • The object returned in data will be hijacked by Vue's responsive system, and subsequent modification or access to the object will be processed in the hijacking:

Two, methods

The methods attribute is an object, usually we will define many methods in this object:

  • These methods can be bound into templates;

  • In this method, we can usethis keywordTo directly access the properties of the object returned in data;

  • Declared methods can be accessed directly through the component instance, or used in template syntax expressions. All methods automatically bind their thiscontext to the component instance, even when passed.

    Avoid using arrow functions when declaring methods, as they cannot thisaccess the component instance via .

Why can't arrow functions be used ?

  • The reason is that the arrow function is bound to the context of the parent scope, so thisit will not point to the component instance as expected
    • The arrow function uses the lookup rules of this, it will look up this in its upper layer
    • In the end, what I just found is the this that the script acts on, so it is window
    • Itthis cannot be window, because we cannot get the data in the data return object in window

3. Calculated properties

Computed properties are recommended for describing complex logic that relies on reactive state.

3.1 Basic usage of computed

Details :

Computed property usage :

  • option: computed
  • 类型:{[key:string]:funcition|(get:funcition,set function)}
  • Computed properties have a caching mechanism. When we use a calculated property multiple times, the calculation in the calculated property will only be executed once, and the calculated property will be re-executed only when the data on which the calculated property depends changes .

Give a chestnut: output words in reverse order

<div id="example">
  <p>Original message: "{
   
   { message }}"</p>
  <p>Computed reversed message: "{
   
   { reversedMessage }}"</p>
</div>
var vm = new Vue({
    
    
  el: '#example',
  data: {
    
    
    message: 'Hello world'
  },
  computed: {
    
    
    // 计算属性的 getter
    reversedMessage: function () {
    
    
      return this.message.split(' ').reverse().join(' ')
    }
  }
})

3.2 The difference between Computed and methods

  • We can define the same function as a method instead of a computed property.
  • The end result is indeed exactly the same both ways.
  • However, the difference is that computed properties are cached based on their reactive dependencies . They are only re-evaluated when the relevant reactive dependencies change.
  • This means messagethat multiple accesses to reversedMessagethe computed property will immediately return the previously computed result without having to execute the function again, as long as the has not changed.
  • In contrast, calling a method will always execute the function again whenever a re-render is triggered .
  • Why do we need caching? Suppose we have a computed property A with high performance overhead , which needs to traverse a huge array and do a lot of calculations. Then we may have other computed properties that depend on A. If there is no cache, we will inevitably execute A 's getter multiple times! If you don't want caching, use method instead.

4. Listening properties

4.1 Basic usage of watch

What is a listener?

  • During development, we define data in the object returned by data, and this data is bound to the template through interpolation syntax and other methods ;
  • When the data changes, the template will be automatically updated to display the latest data;
  • But in some cases, we want to monitor the change of a certain data in the code logic , at this time, we need to use the listener watch to complete;

The usage of the listener is as follows :

  • option: watch
  • 类型:{ [key: string]: string | Function | Object | Array}
  • watchThe default is shallow: the monitored property will only trigger the callback function when it is assigned a new value - and the change of the nested property will not be triggered (only for changes in the monitored data itself (internal occurrences) Changes cannot be listened to))

4.2 Listeners for immediate callbacks

watchThe default is lazy execution: the callback will only be executed when the data source changes. But in some scenarios, we want to execute the callback immediately when the listener is created. Say, for example, we want to request some initial data, then re-request the data when the relevant state changes.

We can declare the listener with an object that has handlera method and immediate: truean option to force the callback function to execute immediately:

 watch: {
    
    
    question: {
    
    
      handler(newQuestion) {
    
    
        // 在组件实例创建时会立即调用
      },
      // 强制立即执行回调
      immediate: true
    }
  }

4.3 Deep Monitoring

watchThe default is shallow: the listened property will only trigger the callback function when it is assigned a new value - and the change of the nested property will not trigger. If you want to listen to all nested changes, you need a deep listener:

  watch: {
    
    
    someObject: {
    
    
      handler(newValue, oldValue) {
    
    
        // 注意:在嵌套的变更中,
        // 只要没有替换对象本身,
        // 那么这里的 `newValue` 和 `oldValue` 相同
      },
      deep: true
    }
  }

4.4 The difference between Computed and Watch

For Computed:

  • It supports caching and will only be recalculated if the dependent data changes
  • Does not support asynchronous , when there are asynchronous operations in Computed, it is impossible to monitor data changes
  • Computed values ​​will be cached by default, and computed properties are cached based on their responsive dependencies, that is, calculated based on data declared in data or props passed by parent components.
  • If an attribute is calculated from other attributes, and this attribute depends on other attributes, computed is generally used
  • If the attribute value of the computed attribute is a function, then the get method is used by default, and the return value of the function is the attribute value of the attribute; in computed, the attribute has a get method and a set method, and the set method will be called when the data changes.

For Watches:

  • It does not support caching , when the data changes, it will trigger the corresponding operation
  • Support asynchronous monitoring
  • The monitored function receives two parameters, the first parameter is the latest value, and the second is the value before the change
  • When an attribute changes, you need to perform the corresponding operation
  • The monitoring data must be the data declared in the data or the data in the props passed by the parent component. When there is a change, other operations will be triggered. The function has two parameters:
    • immediate: The callback function is triggered immediately when the component loads
    • deep: In-depth monitoring to discover internal changes in data, used in complex data types, such as changes in objects in an array. It should be noted that deep cannot monitor changes inside arrays and objects.

Watches are needed when you want to perform asynchronous or expensive operations in response to constant changes.

Summarize:

  • computed computed attribute: depends on other attribute values, and the value of computed is cached, only when the value of the attribute it depends on changes, the value of computed will be recalculated the next time the value of computed is obtained.
  • watch listener: It is more of an observation function, no caching , similar to the monitoring callback of some data, whenever the monitored data changes, the callback will be executed for subsequent operations.

Application scenario:

  • When you need to perform numerical calculations and depend on other data, you should use computed, because you can use the cache feature of computed to avoid recalculation every time you get a value.
  • When you need to perform asynchronous or expensive operations when data changes, watch should be used. Use the watch option to allow asynchronous operations (access an API), limit the frequency of execution of the operation, and set an intermediate state before getting the final result . These are things that computed properties cannot do.

5. components

An object used to register components available to the current component instance.

export default {
    
    
  components: {
    
     TabControl }
  }

Guess you like

Origin blog.csdn.net/qq_53664443/article/details/129673978