Framework class

The virtual DOM of vue

A. the b. the C. the D. the

Vue abstracts DOM into an abstract tree composed of JavaScript objects and simulates real DOM with VNode nodes. You can add, delete, change and check nodes in this abstract tree. This process does not need to operate the real DOM. By updating these small unit views, you can eliminate a lot of unnecessary DOM manipulation and greatly improve performance.

advantages

  • Cross-platform function: Because virtual DOM is based on JS objects and does not depend on the real platform environment, it has the advantages of cross-platform, including browser, nodeJs, weeX, which improves the possibility of isomorphism for the front and back ends.
  • Improved rendering performance: With our large and frequent data updates, the view can be reasonably and efficiently updated.
  • Improve browser performance: We put the DOM comparison operation in the JS layer, because the execution speed of DOM operation is far less fast than that of JS, so we move a large number of DOM operations to JS, and use patching algorithm to calculate the nodes that are really updated, so as to minimize DOM operations and significantly improve performance.

Refer to the link

Vue patch algorithm

The core algorithm is diFF algorithm, which is a highly efficient algorithm with only O (n) time complexity by comparing nodes in the same layer tree rather than searching and traversing the tree layer by layer.

Substitution rule:

  1. When a new node has no children and an old node has children, all children of that DOM node are removed
  2. If the old node has no children and the new node has children, clear the DOM text of the old node and add children to the current DOM node
  3. If the old and new nodes are equal to children, diff the children and call updateChildren

What is the MVVM framework for VUE

MVVM framework is the concept of the whole view layer view, belonging to the concept of the view layer, the full name means: model-view-view model

  • Model: Refers to the data passed by the back end
  • View: Refers to the page you see
  • View model: Is the core of MVVM pattern, it is the bridge between view and model, involving two S data transfer directions:

1) Convert the model into a view, that is, convert the data passed by the back end into the page you see. The implementation method is data binding

2) Convert the view into a model, that is, the page you see is converted into back-end data by means of event listening

Under the MVVM framework, the view and model cannot communicate directly, but need to communicate through the View Model. By implementing an observer, when the data changes, the View Model listens for the change and notifies the corresponding view for automatic update. When the user operates the view, the ViewModel can also listen for the change of the view. The data is then notified to make changes to achieve two-way binding of the data

Differences between Vue computer and Watch and application scenarios

A. the b. the C. the D. the

Computer attribute

  • Calculate attribute
  • Cache-based, does not recalculate if the page is re-rendered but the values it relies on have not changed
  • Simplified template {{}} expression to handle passes to props

Watch the attribute

  • Is a listening action
  • The handle function is executed if the value of the monitored property changes
  • Listen for prop changes in child components to perform corresponding actions

The lifecycle execution order of vUE’s parent and child components

  • Loading the rendering process
Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent MountedCopy the code
  • Child component update process
Parent beforeUpdate -> Child beforeUpdate -> Child updated -> Parent updatedCopy the code
  • Destruction of the process
Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyedCopy the code

Vue life cycle

  • beforeCreate:Data, Watcher, and Methods do not exist before data detection and initialization events have started.
  • created:Called after the instance is created, this stage can access data, use Watcher, Events, methods, data observation and data listening events are configured, but the DOM is not mounted.
  • beforeMount:The HTML is parsed into AST nodes, and then the render function is dynamically generated according to the AST nodes. The related render function is called for the first time
  • mounted:Called after the mount is complete, executes the render function to generate the virtual DOM, creates the real DOM to replace the virtual DOM, and mounts it on the instance. The dom can be manipulated in this hook function.
  • beforeUpdate:Called after vm.data is updated and before the virtual DOM is re-rendered, this hook can modify vm.data without triggering additional re-rendering.
  • updated:Called after the virtual DOM is re-rendered, and if you modify data here, beforeUpdate,updated again, enters an endless loop.
  • beforeDestory:Called before the instance is destroyed. The instance can still be called from this hook
  • destory:Called after the instance is destroyed, all event listeners are removed, and the subinstance is destroyed

Vue invokes the asynchronous request at that lifecycle stage. The best asynchronous request can be invoked at any stage, since the asynchronous function is executed before the full-lifecycle hook function is executed. However, for the sake of user experience, it is best to invoke asynchronous requests in Created. The earlier data is retrieved, the more timely the mounted instance is mounted.

Refer to the article

Vue’s keep-alive function

A. the b. the C. the D. the

Keep-alive is an abstract component of Vue that keeps the state of the components it wraps around from being destroyed, avoiding repeated rendering and creation of components.

<keep-alive :include = 'whiteList' :exclude = 'blackList' :max='amount' >
  <router-view></router-view>
</keep-alive>
Copy the code
  • indeludeDefine a cache whitelist. Keep-alive caches hit components
  • excludeDefine a cache blacklist. Hit components will not be cached
  • maxDefine the cache component upper limit, beyond which the cache data is replaced with LRU’s policy

Attributes: This tag includes include and exclude, which can be expressed as a string or regular expression. The former is only cached for matched components, and the latter is not cached for matched components

Life hooks: Provides two life hooks: the Activated life cycle is called when the component is activated and the deactivated life cycle is called when the component is disabled.

Source analysis

  1. Instead of defining the component, the component name is set tokeep-aliveThat define theabstractProperties fortrue.propsThe property defineskeep-aliveThe component supports all parameters.
  2. Hook functions are defined during the lifecycle
    1. createdInitialize the set of two objects that cache vNodes (virtual DOM) and the corresponding vNode keys
    2. destoryedDelete the vNode instance cached in this.cache and the deStory hook function for the corresponding component instance
    3. mountedListen for include and exclude parameters, and update (delete) them in real time

Vue data bidirectional binding principle

A. the b. the C. the D. the

The data bidirectional binding of VUE is realized by using data hijacking combined with publishe-subscribe mode. Its core is to use object.definePrototype () method, which can realize the readable, traversable and enumerable permissions of Object attributes, and perform get and set operations by monitoring the changes of data

Realizing three modules

  • Compile compiler: parses template instructions during project initialization, replaces variables in the template with data, initializes render page views, binds the corresponding node of each instruction to update functions, adds subscribers to listen for data, and updates views when notified of data changes.
  • Listener: Adds getters and setters to properties of data objects and subproperties to listen for and hijack elements of data, and sends updates to subscribers when changes are detected.
  • Subscriber: 1) Add itself to the attribute subscriber (DEP) when instantiating itself; 2) When the dep.notice() notification is triggered by a property change, it can call its own update() method and trigger the callback bound in compile to update the view.

Refer to the connection

Reference Link 2

React vs. Vue. Why vue

  1. Data flow and design idea: vueJS design idea is responsive, based on variable data, data flow is bidirectional; React’s overall design is functional. Components are designed as pure components, and state and logic are passed in through parameters. Data flows are one-way.

  2. Update performance: React changes in the state of a component cause the entire subtree of the component to be re-rendered from the root; (Solution: Use immutable data structures whenever possible and use shouldComponentUpdate whenever possible); Vue allows you to know exactly which components actually need to be rerendered, and components’ dependencies are automatically tracked during its rendering, so the entire component doesn’t have to be completely rendered. Vue is superior to React in terms of update performance

  3. Syntax: React HTML and CSS are written using JAVASCRIPT. All components are rendered using JSX. Vue provides writing templates in HTML;

Refer to the link

Differences between VUe2.0 and VUe3.0

  • Project directory structure
    1. Vue 3.0 removes the configuration file directory, config, and build folders
    2. Add a public folder and place index.html in public
  • Project configuration
    1. The domain name configuration was moved from the config folder to vue.config.js
  • Support visual interface, using vue UI command in the project can be configured, dependent operations
  • The principle of two-way data binding is based onObject.definepropotypeTo use proxy object proxy, to solve the problem that only support the object’s new elements can be monitored.

The core algorithm of Patch is diFF algorithm

A. the b. the C. the D. the

The diff algorithm of Vue only diff between vnodes at the same level of D, recursively diff of vnodes at the same level, and finally realize the update of the whole DOM tree

Diff algorithm core function implementation process

  • For the first rendering, render the VDOM as a real DOM and insert it into the container
function element(vnode){ var tag = vnode.tag; var attrs = vnode.attrs || {}; var children = vnode.children || []; var elm = document.createElement(tag); if(! tag) return; for(var attrName in attrs){ if(attrs.hasownprototype(attrName){ elem.setAttribute(attrName,attrs[attrName]); } children.forEach(function(childNode){ elem.appendChild(createElement()) }) } }Copy the code
  • When rendering again, compare the new virtual node with the old one

Vuejs implements the principle of data-driven view

A. the b. the C. the D. the

Data drive is one of the biggest features of Vuejs. It is realized through MVVM framework, including three parts: Model, View, viemodel. The data-driven principle is that developers don’t need to manually modify the DOM when data changes, but instead use an observer to drive data.

The process is as follows:

  • When vueJS is instantiated, it iterates over the data option passed to the instantiated object and uses all of its attributesObject.definePropertyConvert these properties into getters/setters
  • One for each instance objectwatcherObject, which uses the getter to access the data property during template compilation and is recorded as a dependency to establish a relationship between the data and the view
  • When we render a view with a change in its data dependencies (i.e., a change in the setter), the observer compares whether the data has changed before and after and decides whether to notify the view to re-render.

Babel converter

Js editor (es6 +) is a js editor that converts es6 + code into backwardly compatible JS syntax and runs in current and older browsers, essentially a toolchain

Implementation of Babel

The core consists of parse, Transform, and Generator. The execution process is as follows

  1. Source code passThe compilerConvert to abstract syntax tree AST
  2. Pass the abstract syntax tree ASTconverterConvert to get a new AST tree
  3. Pass the new AST treeThe generatorRegenerate the code so that it can run safely in the browser

Vue slot slot usage

The slot element is used as an outlet to distribute content, to determine what content to carry, and to insert it into a designated location to implement what we want to display.

advantages

  • You can use the parent component’s data and have the same instance properties as the parent component, which is a good way to implement parent-child parameter passing
How does VUe2.0 implement bidirectional data binding, and how does VUe3.0 implement it? What problem does this solve

Vue2.0 is a two-way binding of data via data hijacking combined with publish subscription. The core is to monitor data changes through getter and setter of Object.defineProperty (), and then to achieve data update rendering through the subscriber. This mainly involves several modules: the interaction between listeners, compilers and subscribers

  • Compiler: scans the elements of each template at project initialization and parses them into data objects and initializes the subscriber
  • Listener: Listens for and hijacks data elements, and sends updates to subscribers when changes are detected
  • Subscriber: Bridge between compiler and listener, receives signal, executes updated function to update view

Vue3.0 implements data hijacking through proxy. The advantages are:

  • DefineProperty can only listen for a property, not for all objects
  • You can detect changes in the data inside the array without having to do specific operations on the array alone

Understand vueJs nextTick()

Application scenario:

  • The Created () hook function in the lifecycle of the Vue does dom manipulation in thethis.nextTick()In the callback function of.

The DOM is not rendered at the time the Created hook function is executed, so dom manipulation is not possible, but with this.nexttick () it is possible to manipulate the DOM at the time the Created hook function is executed

  • You can use this method immediately if you need to modify the data and get the updated DOM in the case of a delayed callback after the next DOM update loop.
  • This prevents an operation that needs to be performed when the data changes, and that requires changing the DOM structure with the data changesthis.nextTick()perform

Refer to the blog

Vue’s asynchronous dom update strategy

  • When a responsive data changes, its setter function notifies the DEP, and the DEP calls all watch objects it manages, triggering the Update implementation of the Watch object.
  • Instead of updating the view immediately, watch objects are pushed into a queue in a waiting state. During this time, many watch objects can be pushed into the queue (and deduplicated), and these watch objects will not be iterated until nextTick runs. Update the view.

The purpose of nextTick is to generate a callback function and put it into the task execution stack of VUE. When the stack is finished, the callback function is called to execute the RUN function in the watch object of the queue and update the view, which can achieve such an asynchronous trigger purpose. And executing the DOM in the finished callback ensures that the DOM used is the most up-to-date

The purpose of asynchronous updates is to change the value of test many times in the mount function. In the case of no asynchronous updates, the DOM update view will be directly manipulated for each update, which can be very costly in performance. VueJS implements queue, and uniformly executes the run method of the watch object of the queue in the next tick, and performs the de-replay operation. If the watch object with the same ID is not added to the queue repeatedly. So the performance is greatly optimized.

Vue Method of obtaining route parameters

  • Obtain the dynamic parameters by defining dynamic routes

Setting method: In the route configuration file, the path attribute is added with the /: parameter name, and then carries the parameter in the actual route address

This.$route.params.id is the router object

  • In the use ofthis.$router.push()This function, you can define itParamsPass parameters to define dynamic routes that are not compatible
  • queryandpathPassing parameters
  • nameparamas

The problem with v-if and V-for being used together

Reason: V-for has a higher priority than V-IF, which means v-IF runs in every V-for loop

Solutions:

  • Instead of using V-if, use calculated attributes and filter to filter out information that does not need to be displayed

A figure of speech commonly used in vue

  • .stop: Prevents bubbles
  • .prevent: Blocks the default event
  • .once: The event is triggered only once
  • .lazy: By default, usev-modelSynchronize the input field value with the data each time the input event is triggered, but when we add.lazyFigures of speech, will turnchangeSynchronize after the event (that is, when you lose focus or hit enter)
  • .number: Converts the input value to type Number
  • .trim: Automatically filters out the first and last Spaces

What is Node.js?

Node. js is a JavaScript environment based on the Chrome V8 engine.

There is a problem with the current server program:

  • The number of concurrent connections is valid. As clients grow, if you want your Web application to support more users, you need to add more servers, increasing server costs, traffic costs, and labor costs.
  • Potential technical issues: Users may use different servers for different requests, so sharing resources requires sharing by all servers.

Maximum bottleneck: The maximum number of concurrent connections that the server can handle

NodeJS proposed solution: Change the connection to the server. Instead of generating an OS thread for each connection, each connection emits an event that runs in the Node engine process. So nodeJS handles high-concurrency tasks by changing the way they connect to the server.

Advantages: Node.js uses an event-driven, non-blocking I/O model and asynchronous programming, making it lightweight and efficient.

Disadvantages: single process, single process, only support single-core CPU, can not fully use the multi-core CPU server, once the process collapsed, then the entire server collapsed.

Refer to the article

Vue project optimization

The VUE framework handles a lot of the most troublesome PARTS of DOM manipulation through two-way data binding and virtual DOM technology, without considering how to manipulate dom and how to efficiently manipulate DOM.

  • Optimization at the code level
    1. V-if and V-show are used in different scenarios
      1. V-if is true conditional rendering and ensures that events and nodes of the conditional block are properly destroyed and rebuilt during the condition switch. But it is also lazy, and when the initial render condition is false, nothing is done. Suitable for conditions that do not require frequent switching
      2. V-show elements are rendered in any case, just a simple CSS-BASED display switch, suitable for frequently switched conditional scenarios.
    2. Computed and Watch distinguish usage scenarios
    3. V-for traversal plus key, and avoid use with V-if
    4. Long list performance optimization
      1. Vue 2.0 hijacks data through Object.defineProperty to make the view respond to data changes, but some components are purely data presentation, so vUE does not need to hijack our data, and in the case of large data presentation, component initialization time can be significantly reduced. To disallow vUE to hijack data methods, use Object.freeze to freeze objects
    5. Lazy loading of image resources

      For pages with too many pictures, in order to accelerate the speed of the page, many times you can not load the pictures that do not appear in the visual area of the page, and then load them after scrolling to the visual area, and the page loading performance will be greatly improved.

      1. Loading a static loading image
      2. Determine which images need to be loaded according to the height of the scroll bar
      3. Generate an IMG object to load images stealthily
      4. To replace a fake image with a real one, place the address of the real image to be loaded in data-src
    6. Route lazy loading
  • Optimization at the WebPack level
  • Basic Web technology optimization

Refer to the article

Vuex principle is realized

Vuex is a state management mode specially developed for vuue. js applications. It adopts centralized storage to manage the state of all components and ensures the state according to corresponding rules. The application scenarios are as follows: The simplicity of vUE’s single data flow can easily be compromised when our application encounters multiple component sharing states and can be used to share data across multiple components or transfer data across components. It mainly includes the following parts: State, getters, mutations, Actions and Module

  • State: A single state of storage. It is the basic data to be stored
  • Getters: is the calculated property of state. The data derived from the state is processed twice, and the value returned by the getter is cached according to its dependencies, and will be recalculated only when its dependencies change
  • Mutations: Submit changes to the data, usestore.commitMethod to change the state of the storage (synchronous update)
  • Actions: Like a decorator, submitmutationMethod, rather than changing state directly, can be used to perform asynchronous operations
  • A moudule is a store-separated module. Each module has getters, state, actions, etc

When vuEX’s data flow VUE component invokes a vuex method, it needs to dispatch the actions method of VUex, and submit the methods in mutations to achieve the operation of state members. The last modified state member is rendered to the original location of the component.

How to use mixins in Vue

Vue introduces mixins, a hybrid mechanism provided by vUE, to achieve more efficient reuse of component content.

  • After the reference, the component merges the contents of the component, such as data and method, with the corresponding contents of the parent component. In effect, the parent component’s various property methods have been extended since its introduction
  • The parent component and the child component have various property methods in the child component, but it does not mean that they share and handle these variables at the same time, and do not affect each other.

Refer to the blog

Vue-router core implementation principle

Router-link and router-view are two components defined globally in vue-Router. They are used to redirect routes and display components corresponding to routes respectively. When router-link is clicked, vue-Router monitors route changes, finds matching components according to routing rules, and renders them in router-View.

  • Single page: The first time we enter the page, we request an HTML file. When we switch to another component, the path changes and the page content changes, but no new HTML file is requested.

The principle is as follows: JS monitors url changes through API, uses JS to clear the current page content, and then mount the next page content to the current page. At this time, routing is not done by the front end, but the front end controls to determine which component is displayed on the page. This process is single-page application.

  • Multi-page: Each time the page jumps, the background server will return a new HTML document, this type of site is multi-page site, also known as multi-page application.

The principle is as follows: In traditional single-page applications, hyperlinks are used to switch between pages.

Implementation principle of vue-Router

The principle is to update the view without rerequesting the page. Vue-router supports the hash and history modes for page redirection

Routing patterns

  • Hash: Uses the URL hash value as the route. The default mode is hash. Hash is in the browser URL#The content after +, the anchor point in the URL, represents a location in the page. If you change the content after #, the browser will only load the content at that location, not reload the page, and we can also read it with the window.location.hash property.
    1. #It appears in the URL, but is not included in the HTTP request, is used to guide browser actions, and is completely useless to the server, so changing the hash does not reload the page.
    2. Add listening events for hash changes and then update the routing view; Each time the hash content is changed, a record is added to the browser’s access history.

Therefore, the hash mode is to render different data of the specified DOM according to different values by changing the anchor point value

  • History: Relies on the HTML5 History API and server configuration. The history.pushState API lets developers change the site URL without refreshing the page

In history mode, if the requested address does not have the corresponding route processing at the back end, a 404 error will be returned. In this case, you need to add a candidate resource that covers all cases. If the URL does not match the resource, a unified 404 page will be returned

Reference article Reference article 2

Lazy loading of vue-Router

Lazy loading is mainly to divide the page, the time needed to load the page, effectively bear the load pressure of the home page, reduce the time used to load the home page.

Lazy loading method, principle

  • userequireMode Import route (related to require import mode)
  • Provided using Webpackrequire.ensure()Count, implement load on demand, specify the same chunkName for multiple routes, which will then be packaged into a JS file.

Vue nested routines by

Nested routing means that a route can continue to be used under a routed page. Nested means routing within routing. You can use the left and right sub-menus to jump to achieve local page content changes. Set this parameter in the children property of route configuration

Vue-router’s global navigation hook

  • Global guard:

Use routet.beforeEach to register a global front-guard that is called in the order in which it was created when a navigation is triggered.

 router.beforeEach((to, form , next )=>{
 })
Copy the code

Three parameters are received:

  1. to:RouteRepresents the target to enter
  2. from:RouteIndicates the route that is leaving
  3. next:FunctionThe effect of guard execution isDepend on the parameters of the next method
    1. next()The next hook into the pipe
    2. next(false)Interrupts the current navigation and resets to the address corresponding to the FROM route
    3. next({path:'/'})Switch to an arbitrary location address
  • Route exclusive guard

Define beforeEnter guards between configured routing objects

const router = new VueRouter({
    routes:[{
      path:'/foo',
      component:foo,
      beforeEnter:(to, from, next) =>{
      }
    }]
})
Copy the code
  • Guards within components

Refer to the article