The purpose of this article is to understand the content of the Vue API and to check for gaps. The basic API is not explained here.

Global configuration

Set via vue.config

  • silent
  • optionMergeStrategies
  • devtools
  • errorHandler
  • warnHandler
  • ignoredElements
  • keyCodes
  • performance
  • productionTip

Vue.config.errorHandler

Vue.config.errorHandler = function(err, vm, info) {console.log(' Component ${vm.$vnode.tag} Error: ${err.message},${info} ')}
mounted() {
  b  
},

log

Component XXX has an error: B is not defined,mounted hook

Global API

  • Vue.extend
  • Vue.nextTick
  • Vue.set
  • Vue.delete
  • Vue.directive
  • Vue.filter
  • Vue.component
  • Vue.use
  • Vue.mixin
  • Vue.compile
  • Vue.observable
  • Vue.version

Vue.extend

Using the base Vue constructor, create a “subclass.” The parameter is an object that contains the component options. Note that the data option is a special case and needs to be a function

Var Profile = vue.extend ({template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>', data: Function () {firstName: 'Walter', lastName: 'White', alias: 'Heisenberg'}}) // Create a Profile and mount it on an element. new Profile().$mount('#mount-point')
<div id="mount-point"></div> // <p>Walter White aka Heisenberg</p> // <p> // <div id="mount-point"></div> //

Vue.nextTick

A deferred callback that is executed after the DOM update loop has ended. Vue executes asynchronously when it updates the DOM

  • As soon as a data change is heard, Vue starts a queue and buffers all data changes that occur in the same event loop
  • If the same watcher is triggered multiple times, it will only be pushed into the queue once. This removal of duplicate data while buffering is very important to avoid unnecessary computation and DOM manipulation

Example: Modify MSG at this point.

Vm.msg = "11" console.log(" original ": MSG) vue. nextTick(function (){console.log(" updated ": MSG)})

2.1 New support for Promise

}) await vue.nextTick (). Then (function () {// await vue.nextTick ()).

Use $nextTick inside the component

Vue.set / Vue.delete

When the data is an array. We used it when we updated the subscripts

Vue.use()

Parameters: {Object | Function} the plugin

  • If the plug-in is an object, you must provide the install method
  • If the plug-in is a function, it will be treated as an install method. When the install method is called, the Vue is passed in as an argument
  • This method needs to be called before new Vue() is called.
  • When the install method is called multiple times by the same plug-in, the plug-in will only be installed once

Vue.compile(template)

Compiles a template string to the render function.

  • Note: Available in full version only

    var res = Vue.compile('<div><span>{{ msg }}</span></div>')
    
    new Vue({
    data: {
      msg: 'hello'
    },
    render: res.render,
    staticRenderFns: res.staticRenderFns
    })

    Vue.observable( object )

    Make an object responsive. It is used internally by Vue to handle objects returned by the data function

The returned object can be used directly within the rendering function and the computed properties, and updates are triggered when changes occur. It can also be used as a minimized cross-component state store for simple scenarios

const state = Vue.observable({ count: 0 })

const Demo = {
  render(h) {
    return h('button', {
      on: { click: () => { state.count++ }}
    }, `count is: ${state.count}`)
  }
}

Options/Data

  • data
  • props
  • propsData
  • computed
  • methods
  • watch

props

  • Array<string> | Object

    // simple syntax vue.component (props-demo-simple', {props: props: ['size', 'myMessage']}) // Object syntax to validate vue.component ('props-demo-advanced', {props: {// Check type height: Age: {type: Number, // Basic type default: 0, // Default: true, // Must add validator: Function (value) {return value >= 0}}}})

    propsData

  • { [key: string]: any }
  • Only used in instances created by new
  • Pass props when creating the instance. The main function is to facilitate testing

    var Comp = Vue.extend({
    props: ['msg'],
    template: '<div>{{ msg }}</div>'
    })
    
    var vm = new Comp({
    propsData: {
      msg: 'hello'
    }
    })

watch

Note: The arrow function should not be used to define the watcher function

Options/DOM

  • el
  • template
  • render
  • renderError

Options/lifecycle hooks

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • activated
  • derectived
  • beforeDestroy
  • destroyed
  • errorCaptured

All lifecycle hooks automatically bind the this context to the instance, so you can access the data and perform operations on properties and methods

  • Note: You cannot use arrow functions to define a lifecycle method (this does not refer to a Vue instance).

beforeCreate

The Data Observer and Event/Watcher events are called after the instance is initialized and before the event/watcher events are configured

created

Is called immediately after the instance is created.

  • The instance has completed the following configuration: data observer, property and method operations, watch/event callbacks.
  • The mount phase has not started yet and the $EL property is not available at this time.

beforeMount

Called before the mount begins: The associated render function is called for the first time

  • Note that this hook is not called during server-side rendering

mounted

  • Called after the instance is mounted, EL is replaced with the newly created vm.$EL
  • If the root instance is mounted on an element in a document, vm.$el is also in the document when the mounted instance is called
  • Note that mounted does not guarantee that all child components are mounted together
  • If you want to wait until the entire view is rendered, you can use vm.$nextTick internally

    mounted: function () {
    this.$nextTick(function () {
      // Code that will run only after the
      // entire view has been rendered
    })
    }
  • Note that this hook is not called during server-side rendering

beforeUpdate

  • Called when data is updated, before the virtual DOM is patched
  • This is a good place to access the existing DOM before updating, such as manually removing added event listeners
  • Note that this hook is not called during server-side rendering, because only the initial rendering takes place on the server side

updated

  • This hook is called after the virtual DOM is re-rendered and patched due to data changes
  • When this hook is called, the component DOM has been updated, so you can now perform operations that depend on the DOM
  • In most cases, you should avoid changing state during this time
  • If you want to change state accordingly, it’s usually best to use computed properties or watchers instead
  • Note that updated does not guarantee that all child components are redrawn together as well
  • If you want to wait until the entire view is redrawn, you can use vm.$nextTick in updated

    updated: function () {
    this.$nextTick(function () {
      // Code that will run only after the
      // entire view has been re-rendered
    })
    }
  • This hook is not called during server-side rendering

activated

Called when a component cached by keep-alive is activated

  • This hook is not called during server-side rendering

deactivated

Called when a component cached by keep-alive is deactivated

  • This hook is not called during server-side rendering

beforeDestroy

Called before the instance is destroyed, the instance is still fully available

  • This hook is not called during server-side rendering

    destroyed

    Called after the instance is destroyed. After this hook is called, all instructions for the VUE instance are untied, all event listeners are removed, and all child instances are destroyed

  • This hook is not called during server-side rendering

errorCaptured

Is called when catching an error from a descendant component

  • (err: Error, vm: Component, info: string) => ? boolean
  • Three parameters: the error object, the instance of the component in which the error occurred, and a string containing information about the source of the error
  • Returns false to prevent the error from continuing upward

Options/Resources

  • directives
  • filters
  • components

Options/Combination

  • parent
  • mixins
  • extends
  • provide/inject

mixins

var mixin = {
  created: function () { console.log(1) }
}
var vm = new Vue({
  created: function () { console.log(2) },
  mixins: [mixin]
})
// => 1
// => 2

extends

Allows a declaration to extend another component without having to use vue.extend

  • This is primarily for the convenience of extending the single-file component

    var CompA = { ... } // Inherit CompA var CompB = {extends: CompA... }

    provide/inject

    Allows an ancestor component to inject a dependency into all of its descendants

    Dojo.provide: Object | () = > Object inject: Array < string > | {[key: string] : string | Symbol | Object}

Options/Others

  • name
  • delimiters
  • functional
  • model
  • inheritAttrs
  • comments

functional

Make the component stateless (no data) and instance-less (no this context). They use a simple render function to return virtual nodes to make them less expensive to render

  • Functional component

model

Allows a custom component to customize the prop and event when using the V-model

  • By default, the V-model uses value as a prop
  • Use input as an event

    Vue.component('my-checkbox', {
    model: {
      prop: 'checked',
      event: 'change'
    },
    props: {
      // this allows using the `value` prop for a different purpose
      value: String,
      // use `checked` as the prop which take the place of `value`
      checked: {
        type: Number,
        default: 0
      }
    },
    // ...
    })
    <my-checkbox v-model="foo" value="some value"></my-checkbox>

    Is equivalent to

    <my-checkbox
    :checked="foo"
    @change="val => { foo = val }"
    value="some value">
    </my-checkbox>

Instances of the property

  • vm.$data
  • vm.$props
  • vm.$el
  • vm.$options
  • vm.$parent
  • vm.$root
  • vm.$children
  • vm.$slots
  • vm.$scopedSlots
  • vm.$refs
  • vm.$isServer
  • vm.$attrs
  • vm.$listeners

vm.$options

Initialization options for the current VUE instance

new Vue({
  customOption: 'foo',
  created: function () {
    console.log(this.$options.customOption) // => 'foo'
  }
})

vm.$slots

Type: {[name: string]:? Array<VNode> }

vm.$scopedSlots

Type: {[name: string] : props = > Array < VNode > | undefined}

vm.$refs

An object that holds all DOM elements and component instances that have been registered with the ref attribute

<base-input ref="usernameInput"></base-input>

this.$refs.usernameInput

vm.$isServer

Boolean, whether the current VUE instance is running on the server

vm.$attrs

Contains attribute bindings (except class and style) that are not recognized (and retrieved) as prop in the parent scope

Instance methods/data

  • vm.$watch
  • vm.$set
  • vm.$delete

Instance methods/events

  • vm.$on
  • vm.$once
  • vm.$off
  • vm.$emit

instruction

  • v-text
  • v-html
  • v-once
  • v-show
  • v-if
  • v-else
  • v-else-if
  • v-for
  • v-on
  • v-bind
  • v-model
  • v-slot
  • v-pre
  • v-cloak

v-pre

You don’t need an expression

  • Skip the compilation of this element and its children
  • Can be used to display the original Mustache tag. Skipping a large number of nodes without instructions speeds up compilation.

    <span v-pre>{{ this will not be compiled }}</span>

v-cloak

You don’t need an expression

  • This directive remains on the element until the associated instance completes compilation
  • Will not be displayed until compilation is complete

    [v-cloak] {
    display: none;
    }
    <div v-cloak>
    {{ message }}
    </div>

Special attribute

  • key
  • ref
  • is
  • slot
  • slot-scope
  • scope

key

Virtual DOM algorithm is mainly used in VUE to identify Vnodes when comparing old and new nodes

  • Instead of using keys, Vue uses an algorithm that minimizes dynamic elements and tries to modify/reuse elements of the same type in place whenever possible
  • When using keys, it reorders elements based on changes in keys and removes elements where keys do not exist.
  • Children that have the same parent element must have unique keys

ref

  • The ref is used to register reference information for elements or child components
  • The reference information will be registered on the parent component’s $refs object
  • If used on a normal DOM element, the reference refers to the DOM element
  • If used on a child component, the reference points to the component instance

    <! -- `vm.$refs.p` will be the DOM node --> <p ref="p">hello</p> <! -- `vm.$refs.child` will be the child component instance --> <child-component ref="child"></child-component>
  • When ref and v-for are used together, the ref you get will be an array containing the subcomponents of the corresponding data source.
  • $refs is not reactive and cannot be used for data binding in templates

is

For dynamic components and works based on the limitations of templates within the DOM

<! >< component v-bind:is="currentView"></component> <! -- This is necessary because '<my-row>' puts a --> <! - ` < table > ` may be rejected and be placed inside to the outside -- -- > < table > < tr is = "my - row" > < / tr > < / table >

Built-in component

  • component
  • transition
  • transition-group
  • keep-alive
  • slot