Finishing the advanced front-end series, can be regarded as an interview review, can also be regarded as a combat view, to share their convenience, convenient to others. Comments are welcome if there are deficiencies

Party 1: CSS Advanced

The second party: JS advanced

Third party: VUE framework advanced

The fourth party: engineering

MVC Architecture (Model, Controller, View)

  • View: detects user input and operation (keyboard and mouse) behavior, and calls Controller to execute corresponding logic. The View update requires refetching the Model’s data.
  • Controller: Is the application layer for collaboration between View and Model, responsible for business logic processing.
  • Model: Data layer, notifies View to update View through observer mode after data changes.

Advantages:

  • Modularity: low coupling, replaceable, expandable and reusable
  • Multiple View updates: Using the observer pattern, you can implement data updates by notifying multiple views of a single Model

Disadvantages:

  • Strong dependence: View and Model are highly dependent and difficult to separate into components

Core principles of THE MVVM framework

As can be seen in the figure, views bind events to Model via THE DOM Listeners of ViewModel, which manage the Data in view through Data Bindings. The View-Model acts as a connection bridge.

Check it out in more detail

Two-way data binding (reactive) principle

Vue. js adopts data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty() to publish messages to subscribers when data changes and trigger corresponding listening callback.

Vue needs three modules to achieve this effect:

  • Observer: The ability to listen for all attributes of a data object and notify subscribers of any changes to the latest values
  • Compile: Scans and parses the instructions of each element node, replaces the data according to the instruction template, and binds the corresponding update function
  • Watcher: Acts as a bridge between the Observer and Compile, and is able to subscribe to and receive notification of each property change, execute the corresponding callback function of the directive binding, and update the view

Vue buckets

Component penetration (component communication, life cycle)

  • Use kebab-case my-component-name or MyComponentName

Component communication:

  1. Between father and son:props -- $emit
  2. this.$parent.event$refs.xxx. Property/methods: Get the child methods and properties directly from the parent
  3. EventBus mode: create a Vue eventBus object and passbus.$emitTrigger event,bus.$onListen for trigger events.

Use of scaffolding

Vue Loader

This plugin is a must! Address the other rules you have defined and apply them to the corresponding language blocks in the.vue file. For example, if you have a rule that matches /\.js$/, it will be applied to the

Routing principle

HashHistory: uses the hash(“#”) in the URL

  • Hash is used to guide browser action and is completely useless on the server side, so changing the hash does not reload the page.
  • You can add listening events for hash changes:

window.addEventListener("hashchange", funcRef, false)

  • Every time changeHash (window. The location. The hash)Adds a record to the browser’s access history

With these features, front-end routing can be implemented to update the view without rerequesting the page

HashHistory.push()

The flow from setting route changes to view updates is as follows:

$router.push()
--> HashHistory.push() 
--> History.transitionTo() 
--> History.updateRoute() 
--> { app._route = route } 
--> vm.render() Copy the code

HashHistory.replace()

It’s similar to push(), except that the current route is replaced by the window.location.replace method.

HTML5History:

Use the new HTML5 method pushState\replaceState

  • PushState () and replaceState() allow us to modify the browser history stack
window.history.pushState(stateObject, title, URL)
window.history.replaceState(stateObject, title, URL)
Copy the code

Implementation principle: The structure of the code and the logic of updating the view are basically similar to the hash mode, except that window.location.replace() is directly assigned to window.location.hash, Instead call the history.pushState() and history.replacEstate () methods.

Prepare an Abstract schema for non-browser environments.

Vuex principle

State: Stores data (equivalent to data)

The properties we set in state will be stored in the root element, this._modules = new ModuleCollection(options) // initialized

Const state = this._modules.root.state // Get the state defined

When vuEX is initialized, it first obtains the value defined in the state attribute new ModuleCollection(options) for module collection (reassembly of relevant attributes in store), and finally forms a Module tree.

Getter: method for getting store properties (equivalent to computed)

Mutations: The only way to change the state in the store is to submit mutation, similar to methods.

The view can change the data in state by clicking on events that trigger methods in mutattions, and getters reflects the data to the view.

Action: Commit mutation to change the state

Actions are simply one more layer to handle asynchrony.

Dispatch, commit

When we fire the click event in VUE, we fire the methods in Methods. Vuex, however, does not work. There must be something to trigger it, which is equivalent to the custom on\emit event.

The relationship is that dispatch triggers methods in actions, commi in action triggers methods in mutions.

Proxy versus Object.defineProperty?

Advantages of Proxy:

  • You can listen directly on objects instead of properties
  • You can listen for changes in the array directly
  • The Proxy returns a new object, and we can just manipulate the new object to do thatObject.definePropertyCan only be modified directly by traversing object properties
  • As a new standard, browser vendors will continue to focus on performance optimization.

TODO: object.defineProperty has the following advantages:

Principle of virtual DOM

The Virtual DOM is an abstraction of the DOM, essentially a JavaScript object that is a more lightweight description of the DOM.

The starting point

The original purpose of Virtual DOM is better cross-platform. For example, Node.js does not have DOM. If you want to implement SSR(server-side rendering), one way is to use Virtual DOM, because Virtual DOM itself is a JavaScript object.

The mainstream

Is a basic requirement of the modern front-end framework does not need to manually DOM, on the one hand because of manual DOM cannot guarantee program performance, collaboration projects if you don’t strict review, there may be a developer write performance low code, on the other hand, more important is to omit the manual DOM manipulation can greatly improve the development efficiency.

The implementation process

A ** function is required to create a single Virtual DOM **. This function is very simple, takes certain parameters, and returns an object based on these parameters. This object is the DOM abstraction.

/ * ** generate vnode* @param {String} type, such as 'div'* @param {String} key Specifies the unique ID of a key Vnode* @param {Object} data data, including attributes, events and so on* @param {Array} children Child Vnode* @param {String} text Text* @param {Element} elm * @return {Object} vnode * / function vnode(type, key, data, children, text, elm) {  const element = {  __type: VNODE_TYPE,  type, key, data, children, text, elm  }  return element } Copy the code

2, The DOM is a Tree, so we need to declare a “function to create an abstraction of the DOM Tree” — a Virtual DOM Tree.

3. The Virtual DOM is ultimately a JavaScript object, and we need to find a way to map the Virtual DOM to the real DOM. In other words, we need to declare a function that “transforms a VNode into a real DOM.”

4. The diff of the Virtual DOM is the most difficult and core part of the entire Virtual DOM. The purpose of diFF is to compare the old and new Virtual DOM trees to find out the differences and update them.

Optimization of Virtual DOM

Snabbdom.js has been the mainstream Virtual DOM implementation in the community. Vue 2.0 phase and Snabbdom.js ** all adopt the “double end comparison algorithm” explained above, so are there any optimization schemes to make it faster?

In fact, there are faster algorithms in the community, Inferno. Js, for example, “claims to be the fastest React-like framework” (although its performance isn’t just due to the algorithm, inferno. Js’s diff algorithm is the fastest yet), and “Vue 3.0 will be optimized using inferno.

What exactly does a key in Vue do?

In the process of diFF algorithm, the beginning and end of the new node will be compared with the end of the old node. When there is no match, the key of the new node will be compared with the old node, and then the difference will be exceeded.

Fast: The uniqueness of the key can be fully utilized by the Map data structure. The time complexity of the Map is only O(1) compared to the time complexity of the traversal search O(n).

The principle of $nextTick

Defer the callback until after the next DOM update cycle. Use the data immediately after you modify it, and then wait for DOM updates.

<template>
 <div id="example">{{message}}</div>
</template>
<script>  var vm = new Vue({  el: '##example'. data: {  message: '123'  }  })  vm.message = 'new message' // Change the data  console.log(vm.$el.innerHTML) / / '123'  Vue.nextTick(function () {  console.log(vm.$el.innerHTML) // 'new message'  }) </script> Copy the code

In the example above, when we update the data with vm.message = ‘new message’, the component does not immediately rerender. When the event queue is refreshed, the component is re-rendered in the next event loop “TICK”. NextTick (callback) is used to put operations based on the updated DOM state into the callback function, which will be called after the DOM update is complete.

Why does the data change frequently but only update once

Vue performs DOM updates asynchronously

Optimized the first screen loading performance

This point is actually talking about the white screen problem, the white screen time is “when the user presses the ok button from the address bar to the first content drawing (see the first content).” “So solving the white screen problem is the key optimization point.” ** Let’s first sort out what happens during the white screen time:

  1. Press Enter. The browser parses the URL and performs A DNS query. The query returns an IP address and sends an HTTP(S) request through the IP address
  2. The server returns the HTML and the browser starts parsing the HTML, triggering a request for JS and CSS resources
  3. Js is loaded, js is executed, various functions are called to create the DOM and render it to the root node until the first visible element is generated

Open HTTP2

  1. Http2 is much more efficient
  2. It can be multiplexed
  3. Http2 can be compressed with headers, saving network traffic for headers

Use skeleton screen

Party 1: CSS Advanced

The second party: JS advanced

Third party: VUE framework advanced

The fourth party: engineering

Students feel helpful can point a praise ha, to encourage 😊

This article is formatted using MDNICE