Vue Common apis and advanced apis

Recently, my hand is itching to play with Vue3.0, very comfortable, hurry to finish this few Vue2.0, write some 3.0 things.

This article mainly lists and analyzes some common or useful apis, as a self-summary note and discussion.

nextTick


Function: Add a delayed callback after the end of the next Dom update loop. After the data is modified, the updated Dom can be retrieved. Usage:

Vue.nextTick( [callback, context] )
vm.$nextTick( [callback] )
2 / / usage
// Use as a Promise (added from 2.1.0)
Vue.nextTick()
  .then(function () {
    // The DOM is updated
  })
Copy the code

Description:

  • Callback: delay callback function
  • Context: Optional object

Ps: Added since 2.1.0: Return a Promise if no callback is provided and in a promise-supporting environment. Please note that Vue does not come with a Promise polyfill, so if your target browser does not support Promises natively, you will have to provide your own polyfill.

Extension: For nextTick’s execution mechanism and usage scenarios, we must also understand requestAnimationFrame(), which is a browser listener (executed before the next redraw), and process.nexttick (), which is a Node listener. At the next event polling point in time.

mixin


Function: Register a mixin that affects all Vue instances created after registration. Plug-in authors can use blending to inject custom behavior into components. Usage:

// Inject a handler for the custom option 'myOption'.
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello! '
})
// => "hello!"
Copy the code

Description:

  • Object: A VM property or method

Ps: Use global mixin with caution, as it affects each individually created Vue instance (including third-party components). In most cases, this should only apply to custom options, as in the above example. It is recommended to publish it as a plug-in to avoid mixing in duplicate applications.

$forceUpdate


Function: Force the Vue instance to re-render. Usage:

vm.$forceUpdate()
Copy the code

Note: Note that it only affects the instance itself and the child components inserted into the slot contents, not all child components.

Set, delete


Function: Set and delete attributes of responsive data, and trigger view update. Usage:

1 / / usage
Vue.set( target, key, value )
Vue.delete( target, key )
2 / / usage
vm.$set( target, key, value )
vm.$delete( target, key )
Copy the code

Description:

  • Target: Indicates the target object
  • Key: indicates the name of the attribute to be added
  • Value: indicates the value of the attribute to be added

Ps: The main use scenario, can avoid Vue can not detect the property is deleted restrictions

filter


Functions: Used for some common text formatting and some canonical data mapping. Usage:

<! -- in double curly braces -->
{{ message | capitalize }}

<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
Copy the code
/ / register
filters: {
  capitalize: function (value) {
    if(! value)return ' '
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)}}Copy the code
// Register globally
Vue.filter('capitalize'.function (value) {
  if(! value)return ' '
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)})new Vue({
  // ...
})
Copy the code

Description:

  • The filter function takes the value of the expression (the result of the previous chain of operations) as its first argument.
  • Filters should be added at the end of JavaScript expressions, indicated by the “pipe” symbol.

Ps: filter can accept multiple parameters, such as {{message | filterA (arg1, arg2)}}, here, filterA is defined as receiving three parameters of the filter function. The value of message is the first argument, the normal string ‘arg1’ is the second argument, and the value of the expression arg2 is the third argument.

directive


Function: Used to register custom directives. Usage:

<! -- This element gets focus when the page loads --> 
<input v-focus>
Copy the code
// Register a global custom directive 'v-focus'
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})
Copy the code
// Register the local directives. The component also accepts a directives option
directives: {
  focus: {
    // Directive definition
    inserted: function (el) {
      el.focus()
    }
  }
}
Copy the code

Description:

  • Inserted is just one of the interpolation functions of the registration directive. The full registration properties can also include:
    • Bind: called only once, when a directive is first bound to an element, where one-time initialization can be performed.
    • Inserted: Called when the bound element is inserted into the parent node (only ensures that the parent exists, but not necessarily that it has been inserted into the document).
    • Update: called when the component’s VNode is updated, but may occur before its children are updated. The value of the directive may or may not have changed, but you can ignore unnecessary template updates by comparing the values before and after the update.
    • ComponentUpdated: component VNode directive and its children VNode all updated call.
    • Unbind: called only once, when a directive is unbound from an element.
Vue.directive('my-directive', {
  bind: function () {},
  inserted: function () {},
  update: function () {},
  componentUpdated: function () {},
  unbind: function () {}})Copy the code

Other simple commonly used properties and methods

// console.log(vm.$root); 
vm.$root    // Instance object

vm.$el  // The root element (the real DOM element)
// console.log(vm.$el);

vm.$el.innerHTML    // Get the contents of the root element (the real DOM element)
// console.log(vm.$el.innerHTML);

vm.$data    // The data object under the instance
// console.log(vm.$data);

vm.$options     // Mount items under the instance
// console.log(vm.$options);

vm.$props   // Data for communication between components
// console.log(vm.$props);

vm.$parent      // In components, refers to the parent element
// console.log(vm.$parent);

vm.$children    // In components, refers to the child element
// console.log(vm.$children);

vm.$attrs   // To get all properties passed by the parent component
// console.log(vm.$attrs);

vm.$listeners   // To get all methods passed by the parent component
// console.log(vm.$listeners);

vm.$slots   // Slot in the component
// console.log(vm.$slots);

vm.$scopedSlots     // Used to access the scope slot
// console.log(vm.$scopedSlots);

vm.$refs    // To locate the DOM element (with ref tracing)
// console.log(vm.$refs);

vm.$watch   // Used to listen for data (automatically destroyed when used in a vue file)
// console.log(vm.$watch);

vm.$emit    // Used to distribute events (usually used for data communication)
// console.log(vm.$emit);

vm.$on  // Used to listen for event dispatch
// console.log(vm.$on);

vm.$once    // Listen for events only once (not after)
// console.log(vm.$once);

// Life cycle
beforeCreate(){}created(){}beforeMount(){}mounted(){}beforeUpdate(){}updated(){}beforeDestroy(){}destroyed(){}Copy the code

conclusion

This article mainly includes these apis commonly used in VUE. If you are interested in learning more, please refer to its official website. Hope this article is useful to you, and can skillfully apply to the actual project development.

The code has been uploaded to Github for easy reading

If there are any mistakes in this post, feel free to correct them in the comments section. If it helps, feel free to like or follow.