Understanding InitState in Vue

Understanding InitState in Vue

This article mainly introduces -initState in Vue data initialization. There is a certain reference value, friends in need can refer to it, I hope to help everyone.

This article mainly introduces -initState in Vue data initialization. There is a certain reference value, friends in need can refer to it, I hope to help everyone.

Data initialization

When a Vue instance is created, it will run a series of initialization operations, and in these initialization operations, the biggest association with data binding is initState.

First, take a look at his code:

function initState (vm) {
    vm._watchers = [];
    var opts = vm. $ options;
    if (opts.props) {
        initProps (vm, opts.props); // initialize props
    }
    if (opts.methods) {
        initMethods (vm, opts.methods); // initialize methods
    }
    if (opts.data) {
        initData (vm); // initialize data
    } else {
        observe (vm._data = (), true / * asRootData * /);
    }
    if (opts.computed) {
        initComputed (vm, opts.computed); // Initiate computed
    }
    if (opts.watch && opts.watch! == nativeWatch) {
        initWatch (vm, opts.watch); // initialize watch
    }
}

In the initialization of so much data, props, methods, and data are relatively simple (so I wo n’t introduce them in detail), while computed and watch are relatively difficult and the logic is more complicated, so I mainly talk about computed and watch (the following code section is simplified).

The initState mainly initializes the props, methods, data, computed and watch data in the Vue instance.

When the props are initialized (initProps), each property in the props is traversed, and then type verification, data monitoring, etc. (provide hook functions that throw warnings when the props property is assigned).

When initializing methods (initMethods), it is mainly to monitor whether the method names in methods are legal.

When data is initialized (initData), the observe function is run to deeply traverse each attribute in the data to perform data hijacking.

When computing is initialized (initComputed), it will monitor whether the data already exists on the data or props. If it exists, a warning will be thrown, otherwise the defineComputed function will be called to monitor the data and bind getters and setters to the properties in the component. If the value of a property in computed is a function, it defaults to the getter function of the property. In addition, the value of a property can also be an object. It only has three valid fields set, get, and cache, which indicate the setter, getter, and whether to enable caching of the property. Get is required. The cache defaults to true.

function initComputed (vm, computed) {
    var watchers = vm._computedWatchers = Object.create (null);

    for (var key in computed) {
        var userDef = computed [key];
        var getter = typeof userDef === 'function'? userDef: userDef.get;

        // Create a calculated property watcher
        watchers [key] = new Watcher (
            vm,
            getter || noop,
            noop,
            computedWatcherOptions
        );

        if (! (key in vm)) {
            // If the defined calculated property is not on the component instance, perform data hijacking on the property
            // defineComputed is very important, let's talk about it below
            defineComputed (vm, key, userDef);
        } else {
            // If the defined calculated property exists in data and props, throw a warning
        }
    }
}

When the watch is initialized (initWatch), the vm. $ Watch function is called to bind the setter callback for the property in the watch (if the component does not have the property, it cannot be successfully monitored, and the property must exist in props, data, or computed). If the value of the property in the watch is a function, it defaults to the setter callback function of the property. If the value of the property is an array, the contents of the array are traversed, which are the property binding callbacks. In addition, the value of the property can also be an object. At this time, the handler field in the object represents the setter callback function, immediate represents whether to immediately execute the handler method inside, and deep represents whether to listen in depth.

The vm. $ watch function will directly use Watcher to construct the observer object. The value of the attribute in watch exists as watcher.cb, and is executed in watcher.run when the observer is updated. Want to understand this process, you can see my introduction to Watcher in the vue responsive system-observe, watcher, dep.

function initWatch (vm, watch) {
    // Walk through the watch and create a listener for each attribute
    for (var key in watch) {
        var handler = watch [key];
        // If the attribute value is an array, iterate through the array and create multiple listeners for the attribute
        // createWatcher function encapsulates vm. $ watch, which will create a listener in vm. $ watch
        if (Array.isArray (handler)) {
            for (var i = 0; i <handler.length; i ++) {
                createWatcher (vm, key, handler [i]);
            }
        } else {
            // Create a listener for the property
            createWatcher (vm, key, handler);
        }
    }
}

function createWatcher (vm, expOrFn, handler, options) {
    // If the property value is an object, take the handler property of the object as a callback
    if (isPlainObject (handler)) {
        options = handler;
        handler = handler.handler;
    }
    // If the property value is a string, look for it from the component instance
    if (typeof handler === 'string') {
        handler = vm [handler];
    }
    // Create a listener for the property
    return vm. $ watch (expOrFn, handler, options)
}
Computed

Computed is essentially a lazy evaluation observer with cacheability. Only when the computed property is accessed for the first time after the dependency changes, the new value is calculated

The following explains this sentence.

As mentioned in the above code, when the data in the calculated attribute exists in data and props, it will be warned, that is, this approach is wrong. So in general, we will declare data directly in the calculated properties. Still in that code snippet, if the defined calculated attribute is not on the component instance, the defineComputed function is run to perform data hijacking on the data. Let's take a look at what is done in the defineComputed function.

function defineComputed (target, key, userDef) {
// Is it server rendering?
var shouldCache =! isServerRendering ();
// If we write the value of the calculated property as a function, then the function defaults to the get of the calculated property
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache?
// If it is not server-side rendering, the cache is used by default, and set to the cache function created by createComputedGetter
createComputedGetter (key):
// Otherwise do not use the cache, set get to userDef this function we define
userDef;
// Set set to an empty function
sharedPropertyDefinition.set = noop;
} else {
// If we write the value of the calculated attribute as an object, the object may contain three fields: set, get, and cache
sharedPropertyDefinition.get = userDef.get?
shouldCache && userDef.cache! == false?
// If we pass in the get field and it is not server-side rendering and the cache is not false,
// Set get to the cache function created by createComputedGetter
createComputedGetter (key): 
// If we pass in the get field, but the server-side rendering or cache is set to false, set get to the userDef function we defined
userDef.get:
// If no get field is passed, set get to an empty function
noop;
// Set set to the set field or empty function we passed in
sharedPropertyDefinition.set = userDef.set?
userDef.set:
noop;
}
// Although both get and set can be set to empty functions here
// But in the project, get for the empty function will give an error in the data value, and set for the empty function will give an error in the data value
// The main role of computed is to calculate the value, so the get field is required

// Data hijacking
Object.defineProperty (target, key, sharedPropertyDefinition);
}

In the previous vue responsive system--observe, watcher, and dep , I mentioned in the introduction of Watcher that when the calculated property watcher is instantiated, options.lazy will be set to true. Here is the calculated property laziness The key to evaluation and cacheability, of course, is that cache is not false.

cache is not false, it will call the createComputedGetter function to create a computed property getter function computedGetter,

First look at a piece of code

function createComputedGetter (key) {
    return function computedGetter () {
        var watcher = this._computedWatchers && this._computedWatchers [key];
        if (watcher) {
            if (watcher.dirty) {
            //watcher.evaluate updates the value of watcher and sets watcher.dirty to false
            // This will set watcher.dirty to true when the next dependency update is performed,
            // Then run this function again when the value is taken
                watcher.evaluate ();
            }
            // Dependency tracking
            if (Dep.target) {
                watcher.depend ();
            }
            // Return the value of watcher
            return watcher.value
        }
    }
}

// For calculated properties, when the value is calculated, it is found that the dirty of the watcher of the calculated property is true
// Indicates that the data is not up-to-date and needs to be recalculated. Here is the value of the calculated attribute.
Watcher.prototype.evaluate = function evaluate () {
    this.value = this.get ();
    this.dirty = false;
};

// When a dependency changes, notify it update
Watcher.prototype.update = function update () {
    // Three kinds of watchers, only the lazy property of the calculation property watcher is set to true, which means that lazy evaluation is enabled
    if (this.lazy) {
        this.dirty = true;
    } else if (this.sync) {
        // The run directly marked as synchronous calculation, the three major types are temporarily unavailable, so they will basically go to the following queueWatcher
        this.run ();
    } else {
        // Push the watcher into the observer queue, which is called when the next tick.
        // That is, the data changes are not updated immediately, but are updated in an asynchronous batch.
        queueWatcher (this);
    }
};

After options.lazy is set to true (only options.lazy for the property watcher is calculated is set to true), every dependency update will not actively trigger the run function, but set watcher.dirty to true. In this way, when the calculated property is fetched, the calculatedGetter function will be run. The calculatedGetter function has a judgment about watcher.dirty. When watcher.dirty is true, it will run watcher.evaluate to update the value and put the watcher. Dirty is set to false, which completes the lazy evaluation process. In the future, as long as the dependency is not updated, update will not be run, and watcher.dirty will not be set to true. When the value is taken again, watcher.evaluate will not be run to update the value, thereby achieving the effect of caching.

In summary, we learned that when the cache is not false, the calculated properties are lazy evaluated and cacheable, and the cache defaults to true. We also mostly use this default value, so we say Computed is essentially a lazy evaluation observer with cacheability. Only when the computed property is accessed for the first time after the dependency changes, the new value is calculated

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

10 Best Vue Icon Component For Your Vue.js App

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!

7 Best Vue Highlight Component for Your Vue App

7 Best Vue Highlight Component for Your Vue App

Vue highlight is often used to highlight text and syntax. Here are the 7 Vue highlight components I've collected.

Vue highlight is often used to highlight text and syntax. Here are the 7 Vue highlight components I've collected.

1. vue-snippets

Vue3 Snippets, This extension adds Vue3 Code Snippets into Visual Studio Code.

Download


2. vim-vue-plugin

Vim syntax and indent plugin for vue files

Download


3. vue-highlighter

Vue directive for highlight multiple istances of a word.

Download


4. vue-code-highlight

Beautiful code syntax highlighting as Vue.js component.

Download


5. Vue Prism Editor

A dead simple code editor with syntax highlighting and line numbers. 7kb/gz

Features

  • Code Editing ^^
  • Syntax highlighting
  • Undo / Redo
  • Copy / Paste
  • The spaces/tabs of the previous line is preserved when a new line is added
  • Works on mobile (thanks to contenteditable)
  • Resize to parent width and height
  • Support for line numbers
  • Support for autosizing the editor
  • Autostyling the linenumbers(optional)

Demo

Download


6. vue-highlight-words

A simple port from react-highlight-words

Vue component to highlight words within a larger body of text.

Demo

Download


7. vue-highlight-text

Vue component for highlight multiple istances of a word.

Demo

Download


Thank for read!

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Collection of 10 Vue Markdown Component for Vue.js App in 2020

Markdown is a way to style text on the web. The 10 Vue markdown components below will give you a clear view.

Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown.

The 10 Vue markdown components below will give you a clear view.

1. Vue Showdown

Use showdown as a Vue component.

View Demo

Download Source

2. showdown-markdown-editor

A markdown editor using codemirror and previewer using showdown for Vue.js.

View Demo

Download Source

3. markdown-it-vue

The vue lib for markdown-it.

View Demo

Download Source

4. perfect-markdown

perfect-markdown is a markdown editor based on Vue & markdown-it. The core is inspired by the implementation of mavonEditor, so perfect-markdown has almost all of the functions of mavonEditor. What's more, perfect-markdown also extends some features based on mavonEditor.

View Demo

Download Source

5. v-markdown-editor

Vue.js Markdown Editor component.

View Demo

Download Source

6. markdown-to-vue-loader

Markdown to Vue component loader for Webpack.

View Demo

Download Source

7. fo-markdown-note Component for Vue.js

fo-markdown-note is a Vue.js component that provides a simple Markdown editor that can be included in your Vue.js project.

fo-markdown-note is a thin Vue.js wrapper around the SimpleMDE Markdown editor JavaScript control.

View Demo

Download Source

8. Vue-SimpleMDE

Markdown Editor component for Vue.js. Support both vue1.0 & vue2.0

View Demo

Download Source

9. mavonEditor

A nice vue.js markdown editor. Support WYSIWYG editing mode, reading mode and so on.

View Demo

Download Source

10. vue-markdown

A Powerful and Highspeed Markdown Parser for Vue.

View Demo

Download Source

Thank for read!