Summary of Vue's common APIs and advanced APIs

Summary of Vue's common APIs and advanced APIs

I've been itching to play around with Vue3.0 lately, and it feels great. So I quickly finished these issues of Vue2.0 and wrote some stuff for 3.0.
This article mainly lists and analyzes some APIs that I personally think are commonly used or have great uses, as notes and discussions for self-summary.

nextTick

Function:

Add a delayed callback after the next Dom update cycle ends. After modifying the data, you can get the updated Dom.
usage:

Vue.nextTick( [callback, context] )
vm.$nextTick( [callback] )
// Usage 2
// Use as a Promise (new since 2.1.0)
Vue.nextTick()
 .then(function () {
  // DOM updated})

illustrate:

callback: delayed callback function
context: optional object
ps: New since 2.1.0: If no callback is provided and in an environment that supports Promise, a Promise is returned. Please note that Vue does not come with a polyfill for Promise, so if your target browsers do not natively support Promise (IE: why are you all looking at me), you will have to provide the polyfill yourself.

Extensions:

Regarding the execution mechanism and usage scenarios of nextTick, we must also master similar requestAnimationFrame() and process.nextTick(). The former is a built-in listener for the browser (executed before the next redraw), and the latter is executed at the next event polling time point in the node environment.

Mixins

Function:

Registers a mixin, affecting every Vue instance created after registration. Plugin authors can use mixins 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!"

illustrate:

object: a vm attribute or method
ps: Please use global mixins with caution, as it will affect every separately created Vue instance (including third-party components). In most cases, this should only be used for custom options, like the example above. It is recommended to publish it as a plugin to avoid duplicating the mixin.

$forceUpdate

Function:

Forces the Vue instance to re-render.
usage:

vm.$forceUpdate()

set, delete

Function:

Set and delete the properties of responsive data, and trigger view updates.
usage:

// Usage 1
Vue.set( target, key, value )
Vue.delete( target, key )
// Usage 2
vm.$set( target, key, value )
vm.$delete( target, key )

illustrate:

target: target object
key: the name of the attribute to be added
value: the attribute value to be added
ps: The main usage scenario can avoid the limitation that Vue cannot detect that the property has been deleted

filter

Function:

Used for some common text formatting and some standard data mapping.
usage:

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

<!-- In `v-bind` -->
<div v-bind:id="rawId | formatId"></div>
// Register filters: {
 capitalize: function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
 }
}
// Global registration Vue.filter('capitalize', function (value) {
 if (!value) return ''
 value = value.toString()
 return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
 // ...
})

illustrate:

Filter functions always receive the value of the expression (the result of the previous chain of operators) as the first argument.
Filters should be added at the end of a JavaScript expression, indicated by the "pipe" symbol.

ps: A filter can accept multiple parameters, such as {{ message | filterA('arg1', arg2) }}. Here, 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.

directive

Function:

Used to register custom directives.

usage:

<!-- When the page loads, this element will receive focus --> 
<input v-focus>
// Register a global custom directive `v-focus`
Vue.directive('focus', {
 // When the bound element is inserted into the DOM...
 inserted: function (el) {
  // Focus element el.focus()
 }
})
// Register a local directive. The component also accepts a directives option directives: {
 focus:
  // Definition of instruction inserted: function (el) {
   el.focus()
  }
 }
}

illustrate:

inserted is just one of the interpolation functions of the registration instruction. The complete registration attributes can also include:
bind: Called only once, when the directive is first bound to an element, where you can perform a one-time initialization setup.
inserted: called when the bound element is inserted into the parent node (it is only guaranteed that the parent node exists, but has not necessarily been inserted into the document).
update: Called when the VNode of the component is updated, but it may happen before its child VNodes are updated. The value of the directive may or may not have changed, but unnecessary template updates can be ignored by comparing the values ​​before and after the update.
componentUpdated: Called after the VNode of the component where the instruction is located and its child VNodes are all updated.
unbind: Called only once, when the directive is unbound from the element.

Vue.directive('my-directive', {
 bind: function () {},
 inserted: function () {},
 update: function () {},
 componentUpdated: function () {},
 unbind: function () {}
})

Other simple common properties and methods

// console.log(vm.$root); 
vm.$root //Instance object vm.$el //Root element (real DOM element)
// console.log(vm.$el);

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

vm.$data //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 a component, it refers to the parent element // console.log(vm.$parent);

vm.$children //In a component, refers to child elements // console.log(vm.$children);

vm.$attrs //Used to get all attributes passed from the parent component // console.log(vm.$attrs);

vm.$listeners //Used to get all methods passed from the parent component // console.log(vm.$listeners);

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

vm.$scopedSlots //Used to access scoped slots // console.log(vm.$scopedSlots);

vm.$refs //Used to locate DOM elements (using ref for tracking)
// console.log(vm.$refs);

vm.$watch //Used to monitor data (will be automatically destroyed after being used in the vue file)
// console.log(vm.$watch);

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

vm.$on //Used to monitor event dispatching// console.log(vm.$on);

vm.$once //Only listen to the event once (no more listening afterwards)
// console.log(vm.$once);

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

Summarize

This article mainly includes several commonly used APIs in vue. If you are interested in learning more, you can refer to its official website. I hope this article is useful to you and can be skillfully applied to actual project development.

For easy reading and understanding, the code of this article has been uploaded to Github

If there are any errors in the article, please point them out in the comment section. If it helps, please like and follow.

The above is the detailed summary of Vue's commonly used APIs and advanced APIs. For more information about Vue's commonly used APIs and advanced APIs, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Encapsulate axios in vue and implement unified management of api interfaces
  • Example of using Composition API of Vue3.0
  • Detailed explanation of the ideas and methods of Axios encapsulation API interface in Vue
  • The vue project is packaged as an APP, and the static resources are displayed normally, but the API request cannot perform data operations
  • How to call swagger API elegantly in Vue using typescript
  • vue sets the global access interface API address operation
  • Vue connects to the backend API and deploys it to the server
  • Vue project interface management, all interfaces are managed and operated uniformly in the apis folder
  • How VUE uses axios to call the background API interface
  • WebStorm cannot correctly identify the solution of Vue3 combined API

<<:  Analysis of MySQL's method of implementing fuzzy string replacement based on regular expressions

>>:  Detailed tutorial on how to delete Linux users using userdel command

Recommend

mysql5.5.28 installation tutorial is super detailed!

mysql5.5.28 installation tutorial for your refere...

Analysis and solution of data loss during Vue component value transfer

Preface In the previous article Two data types in...

Tutorial on migrating mysql from phpstudy to Linux

Project Purpose Migrate the data in MySQL 5.5.53 ...

MySQL 5.7.23 installation and configuration method graphic tutorial

This article records the installation tutorial of...

Install MySQL 5.7.18 using rpm package under CentOS 7

I have been using MySQL recently. The article mys...

Database backup in docker environment (postgresql, mysql) example code

Table of contents posgresql backup/restore mysql ...

Vue makes a simple random roll call

Table of contents Layout part: <div id="a...

Docker primary network port mapping configuration

Port Mapping Before the Docker container is start...

Regular expression usage in CSS selectors

Yes, CSS has regular expressions too (Amen) Two p...

Deploy grafana+prometheus configuration using docker

docker-compose-monitor.yml version: '2' n...

MySQL query optimization: causes and solutions for slow queries

Friends who are doing development, especially tho...

Linux remote login implementation tutorial analysis

Linux is generally used as a server, and the serv...

CentOS 8.0.1905 installs ZABBIX 4.4 version (verified)

Zabbix Server Environment Platform Version: ZABBI...

Using js to achieve waterfall effect

This article example shares the specific code of ...