This is the first day of my participation in the August Challenge. For details, see:August is more challenging

This collection is a frequent interview test site, and optimized and simplified answers for easy description in the interview.


  • HTTP && browser
  • HTML && CSS
  • JS, TS, and ES6
  • Vue
  • React
  • Build tools && engineering
  • Performance optimization

HTTP && network

1. The HTTP and HTTPS

1. Basic concepts of HTTP and HTTPS

HTTP: A standard client – and server-side request – and – reply (TCP) hypertext transfer protocol used to transfer hypertext from WWW servers to local browsers. HTTPS: Indicates an HTTP channel for security purposes. That is, the SSL layer is added to HTTP for encryption.

The role of HTTPS protocol: to establish a secure information channel, to ensure the transmission of data, to ensure the authenticity of the website.

2. What’s the difference between HTTP and HTTPS?

  • HTTP is the hypertext transfer protocol, and information is transmitted in plain text. HTTPS is the SECURE SSL encryption transfer protocol.
  • Https requires a CA certificate, which is costly.
  • Generally, the HTTP port is 80, and the HTTPS port is 443.
  • HTTP connections are simply stateless.

3. Working principle of THE HTTPS protocol

When the client communicates with the Web server in HTTPS mode, perform the following steps:

  1. If the client uses an HTTPS URL to access the server, the web server is requiredEstablishing SSL Links.
  2. After the Web server receives the request from the client, it willTransfer the website certificate (including the public key) to the client.
  3. Start with the client and web serverNegotiate the security level of the SSL link, which is the encryption level.
  4. The client browser passes the security level agreed by both parties.Establishing a session KeyThe session key is then encrypted through the site’s public key and transmitted to the site.
  5. The web serverDecrypt the session key using your private key.
  6. The web serverEncrypts the communication with the client through the session key.

4. Advantages and disadvantages of HTTPS

  • HTTPS is more secure than HTTP and prevents data from being stolen or changed during transmission, ensuring data integrity.
  • Comparison of HTTPS handshake phasesTime consumingIncreases page load time by 50% and power consumption by 10% to 20%.
  • https The cacheIt is not as efficient as HTTP, which increases data overhead.
  • SSL certificates also cost money, the more powerful they areCertificate feeWith the higher.
  • The SSL certificate must be boundIP, you cannot bind multiple domain names to the same IP address. Ipv4 resources cannot support such consumption.

TCP/IP network model

The TCP/IP model is the foundation of the Internet. It is a general term for a series of network protocols. These protocols can be divided into four layers: link layer, network layer, transport layer, and application layer.

  • Link layer: Encapsulates and unencapsulates IP packets, and sends and receives ARP/RARP packets.
  • Network layer: routes and sends packets to the target network or host.
  • Transport layer: Groups and reassembles packets and encapsulates them in TCP or UDP format.
  • Application layer: Responsible for providing applications to users, such as HTTP, FTP, Telnet, DNS, SMTP, etc.

TCP Three-way handshake

  1. The first handshake:When the connection is established, the client sends a SYN packet (SYN =j) to the server and enters the SYN_SENT state, waiting for the server to confirm; SYN: synchronization Sequence Numbers.
  2. Second handshake:The server receives the SYN packet and acknowledges the client's SYN(ack = j + 1),It also sends a SYN packet of its own(syn=k), that is, THE SYN+ACK packet, then the server enters the SYN_RECV state.
  3. The third handshake:After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK =k+1) to the server.After the packet is sent, the client and server enter the ESTABLISHED state (TCP connection succeeds) and complete the three-way handshake.
The packet sent during the handshake does not contain data. Data is transferred between the client and the server only after the three-way handshake.Copy the code

TCP waves four times

  1. The client process sends a connection release packetAnd stop sending data. The header of the data packet is released, FIN=1, and its serial number is SEq = U (equal to the serial number of the last byte of the data that has been transmitted plus 1). At this time, the client enters the FIN-wait-1 state. According to TCP, a FIN packet segment consumes a serial number even if it does not carry data.

2) After receiving the connection release packet, the server sends a acknowledgement packet with ACK=1, ACK= U +1 and its serial number seq= V. Then the server enters the close-wait state. The TCP server notifies the high-level application process, and the client is released to the server. At this time, the client is in the semi-closed state, that is, the client has no data to send. However, if the server sends data, the client still accepts it. This state will continue for a period of time, that is, the entire duration of the closewait state.

3) After the client receives the acknowledgement request from the server, the client enters the FIN-wait-2 state, waiting for the server to send the connection release packet (before receiving the last data sent by the server).

4) After the server sends the LAST data, it sends the connection release packet to the client, FIN=1, ACK = U +1. Since the server is in the semi-closed state, it is likely to send some more data, assuming that the serial number at this time is SEq = W. At this time, the server enters the last-ACK state, waiting for the confirmation from the client.

5) After receiving the connection release packet from the server, the client must send acknowledgement, ACK=1, ACK= w+1, and its serial number is SEq = U +1. At this TIME, the client enters the time-wait state. Notice That the TCP connection is not released, and the client enters the CLOSED state only after 2∗∗MSL (maximum packet segment lifetime) expires and the corresponding TCB is revoked.

6) As long as the server receives the confirmation from the client, it will enter the CLOSED state immediately. Again, canceling the TCB terminates the TCP connection. As you can see, the server ends the TCP connection a little earlier than the client.

Differences between TCP and UDP

  1. TCP is link-oriented, while UDP is connectionless.

  2. TCP supports only unicast transmission, while UDP provides unicast, multicast, and broadcast functions.

  3. TCP’s three-way handshake ensures the reliability of the connection. UDP is a connectionless and unreliable data transmission protocol. First of all, its unreliability is reflected in connectionless. It does not need to establish a connection for communication, nor does it send confirmation signals for received data, and the sender does not know whether the data will be correctly received.

  4. UDP has lower header overhead than TCP, higher data transmission rate, and better real-time performance.

HTTP request cross-domain problem

  1. Cross-domain principle

    Cross-domain means that the browser cannot execute scripts from other websites. It is caused by the browser’s same-origin policy. The same origin policy is a security restriction imposed by the browser on JavaScript. Any difference in protocol, domain name, or port is treated as a different domain. The cross-domain principle is to circumvent browser security restrictions in various ways.

  2. The solution

    When I first did the project, I used JSONP, but there were some problems. It was unsafe to use GET request, and the data carried was small. Later, I also used iframe, but only the same primary domain could be used. On the boot background in this way to do under the server configuration, the use of proxy in the development, the use of nGINX proxy in the server, so that the development process of each other are convenient, high efficiency; Also new in H5 is Windows.PostMessage ()

    • Json: Ajax requests are not allowed to make cross-domain requests because of the same origin policy. However, the link in the SRC attribute of the script tag can access cross-domain JS scripts. Using this feature, the server returns a js code calling a function instead of JSON data. It is called in SRC, which makes it cross-domain.

      Steps:

      1. To create a script tag
      2. The SRC attribute of script sets the interface address
      3. Interface parameter, must have a custom function name, otherwise the background will not return data
      4. Accept the returned data by defining the function name
      // Create script dynamically
      var script = document.createElement('script');
      
      // Set the callback function
      function getData(data) {
          console.log(data);
      }
      
      // Set the SRC property of script and set the request address
      script.src = 'http://localhost:3000/? callback=getData';
      
      // Make the script work
      document.body.appendChild(script);
      Copy the code

      Disadvantages of JSONP: JSON only supports GET because script tags can only use GET requests; JSONP requires back-end coordination to return data in a specified format.

    • Document. domain The same basic domain name has different subdomains

    • In a browser window, all loaded domain names share a single window.name

    • CORS Cross-Origin Resource Sharing (CORS) Server Setting The CORS support principle: After the access-control-allow-Origin HTTP response header is set on the server, the browser will Allow cross-domain requests

    • Proxy Indicates the common proxy mode

    • Window.postmessage () Takes advantage of new h5 features window.postMessage()

    • Websocket

Cookie, sessionStorage, and localStorage

Similarities:

  • Stored on the client

Difference:

  • The cookie data size cannot exceed 4K. The storage of sessionStorage and localStorage is much larger than the cookie, up to 5M+
  • The cookie is valid until the expiration time. LocalStorage Permanent storage. Data is not lost after the browser is closed unless the data is actively deleted. SessionStorage Data is automatically deleted after the current browser window closes
  • Cookie data will be automatically transmitted to the server; SessionStorage and localStorage data is stored locally

The browser’s caching mechanism forces caching && negotiates caching

HTML files are also cached. Using index.php in the project, the back end returns HTML content and will not be cached.

Browser cache policy:

Mandatory cache :(the browser uses strongly cached content directly for a specified period of time)

Expires: Thu.21 Jan 2019 23:59:59 GMT; (HTTP1.0)

Cache-control: max-age=3600 (HTTP1.1, higher priority)

[Cache directive: no-cache needs to negotiate cache to verify expiration; no-store does not cache; public client proxy server can cache; private client can cache.]

Negotiated cache :(negotiates with the server to determine whether the resource is updated)

Last-modified: Thu.21 Jan 2018 23:59:59 GMT; (HTTP1.0)

If- modified-since

Etag (sent from the server); (HTTP1.1)

If-none-match (browser asks)

HTML && CSS

HTML5 new features, semantics

  1. Concept:

    Semantic HTML5 refers to the proper use of semantic tags to create the structure of the page. The right label to do the right thing

  2. Semantic tags:

    header nav main article section aside footer

  3. Advantages of semantics:

    • inWithout CSS, the overall structure of the page will look good
    • Clear code structure, easy to read,
    • Development and maintenance benefitsIt is convenient for other devices (such as screen readers) to render web pages according to semantics.
    • Good for search Engine optimization (SEO), the search engine crawler will give different weights according to different tags

Common compatibility problems

  1. The default margin and padding are different for different browsers. *{margin:0; padding:0; }

  2. IE6 two-sided margin bug: When block property tag float is followed by margin, IE6 shows margin is larger than set. Hack: display: inline; Convert it to an inline property.

  3. Set a small height label (usually less than 10px), and in IE6, IE7, the height is higher than the self-set height. Hack: Set overflow:hidden for tabs that exceed the height; Or set the line height to be less than the height you set.

  4. By default, text smaller than 12px is forced to display as 12px. You can add the CSS property -webkit-text-size adjust: None; To solve.

  5. Hover style does not appear after hyperlink access, was clicked to visit the hyperlink style no longer has the hover and active. L-v-h-a (love hate): A :link {} A :visited {} A :hover {} A :active {}

CSS Box Model

The CSS box model is essentially a box that includes: margins, borders, padding, and actual content. The box model in CSS includes IE box model and standard W3C box model. In the standard box model, width refers to the width of the content section. In the IE box model, width represents the width of content+padding+border.

Therefore, there is a difference when calculating the width of the box:

Total width of a block = width+margin(left)+padding(left)+border(left)

Weird box model: total width of a block = width+margin (left and right) (since width already includes padding and border values)

BFC (Block-level format context)

The concept of landing

BFC stands for Block Formatting Context. BFC is a CSS layout concept. It is a separate rendering area that determines how the inner box is laid out. The child elements of this area do not affect the outer elements.

Principles of the BFC layout rules

  • The internal Box will be inThe vertical direction, one by one
  • BoxThe vertical distance is determined by margin. Margins of two adjacent boxes belonging to the same BFC will overlap
  • The left side of each element’s margin box touches the left side of the containing block’s border box (for left-to-right formatting, otherwise the opposite)
  • The landing areaIt doesn't overlap with float box
  • BFC is a separate container, inside the containerThe child element does not affect the outer element
  • When calculating the height of the BFC,The float element is also involved in calculating the height
  • Element type andThe display property determines the type of Box. Different types of Box will participate in differentFormatting Context.

How do I create a BFC?

  • The root element, the HTML element
  • The value of float is not None
  • Position is absolute or fixed
  • The display value is inline-block, table-cell, and table-caption
  • The overflow value is not visible

Use scenarios of the BFC

  • Remove margin overlap
  • Clear float (let parent height contain child float element)
  • Avoid an element being overwritten by a floating element
  • Avoid wrapping multi-column layouts as width calculations are rounded

How many ways can you center an element horizontally or vertically?

  • Horizontal center

    • For inline elements: text-align: center;

    • For block-level elements whose width is determined:

      (1) Width and margin implementation. margin: 0 auto;

      Margin-left: -width/2; margin-left: -width/2

    • For block-level elements of unknown width

      (1) The table tag is horizontally centered with margin, left and right auto. Use the table TAB (or directly set the block-level element to display:table) and add left and right margin to auto for the TAB.

      (2) Inline-block implements the horizontal center method. Display: inline-block and text-align:center Implements horizontal center.

      (3) Absolute positioning + Transform, translateX can move 50% of its elements.

      (4) Flex layout uses text -content: Center

  • Vertical center

    1. usingline-heightImplement the center, which is suitable for plain literal classes
    2. By setting the relative positioning of the parent container, the children are setAbsolute positioning, the tag realizes adaptive centering through margin
    3. Flexible layout Flex: parent Settings display: flex; Sub-level set margin to auto to achieve adaptive center
    4. The parent sets the relative positioning, and the child sets the absolute positioning, and the displacement transform is implemented
    5. The table layout, the parent is converted to table form,The child then sets the vertical-align implementation. (Note: vertical-align: middle is used only if the elements are inline and the display value is table-cell).

A method to hide an element in a page

1. The opacity: 0: the element is hidden, but does not change the page layout. Moreover, if the element has been bound to some event, such as click event, clicking on the element will also trigger the click event

2. Visibility: hidden, the element is hidden, but will not change the page layout, but will not trigger the event that the element has been bound, hide the corresponding element, and retain the original space in the document layout (redraw).

Display: none, which hides the element and changes the layout of the page, can be interpreted as putting the element in the page. Do not display the corresponding element, no more space allocated in the document layout (reflux + redraw)

What does the project do for mobile terminal adaptation? Flexible Principle (1px issue via viewport)

flex + px

rem + vw

JS, TS, and ES6

JS 8 data types and differences

Including value types (basic object types) and reference types (complex object types)

The basic types (value types) : Number,String,Boolean,Symbol, NULL,undefined occupy a fixed size in memory and are stored in stack memory

Reference types (complex data types) : Object, Function. Other reference types such as Array, Date, RegExp, special basic wrapper types (String, Number, Boolean), and single built-in objects (Global, Math) are stored in heap memory. The stack memory stores the variable identifiers of the object and the location of the object in the heap memory.

JS data type detection scheme

1.typeof

console.log(typeof 1);               // number
console.log(typeof true);            // boolean
console.log(typeof 'mc');            // string
console.log(typeof function(){});    // function
console.log(typeof console.log());   // function
console.log(typeof []);              // object 
console.log(typeof {});              // object
console.log(typeof null);            // object
console.log(typeof undefined);       // undefined
Copy the code

Advantages: Ability to quickly distinguish between basic data types

Disadvantages: Cannot distinguish Object, Array, and Null, all return Object

2.instanceof

console.log(1 instanceof Number);                    // false
console.log(true instanceof Boolean);                // false 
console.log('str' instanceof String);                // false  
console.log([] instanceof Array);                    // true
console.log(function(){} instanceof Function);       // true
console.log({} instanceof Object);                   // true
Copy the code

Advantages: Can distinguish between Array, Object, and Function, suitable for determining custom class instance objects

Disadvantages: Number, Boolean, String basic data types cannot be determined

3.Object.prototype.toString.call()

var toString = Object.prototype.toString;
console.log(toString.call(1));                      //[object Number]
console.log(toString.call(true));                   //[object Boolean]
console.log(toString.call('mc'));                   //[object String]
console.log(toString.call([]));                     //[object Array]
console.log(toString.call({}));                     //[object Object]
console.log(toString.call(function(){}));           //[object Function]
console.log(toString.call(undefined));              //[object Undefined]
console.log(toString.call(null));                   //[object Null]
Copy the code

Advantages: Accurately determine data types

Disadvantages: cumbersome writing method is not easy to remember, recommended to use after packaging

var && let && const

ES6 used var to create variables and then let/const to create variables

Three differences:

  1. Var defines a variable that has no concept of blocks and can be accessed across blocks, but not across functions. Let defines variables that can only be accessed within the scope of a block, not across blocks or functions. Const is used to define a constant, must be initialized (that is, must be assigned), can only be accessed in the block scope, and cannot be modified.

  2. Var can be used first and declared later because of variable promotion. Let must be declared before use.

  3. Var allows multiple declarations of the same variable in the same scope. Let and const do not.

  4. In the global context, global variables based on let declarations have nothing to do with the global object GO (window); Var declares variables that map to GO;

  5. Resolve temporary dead zones:

The temporary dead zone is a bug in the browser: when detecting an undeclared variable type, it will return undefined without an error. For example: console.log(typeof a) //undefined: Console. log(typeof a)// Do not use let a before declaring it

  1. Let /const/function will take the current brace (except function) as a new block-level context, and apply this mechanism. When developing projects, if you encounter the need for loop event binding and other similar requirements, you don’t need to build closures to store them. Instead, you can solve them based on the block function characteristics of let

Variable ascension

When the browser opens up the stack memory for code execution, the code does not immediately execute from the top down. Instead, it continues to do something: declare and define in advance all the variables in the current scope with the keyword var and function.

  • Var is declared in advance, not assigned, and the default value is undefined.
  • Declaration with function plus assignment.
  • Without the vara=3Indicates a global settingwindow.a=3And in the global scopevar a=3It’s the same;

In the variable promotion stage, the variable promotion should be carried out regardless of whether the condition is true or not, when there are braces and judgment bodies, etc., while in the browser of the higher version, the function is only declared and no value is assigned.

JS garbage collection mechanism

  1. In a project, if there is a large amount of memory (heap/stack/context) that is not being freed, the page performance will be slow. Memory leaks occur when certain code operations are not released properly. We use closures as little as possible because they consume memory.

  2. Browser garbage collection/memory collection mechanism:

    The browser’s Javascript has an automatic Garbage Collecation (Garbage Collecation) mechanism, which periodically finds variables that are no longer in use and frees their memory.

    Tag cleanup: In JS, the most common garbage collection mechanism is tag cleanup: variables are marked as “in” when they enter the execution environment, and “out” when they leave the execution environment. The garbage collector destroys the marked values and reclaims the memory they occupy. Google Chrome: “Find a reference”, the browser will occasionally look for the current memory reference, if not occupied, the browser will reclaim it; If it is occupied, it cannot be recycled. IE browser: “reference counting method”, the current memory is occupied once, the count is accumulated 1 times, remove the occupied is reduced by 1, when reduced to 0, the browser will reclaim it.

  3. Optimization means: memory optimization; Manual release: Remove the memory usage.

    (1) heap memory: fn = null

    (2) Stack memory: the context, the external occupied heap occupancy can be cancelled.

  4. A memory leak

    In JS, there are four common memory leaks: global variables, closures, DOM element references, timers

Scope and scope chains

When a function is created, the scope of the current function is declared ==> The context in which the function is currently created. [[scope]]:EC(G); if the function is created globally, it is [[scope]]:EC(G). When the function is executed, it forms a new private context, EC(FN), for string code to execute.

Definition: Simply put, scope is the accessible scope of variables and functions, consisting of a series of variable objects in the current environment and the upper environment 1. Global scope: Code can be accessed anywhere in the program. The built-in properties of the Window object have global scope. 2. Function scope: It can only be accessed in fixed code snippets

Function: The most useful thing about scopes is to isolate variables. Variables with the same name in different scopes do not conflict.

Scope chain Reference link In general, the value of a variable to the scope of the function that created it. However, if it is not found in the current scope, it will be searched to the upper scope until it reaches the global scope. The chain formed by the search process is called the scope chain.

Closures have two main functions: save/protect

  • The concept of closures

    The private context EC(FN) formed when the function is executed, which is normally released after the code is executed off the stack; However, in special cases, if something in the current private context is occupied by something outside the context, the context will not be released off the stack, thus forming an undestroyed context. During the execution of a function, a new private context is formed, which may or may not be released. Whether it is released or not, it serves the following purposes:

(1) Protection: divide an independent code execution area, in which there is a storage space for its own private variables to protect its own private variables from external interference (operating its own private variables has no relationship with the outside world);

(2) Save: If the current context is not released [as long as something in the context is external occupation can be], the stored private variables will not be released, can be called for its child context use, equivalent to some values saved;

The mechanism to protect and store private variables in the private context of function execution is called closure.

Closures are functions that have access to variables in the scope of another function — JavaScript Advanced Programming

A more comprehensive answer: In JS, the scope of the variable belongs to the function scope. After the function is executed, the scope will be cleaned up and the memory will be recycled. However, as the closure function is a subfunction built inside the function, because it can access the superior scope, even if the superior function is executed, the scope will not be destroyed. The subfunction (i.e., the closure) now has access to variables in the parent scope, even if the value in the scope is not destroyed after the parent function executes.

  • Closure features:

    • Internal functions can access the parameters and variables that define their external functions. (Look up the scope chain and store the values of variables in the outer scope in memory instead of destroying them after a function call.) Design private methods and variables to avoid global variable contamination.

      1.1. Closures are closed containers, similar to sets and maps, that store data

      1.2. A closure is an object that stores data in key-value format

    • 2. Function nesting

    • 3, the essence is to connect the function inside and outside. The advantage is that you can read variables inside a function, keeping their values in memory and not automatically clearing them after the function is called

  • Conditions for closure formation:

    1. Nesting of functions
    2. An internal function refers to a local variable of an external function, prolonging the variable lifetime of the external function
  • Closures are used for:

    1. Mimic block-level scope
    2. Lexical scope in which variables that protect an external function can access the function definition (preventing it from being reclaimed)
    3. Encapsulate private variables
    4. Create a module
  • Closure application scenarios

    Two scenarios for closures, two functions of closures: save/protect. In development, we see closures everywhere. Most of the front-end JavaScript code is “event-driven” — an event-bound callback method; To send an ajax request success | failure callback; Delay callback to setTimeout; Or if a function internally returns another anonymous function, these are all applications of closures.

  • Advantages of closures: prolong the life cycle of local variables

  • Closure disadvantages: The function’s variables will always be stored in memory, and too many closures may cause memory leaks

Five cases of this in JS

  1. When executed as a normal function,thisPoint to thewindow.
  2. When a function is called as a method on an object,thisCan point toThe object.
  3. Constructor call,thisPoint to theThis object is returned.
  4. Arrow function of the arrow functionthisBinding looks atThe object under which this function is definedWhich object is bound to. In the case of nesting, this is bound to the nearest layer of objects.
  5. Based on function.prototypeApply, call, and bindCall mode, all three methods can display the point to this of the specified calling function.applyThe array that receives the argument,callAccept the argument list, ‘ ‘bindMethod returns an object by passing in an object this The new function is bound to the passed object. Of this functionthisPointing in addition to using“New” will be changed, but nothing else. If empty, the default is to point to the global object window.

Prototype && Prototype chain

Prototype relationship:

  • Each class has its prototype displayed
  • Each instance has an implicit stereotype _ proto_
  • The _ proto_ of the instance refers to the prototype of the corresponding class

Stereotype: In JS, every time an object is defined (functions are also objects), the object contains some predefined properties. Each of these function objects has a Prototype property that points to the function’s prototype object.

Prototype chain: a function’s prototype chain object constructor defaults to the function itself. In addition to having prototype properties, the prototype object implements inheritance by having a prototype chain pointer __proto__ that points to the previous level’s prototype object whose structure remains similar. So we can use __proto__ to point all the way to the Object prototype, which is denoted by object.prototype. __proto__ = null at the top of the prototype chain. Thus forms the js prototype chain inheritance. At the same time, all JS objects have the basic defense of Object

Features: JavaScript objects are passed by reference, and we don’t have a copy of the prototype for each new object entity we create. When we modify the prototype, the objects associated with it inherit the change.

Implementation mechanism of the new operator

  1. First, I create a new oneAn empty object
  2. Set the prototypeTo set the prototype of the object to that of the functionprototypeObject.
  3. Let the function of thethisPoints to the object and executes the constructor code (adding properties to the new object)
  4. Determines the return value type of the function and, if it is a value type, returns the created object. If it is a reference type, an object of that reference type is returned.

JS deep and shallow copy

EventLoop indicates the EventLoop

JS is single-threaded, in order to prevent a function the code behind the blocked the execution time is too long, so will try to press the synchronization code into execution stack, in turn, push the asynchronous code into the asynchronous queue, asynchronous queue is divided into macro task queue and task queue, because the macro task queue execution time is longer, so the task queue to priority has been the task queue. The representative of a microtask queue is promise. then, MutationObserver, and in the case of a macro task, setImmediate Mediate setTimeout setInterval

JS runtime environment. It is usually a browser or Node. In the browser environment, there is the JS engine thread and the render thread, and the two threads are mutually exclusive. In the Node environment, there are only JS threads. Different environments have different execution mechanisms, and different tasks enter different Event queues. When the main process is finished, the prepared microtask is executed, and then the prepared macro task is executed. A poll is completed.

Event Loop in the browser

The operation mechanism of event loop is that the contents of the stack will be executed first, and then the micro task will be executed after the contents of the stack are executed, and then the macro task will be executed after the micro task is cleared, and then a macro task will be fetched, and then the micro task will be executed, and then the macro task will be fetched and the micro task will be removed.

  • EventLoop is implemented by the JS host environment (browser);

  • The event loop can be simply described as the following four steps:

    1. When an asynchronous task is executed in the Stack, it is thrown to the WebAPIs, and then the synchronous task is executed until the Stack is empty.
    2. During this time, WebAPIs completes the event and puts the callback function on the queue for execution (microtasks on the microtask queue and macro tasks on the macro task queue).
    3. When the execution stack is empty, the Event Loop clears the execution of the microtask queue.
    4. After the microtask queue is cleared, the macro task queue is entered and the first task in the queue is put into the Stack for execution. After the execution is complete, the microtask queue is checked to see whether there are any tasks in the microtask queue. If there are any tasks, the microtask queue is cleared. Repeat 4 to continue to fetch tasks from macro tasks for execution. After execution, continue to empty microtasks, and so on, until all tasks are empty.

  • Task source in browser:

    • Macrotask: The host environment provides, for example, browser Ajax, setTimeout, setInterval, setTmmediate(ie compatible only), script, requestAnimationFrame, messageChannel, UI rendering, and some browser apis

    • Microtask: Languages themselves, such as promise.then THEN, queueMicrotask(based on then), mutationObserver(provided by the browser), messageChannel, and mutationObersve

Event Loop in the Node environment

Node is a JavaScript running environment on the server based on the V8 engine. It has obvious advantages in processing high concurrency and I/ O-intensive (file operation, network operation, database operation, etc.) scenarios. Although it also uses V8 engine, its API is different from that of native JS due to the different service purpose and environment. Its Event Loop also has to deal with some I/O, such as new network connection, so the Event Loop mechanism of Node is different from that of browser.

The execution sequence is as follows:

  • timers: a timer that performs callbacks to setTimeout and setInterval
  • pending callbacks: Executes I/O callbacks that are delayed until the next iteration of the loop
  • idle, prepare: Indicates the movement of a queue, which is used only within the system
  • Poll polling: Retrieve new I/O events; Perform I/ O-related callbacks. In fact, almost all asynchrony is handled in this phase, except for things that are handled in several other phases.
  • check: performsetImmediateThe callback, setImmediate, is performed here
  • close callbacks: performcloseThe eventcallbackOn (‘close’,…)

SetTimeout, Promise, Async/Await

  1. setTimeout

    The setTimeout callback is placed in the macro task queue and executed when the execution stack is cleared.

  2. Promise

    The Promise itself is a synchronous, immediate execution function. When a resolve or reject is executed in an executor, it is an asynchronous operation that executes then/catch first. When the main stack is complete, it calls the resolve/reject method.

    console.log('script start')
    let promise1 = new Promise(function (resolve) {
        console.log('promise1')
        resolve()
        console.log('promise1 end')
    }).then(function () {
        console.log('promise2')})setTimeout(function(){
        console.log('settimeout')})console.log('script end')
    // Output sequence: script start->promise1->promise1 end->script end->promise2-> setTimeout
    Copy the code
  3. async/await

    The async function returns an await object. When the function executes, it returns an await object and waits until the async operation is complete before executing the following statement in the function body. Async: async: async: async: async: async

    async function async1(){
       console.log('async1 start');
        await async2();
        console.log('async1 end')}async function async2(){
        console.log('async2')}console.log('script start');
    async1();
    console.log('script end')
    
    // Output sequence: script start->async1 start->async2->script end->async1 end
    Copy the code

How to implement Async/Await in a synchronous manner

Async/Await is a self-executing generate function. Use the generate feature to write asynchronous code as “synchronous,” with the return value of the first request as a parameter to each subsequent request, each of which is a Promise object.

Promise

The use of sets and maps in ES6 and their corresponding data structures

Set data structure

Concept: SET is a new data structure in ES6. The concept of a set is a set of unordered and unique (that is, not repeated) items. The set data structure uses the same mathematical concepts as finite sets and is applied to computer data structures, similar to arrays, except that the members are unique and there are no duplicate values.

Features: The key is the same as the value. There is no duplicate value. Just the key, no key name, sort of like an array.

Property: set.size Set size

Set the usual method

1, set.add(value) adds a data, returns the set structure itself 2, set.delete(value) deletes the specified data, indicating whether the deletion is successful 3, set.has(value) determines whether the value is a set member, Return a Boolean value. 4, set.clear() clears all data, There is no return value 5, set.keys() iterator that returns key names 6, set.values() iterator that returns key values 7, entries() iterator that returns key-value pairs 8, forEach() iterator that uses each member of the callback function

2. WeakSet

WeakSet objects allow you to store weak reference objects in a collection

The difference between WeakSet and Set:

  • WeakSet can only store object references, but not values, while Set objects can
  • The object value stored in a WeakSet object is weakly referenced, that is, the garbage collection mechanism does not consider the application of a WeakSet to the object. If there is no other variable or attribute reference to the object value, the object will be garbage collected (regardless of the existence of the object in a WeakSet), so, The number of member elements in WeakSet object depends on whether the garbage collection mechanism is running, the number of members before and after the operation may be inconsistent, after the end of the traversal, some members may not be retrieved (by garbage collection), WeakSet object is unable to be traversed (ES6 specifies that WeakSet cannot be traversed), There’s no way to get all the elements that it contains

Properties:

  • Any object that has an Iterable interface can be taken as an argument

3.Map data structure

A Map is a data structure called a dictionary. The biggest difference between a Map and an object is that the key can be any type

An instance of the Map structure has the following properties:

1. Size attribute The size attribute returns the total number of members of the Map structure. Set (key, value) 3. Get (key) The get method reads the corresponding key value. If the key cannot be found, the function returns undefined. The has(key) method returns a Boolean value indicating whether a key is in the Map data structure. 5. Delete (key) The delete method deletes a key, returning true. If deletion fails, return false. 6. Clear () The clear method clears all members without returning a value.

Map natively provides three iterator generators and one iterator method.

  • keys(): The iterator that returns the key name.
  • values(): the iterator that returns the key value.
  • entries(): Returns a traverser for all members.
  • forEach(): Traverses all members of the Map.

It is important to note that the Map traversal order is the insertion order.

4. WeakMap

A WeakMap object is a set of key-value pairs, where the key is a weak reference object and the value can be arbitrary.

Note that WeakMap weakly references only the key name, not the key value. The key is still a normal reference.

In a WeakMap, the reference of each key to its referenced object is a weak reference. If there is no other reference and the key references the same object, the object will be garbage collected (the corresponding key will become invalid), so the key of a WeakMap cannot be enumerated.

Properties:

  • Constructor: constructor

Methods:

  • Has (key) : Determines whether there is a key associated object
  • Get (key) : return the key associated object (undefined if there is none)
  • Set (key) : Sets a group of key associated objects
  • Delete (key) : Removes the associated object of key

weakSet

  1. Members are objects
  2. Members are weak references and can disappear at any time. Can be used to store DOM nodes and is less prone to memory leaks
  3. We can’t iterate. We have add, DELETE,has Map
  4. It’s essentially a set of key pairs, like a set
  5. Can iterate, many methods, can do with a variety of data format conversion weakMap 1. Accepts an object directly as the key name (except null), and does not accept a value of any other type as the key name
  6. The object to which the key refers is not included in garbage collection
  7. We can’t iterate. We can do the same thing as get,set,has,delete

Briefly describes the MVVM

What is MVVM?

ViewModel bidirectional binding, short for Model-view-ViewModel, is the evolution of the Controller in MVC into ViewModel. The Model layer represents the data Model and the View represents the UI component. The ViewModel is the bridge between the View and the Model layer. The data is bound to the ViewModel layer and automatically renders the data to the page. Instead of manipulating THE DOM structure to update the view, it’s now a data-driven view.

Advantages of MVVM:

1. Low coupling. Views can be changed and modified independently of the Model. A Model can be bound to different views. The Model can remain unchanged when the View changes, and the View can remain unchanged when the Model changes. 2. Reusability. You can put some View logic in a Model and have many views reuse that View logic. 3. Independent development. Developers can focus on business logic and data development (ViewModel), and designers can focus on page design. 4. Testable.

Talk about Vue MVVM implementation principle

  1. Vue as MVVM pattern implementation library of two technologies

    A. Template parsing b. Data binding

  2. Template parsing: to achieve initial display

    A. Parse braces. B. Parse instructions

  3. Data binding: update display

    A. Through data hijacking

Observer is created to monitor/hijack attributes at all levels in data, and deP is created for each attribute. Dep corresponds to one attribute in data. Complie is used to compile templates, initialize interfaces, and call update objects. Complie also creates a watcher for each expression and specifies a callback function for the update node, adding watcher to all the corresponding dePs.

Talk about your understanding of vue virtual DOM

What is virtual DOM? Basically, it is to add DOM elements in the form of JS objects, which is essentially an optimization of diff algorithm. Virtual DOM also has its own defects

What is VDOM?

The Virtual DOM uses JS to simulate the DOM structure. JavaScript object structure represents the structure of the DOM tree; We then use this tree to build a real DOM tree, insert it into the document and rebuild a new object tree when the state changes. The new tree is then compared to the old tree, and the differences between the two trees are recorded. The recorded differences are applied to the real DOM tree built, and the view is updated. The Virtual DOM is essentially a cache between JS and the DOM.

Create a virtual DOM object (JS object) corresponding to the DOM tree, and represent the DOM tree in the way of object nesting. Then every change of THE DOM will become the change of the property of the JS object. In this way, the performance overhead of finding the property change of JS object is less than that of querying the DOM tree.

Why use VDOM?

  1. DOM operation is very “rang expensive”, put THE DOM comparison operation in JS layer, improve efficiency

  2. DOM structure comparison, in the JS layer to do (Turing complete language: can implement logical code language)

What are the core functions of VDOM

Core function: h(‘ tag name ‘, {… The property name… }, [… child…] ) h(‘ tag name ‘, {… The property name… }, ‘… ‘) patch(container, vnode) patch(vnode, newVnode)

Underlying implementation principles of Vue

Vue.js adopts data hijacking combined with the mode of publisheer-subscriber. It hijacks the setter and getter of each property through object.defineProperty (), publishes messages to subscribers when data changes, and triggers the corresponding listening callback. Vue is a typical MVVM framework. The Model is just a normal javascript object, and attempts to modify it are automatically updated. This design makes state management very simple and intuitive

Observer (data listener) : The core of the Observer is to listen for data changes via object.defineProprtty (). This function defines the setter and getter internally and fires the setter whenever the data changes. At this point, the Observer notifies the subscriber, who is the Watcher

Watcher (subscriber) : The Watcher subscriber acts as a communication bridge between the Observer and Compile, and mainly does the following:

  1. Adds itself to the property subscriber (DEP) when it instantiates itself
  2. You must have an update() method on your own
  3. When dep.notice() is notified of property changes, you can call your own update() method and trigger the callback bound in Compile

Compile (instruction parser) : The main thing Compile does is to parse the template instructions, replace variables in the template with data, and then initialize the render page view, and bind the corresponding node of each instruction to update functions, add subscribers to identify the data, once the data changes, receive notification, update attempt

Vue response principle

Level1: in vue2.0, the core of the responsive implementation is ES5 Object. DefineProperty (obj, prop, descriptor). Object.defineproperty () hijacks the getters and setters of the data and props properties. The getters collect dependencies and the setters distribute updates. Overall, it’s a data hijack + publish – subscriber model.

Level2: in the vue initialization phase (after beforeCreate and beforeCreate), walk through data/props and call object.defineproperty to add getters and setters for each property. A watcher is instantiated for each component and for each computed (as well as for each custom watcher), and a watcher is subscribed to the data/props/computed that is used for rendering/computing. If the data changes, the setters are called. The rendering Watcher is told to recalculate and update the component.

Question 4 VUE Component Communication Level1: Props + events parent-child communication components (parent/parent/parent/children), communication, any component vuex emit events center/emit/emit/on any component of the communication, Attrs/attrs/attrs/listeners offspring (dojo.provide/inject) of communication.

Level2: How vuex works: The State of Vuex serves as a repository for data-driven Vue Component rendering. You can dispatch actions by dispach. Some asynchronous operations can be performed in the Actions. Actions or the view is submitted to mutations, mutations to change state via COMMIT.

Level3: source code analysis: vuex is actually a vue. js plug-in. Plugins need to provide an install method. Install method call will pass Vue as parameter. Vue.user(plugin) installs the plug-in, that is, executes the install method of the plug-in. A beforeCreate hook function is mixed into the global, saving the sample Store to this.$Store for all components.

Level4: Mutation Changes state, what causes the view change? With vue, [instantiate vue with state as a data attribute. ↔ ️ core

What is the V-model? What’s the use?

$emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) = $emit(‘input’, XXX) The same idea applies to components that implement the V-Model approach themselves.

What is your understanding of the VUE lifecycle?

Each Vue instance goes through a series of initialization processes when it is created. A Vue lifecycle hook is a function that is fired when a certain stage or condition is reached in order to complete some action or event

  • The create phase: The vue instance is created

    beforeCreateThe data in data and Methods has not been initialized

    created: The creation is complete, data has a value and is not mounted
  • Mount stage: The vue instance is mounted to the real DOM node

    beforeMount: Can initiate server requests to remove data

    mounted: You can operate the DOM
  • The update phaseWhen the data in the vue instance changes, the component is rerendered

    beforeUpdateBefore the update:

    updatedAfter the update:
  • Destroy stage: The vue instance was destroyed

    beforeDestroy: Before the instance is destroyed, you can manually destroy some methods at this point

    destroyed: after destruction

Component life cycle

Life Cycle (parent component) Parent component beforeCreate –> Parent component created –> Parent component beforeMount –> child component beforeCreate –> child component Created –> child component beforeMount –> Child component Mounted –> Parent component Mounted –> Parent component beforeUpdate –> child component beforeDestroy–> Child component Destroyed –> parent component updated

Loading rendering process Parent beforeCreate-> parent created-> parent beforeMount-> child beforeCreate-> child Created -> child beforeMount-> Child Mounted -> parent

Mounting Phase Parent CREATED -> Child CREATED -> child Mounted -> parent mounted

Parent component update phase Parent beforeUpdate-> Parent updated

Child component Update phase Parent beforeUpdate-> child beforeUpdate-> child Updated -> parent updated

Destruction phase Parent beforeDestroy-> Child beforeDestroy-> child Destroyed -> parent Destroyed

Computed with the watch

In general, you can implement both computed and watch listening, computed is recommended, but the important thing about computed is that the computed attribute is a declarative way of saying that one value depends on another value, When the dependent value or variable changes, the computed property changes; The watch listens to a variable that has already been defined in data, and when that variable changes, the watch method fires.

Watch property monitoring is an object, the key is the property to be observed, and the value is the corresponding callback function. It is mainly used to listen to the changes of certain specific data, so as to perform some specific business logic operations and listen to the changes of properties. It is used to perform asynchronous or costly operations when data changes

The results of computed properties are cached. When a function in computed depends on a property that has not changed, the results are read from the cache when the function is called. Functions that use computed primarily as a property must use return to return the final result for computed because computed is more efficient. Data is not changed and computed is not updated.

Use scenario Computed: This parameter is used when one attribute is affected by multiple attributes, for example, shopping cart checkout. Watch: This parameter is used when one data item affects multiple data items, for example, data search

Why is data in a component a function?

1. When a component is reused multiple times, multiple instances are created. Essentially, these instances use the same constructor. 2. If data is an object, the object is a reference type and affects all instances. So to ensure that data does not conflict between different instances of a component, data must be a function.

Why are v-for and V-if not recommended together

1. When v-for and V-if are on the same node, V-for has a higher priority than V-IF, which means v-IF will be repeated separately in each V-for loop. If you have a large array to walk through and very little data to actually display, this is a big performance waste 2. In this scenario, you are advised to use computed because data is filtered first

The role of keys in React/Vue projects

  • The function of key is to find the corresponding node faster during the execution of diFF algorithm, improve the speed of DIFF, and update the virtual DOM more efficiently.

    Both Vue and React use the DIff algorithm to compare old and new virtual nodes to update them. In the diff function of vue, the key in the old node array is compared according to the key of the new node, so as to find the corresponding old node. If it is not found, it is considered a new node. If there is no key, then a traversal lookup will be used to find the corresponding old node. One is a map mapping, and the other is a traversal lookup. By comparison. Map maps are faster.

  • To force components to update when data changes to avoid the side effects of in-place reuse.

    When vue. js updates a rendered list of elements with V-for, it defaults to a “reuse in place” policy. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will simply reuse each element here and make sure that it shows each element that has been rendered under a specific index. Duplicate keys cause rendering errors.

Communication mode of the VUE component

  • Props /$EMIT parent component communication

    Parent -> child props, child -> parent $on, child -> parent $on, child -> parent $on, child -> emit $on, child -> emit $on, child -> emit $on, child -> emit $on, child -> emit $on

  • $Emit /$ON custom event sibling component communication

    $Bus = new Vue() custom Event

  • Vuex cross-level component communication

    Vuex, $attrs, $Listeners Provide, inject

Bidirectional binding implementation principle

When a Vue instance is created, Vue traverses the properties of the data option, turning them into getters/setters with object.defineProperty and tracking the dependencies internally, notifying the properties of changes when they are accessed or modified. Each component instance has a corresponding watcher instance, which records properties as dependencies during component rendering, and then when the setters for dependencies are called, informs watcher to recalcalculate, so that its associated component can be updated.

V-model implementation and how it is implemented?

  1. vueThe bidirectional binding in is an instructionv-modelCan bind a dynamic value to a view, and changes in the view can change the value.v-modelIs syntax sugar, which by default corresponds to:The value and @ input.
  2. usev-modelCan reduce a lot of tedious event handling code, improve development efficiency, code readability is better
  3. Usually used on form itemsv-model
  4. Native form items can be used directlyv-modelTo use it on a custom component, bind value within the component and handle input events
  5. I have done tests and the output containsv-modelThe component rendering function of the template is found to be converted to a value attribute binding and an event listener, and the event callback does the corresponding variable update operation, indicating that the magic is actually done by the vue compiler.

The realization of the nextTick

  1. nextTickisVueProvides a globalAPIIt’s next timeDOMA delay callback is performed after the update loop has ended and is used after the data has been modified$nextTick, you can get the updated version in the callbackDOM;
  2. Vue executes asynchronously when updating the DOM. As soon as you listen for data changes,VueA queue is started and all data changes that occur in the same event loop are buffered. If the samewatcherIf triggered multiple times, it will only be pushed to the queue – times. This removes duplicate data at buffering time to avoid unnecessary calculations andDOMOperation is very important.nextTickMethod adds a callback function to the queue, ensuring that the function is not called until the previous DOM operation has completed;
  3. For example, when I’m doing something, I’ll use nextTick and pass a callback function into it to perform dom operations.
  4. I also have a brief understandingnextTickImplementation, it will be incallbacksWe put in the function that we passed in, and we usetimerFuncCall them asynchronously, and the preferred asynchronous mode would bePromise. And that makes me understand why I can be herenextTickseedomOperation result.

How does nextTick work?

Execute a delayed callback after the next DOM update loop ends, and use nextTick to get the updated DOM immediately after modifying the data. NextTick mainly uses macro tasks and microtasks. Depending on the execution environment, try to use Promise, MutationObserver, and setImmediate, and if none of the above fails, define an asynchronous method with setTimeout. Multiple calls to nextTick will store the method in a queue, and the current queue will be empty through this asynchronous method.

Have you ever used a slot? Whether a named slot or an anonymous slot or scoped slot is used

A slot in vUE is a very useful thing. A slot is a placeholder. There are three types of slots in VUE: default slots (anonymous), named slots, and scoped slots

Keep – the realization of the alive

What it does: Implements a cache of components to keep them in state to avoid performance problems caused by repeated rendering. Requires cache components to switch frequently, without the need to repeat the render

Scenario: Tabs background navigation, vUE performance optimization

How it works: Viee. js internally abstracts DOM nodes into VNode nodes. The cache of keep-Alive components is also based on VNode nodes rather than storing the DOM structure directly. The components that satisfy the criteria (pruneCache and pruneCache) are cached in the cache object, and the VNode node is extracted from the cache object and rendered when it needs to be rerendered.

mixin

Mixins are used when a mixin project becomes complex and there is duplicate logic between multiple components. Multiple components have the same logic, and pulling out mixins is not a perfect solution, The Composition API proposed by VuE3 is designed to address these issues (there is a cost to being perfect, such as development costs) Scenario: The right side of the news list is the same as the details page on the PC, and you can use mixins for mixed disadvantages: 1. The source of variables is not clear, which is not good for reading. 2. Multiple mixins may cause name conflictsCopy the code

What is vuex? How does it work? How does it work? Which functional scenario uses it?

State management library, similar to Rudux in React

Vuex is a state set management specifically built for VUE, mainly to solve the problem of state sharing between components, emphasizing the centralized management of data. In a word, it is mainly easy to maintain and decouple, so not all projects are suitable to use VUEX. If you’re not building a large project, using Vuex can make your project code tedious and redundant

The core of VUEX: State mutations getters Actions modules

Understanding and usage scenarios of Vuex

Vuex is a state management pattern developed specifically for Vue applications. At the heart of every Vuex app is the store.

  1. The state store of Vuex is responsive; When the Vue component reads the status from the store,

If the state in the store changes, the corresponding component is updated accordingly. 2. The only way to change the state in the Store is to explicitly commit the mutation, which makes it easy to track every state change. Vuex consists of the following core modules:

  1. State: Defines the application State data
  2. Getter: Defines the “Getter” (which can be thought of as the calculated property of the store) in the store,

Just like evaluating attributes, the return value of a getter is cached according to its dependencies, and is recalculated only if its dependencies have changed. 5. Module: Allows a single Store to be split into multiple stores and stored simultaneously in a single state tree

Vuex mechanism for managing state

Vuex is a Vue plug-in for state management for vue.js applications. Vue centrally manages the state shared by multiple components and the data obtained from the background to help the component manage the state. There is also a computing property data getters based on the state. Getters reads the data from the state and calculates it. Component for reading state data State or mapState(), there are also two ways to read the computed property data: store.state or mapState(), and there are also two ways to read the computed property data: store.state or mapState(). Getters and mapGetters (); Updating the state data involves actions and mutations, which trigger the call to action through $store.Dispatch or mapAction(), and actions trigger the call through Commit (), which updates the state directly; Actions can also communicate bidirectionally with the backend API.

Unidirectional data flow

Minimalism of the idea of “Unidirectional data flow” :

  • State: Data source that drives the application.
  • View: Maps state to a view declaratively.
  • Actions: Responds to state changes caused by user input on the view

Unidirectional data flow process:

A simple Unidirectional data flow is when a user accesses a View, the View issues an Action that the user interacts with, and the state is updated in the Action accordingly. The state update triggers the View to update the page. In this way, the data always flows clearly in one direction, which is easy to maintain and predictable

Vue’s Diff algorithm

Problem: Rendering the real DOM is expensive. Modifying a piece of data, if rendered directly to the real DOM, causes the entire DOM tree to redraw and rearrange. The Virtual Dom is a Virtual Dom generated based on the real Dom. When the data of a node in the Virtual Dom changes, a new Vnode is generated. Then the Vnode and oldVnode are compared, and the difference is directly modified on the real Dom. Then set oldVnode to Vnode. Note: When diff algorithm is used, only comparisons are made at the same level, not across levels. When the data changes, the set method calls the dep.notify () method to notify all subscribers to Watcher, who then calls the patch function to patch the real DOM and update the response attempt.

Do you know what new features Vue3 has? What effect will they have?

  • Performance improvement

Smaller, faster support for custom renderers Support for tree shaking: an optimization that removes unwanted code when packaging supports Fragments and cross-component rendering

  • API changes

The template syntax remains 99% unchanged with native support for class-based components, And overwriting the virtual DOM without taking TypeScript’s type inference features into account at design time without any compiler and various stage features can expect more compile-time prompts to reduce runtime overhead. Optimized slot generation can render parent components and child components separately. Static tree lifting reduces rendering costs Proxy-based observer mechanism saves memory overhead

  • Incompatible IE11

The detection mechanism is more comprehensive, accurate and efficient, with more debuggable response tracking

What optimizations have been made for Vue3.0 compilation?

A. The granularity that generates the data update of Block tree vue.js 2.x and triggers the re-rendering is component level, and the entire VNode tree of the component needs to be traversed within a single component. In 2.0, rendering efficiency is positively correlated with component size: the larger the component, the slower the rendering efficiency. Also, for static nodes where no data is updated, these traversals are a waste of performance. Vue.js 3.0 makes it possible to generate a Block tree by analyzing the static template in the compilation stage. Block Tree is a nested Block that cuts the template based on the dynamic node instruction. The node structure inside each Block is fixed, and each Block only needs to track its own dynamic nodes. So, in 3.0, rendering efficiency is no longer positively correlated with template size, but positively correlated with the number of dynamic nodes in the template.

In vue.js 2.x, if a component is passed into slot, every time the parent component is updated, the sub-component is forced to update, resulting in a waste of performance. Vue.js 3.0 optimizes slot generation so that updates to attributes in non-dynamic slots only trigger updates to child components. Dynamic slot refers to the operation that uses v-if, V-for, and dynamic slot name on a slot, which causes the dynamic state of the slot to change during the runtime but cannot be used for component track. C. Diff algorithm optimization

How does Vue3.0 get faster? (Bottom, source)

A. Diff method is used to optimize the virtual DOM in Vue2.x for full comparison. In Vue3.0, PatchFlag is added: When comparing with the last virtual node, the value of the node with patch flag can be compared, and the specific content of the current node to be compared can be learned from the information of flag. B. hoistStatic Static promotion vue 2.x: The element is recreated each time whether or not it participates in the update. Vue3.0: Elements that do not participate in the update are created only once and then reused every time they are rendered. By default, onClick is treated as a dynamic binding, so it is tracked each time. But because it is the same function, it is not tracked, so it can be cached and reused. Original author’s name: Ouyang ah

1. Clone a copy of the original data. 2. Set listening for each attribute in the object

Vue3.0 new features

The similarities and differences between Composition API and react.js Hooks

Use React Hooks to allow you to “hook” into React functions such as component state and side effects handling. Hooks can only be used in function components, and allow us to insert state, side effects, and more into components without having to create classes. The React core team’s adoption strategy is not against class components, so you can upgrade the React version, start trying Hooks in new components, and leave existing components unchanged. Case in point: useState and useEffect are examples of React Hooks that make it possible to add state and runtime side effects to function components. We can also create custom Hooks, which open new doors to code reusability and extensibility.

What performance optimizations have you made for Vue?

The encoding phase minimizes the data and hierarchy in data, and adds getters and setters to all data in data. The watcher is collected and the v-if and V-for cannot be used together. If you need to bind events to each element using v-for, use the event proxy. The SPA page uses the keep-Alive cache component. Use V-IF instead of V-show key to ensure the only use route lazy loading, asynchronous component damping, throttling third-party modules on demand import long list scroll to the visible area dynamic loading image lazy loading SEO optimization pre-render server rendering SSR packaging optimization compression code Tree Shaking/Scope Use CDN to load third-party modules, multithreaded package, Happypack splitChunks, pull out public files, sourceMap to optimize user experience, optimize skeleton screen, PWA can also use cache optimization (client cache, server cache), enable gZIP compression on the server, etc.

Vue versus React

Similarities: 1. Both are componentized development and Virtual DOM 2. Both support data communication between parent and child components using props. 3. Both support data-driven view, which automatically updates status data without directly manipulating the DOM 4. 5. Both support native solutions, React Native, Vue Weex

Differences: 1. Data binding: VUE implements bidirectional data binding while React data flow is unidirectional 2. The component is written differently. React recommends JSX syntax, which is to write HTML and CSS into JavaScript, “all in JS “. Webpack + Vue + Loader single-file component format, that is, HTML, CSS, JS written in the same file; 3. Data state management is different. State objects in the React app are immutable and need to be updated using the setState method. In vUE, state objects are not required, and data is managed by the Data attribute in the VUE object. As for React, when the application state changes, all components will be rendered, so react needs shouldComponentUpdate to control the lifecycle function method.React strictly only applies to the View layer of MVC, while Vue is MVVM mode

React

Parent and child components pass values in React

Use common components for state promotion

React in each component parameters, the father and the son is the father in the parent component binding property is set to a function, when the component need to pass the value to the parent component, is through the props will call the function parameter passed to the function, this can be in the parent component receives the parameters in the function, this parameter is to get the value of the child component

This is the function of binding a normal property directly to the parent component. This property is the exact value that can be obtained from the child component using props

Communication between any components

1. You can create a new Vue EventBus for event listening. While listening, you can execute the new Vue EventBus, which is a publish and subscribe mode, which can be used in React;

2. Use the pubsub – js

3.redux

When is setState synchronized in React and when is it asynchronous?

The React event is an asynchronous operation

If the setTimeout event or custom DOM event is used, it is synchronized

3. Synchronization Condition The asynchronous setstates of multiple dom events are merged before update, but are not merged before update

The life cycle

When an instance of a component is created and inserted into the DOM, these methods are called in the following order:constructor()
static getDerivedStateFromProps()
render()
componentDidMount(Updates within updates can be caused by item or status changes. When a component is rerendered, these methods are called in the following order:static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate() uninstall when components fromDOMThis method is called when thecomponentWillUnmount()


Copy the code

Portals

Portals provide a first-class way to render child components into DOM nodes that exist outside of the PARENT component’s DOM hierarchy. Structures can be created using portals without outside control

Asynchronous components

// Asynchronous lazy loading
const Box = lazy(() = >import('./components/Box'));
Use suspense when using components
<Suspense fallback={<div>loading...</div>}>
    {show && <Box/>}
</Suspense>
Copy the code

immutable.js

Immutable refers to all data types that perform arbitrary operations on data resulting in a modified value and a new object that has not been changed.

Performance optimization

What are shockproof and throttling? What’s the difference? How?

1. The concept

Throttling: After the event is fired, the event handler cannot be called again for a specified period of time. This means that the function can only be called once in a given period of time, and that is the first time the call is triggered.

function debounce(fn) {
  let timeout = null; // Create a tag to hold the return value of the timer
  return function () {
    clearTimeout(timeout); // Clear the previous setTimeout every time the user enters it
    timeout = setTimeout(() = > { // Then create a new setTimeout. This ensures that the fn function will not be executed if there are any characters in the interval after the character is entered
      fn.apply(this.arguments);
    }, 500);
  };
}

function sayHi() {
  console.log('Stabilized successfully');
}

var inp = document.getElementById('inp');
inp.addEventListener('input', debounce(sayHi)); / / image stabilization
Copy the code

Anti-shaking: The event handler can be executed only once, and only when the triggering operation is finished.

function throttle(fn) {
  let canRun = true; // Save a tag by closure
  return function () {
    if(! canRun)return; // Check whether the flag is true at the beginning of the function. Return if it is not true
    canRun = false; // Immediately set to false
    setTimeout(() = > { // Put the execution of the externally passed function in setTimeout
      fn.apply(this.arguments);
      // Finally, set the flag to true(key) after setTimeout completes to indicate that the next loop can be executed. The flag is always false when the timer is not executed and is returned at the beginning
      canRun = true;
    }, 500);
  };
}

function sayHi(e) {
  console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));

Copy the code

2. Application Scenario:

Throttling: scroll loading more, search box search association function, high click, form repeat submission…

Anti-shaking: the search box searches the input, and automatically searches after the input, mobile phone number, email verification input detection, window size resize changes, and then re-renders.

Project optimization

Remove console prints from the production environment. There are many options, including Esling +pre-commit, automatic removal using plug-ins, including Babel-plugin-transform-remov-console, Uglifyjs-webpack-plugin, terser-webpack-plugin. The scaffold vue-CLI uses this plugin to enable caching and multithreaded packaging. No additional plugins need to be installed. Just set the Drop_console of the terser plugin to true in configureWebpack. It’s better to get into good code habits and get rid of useless console once development is almost complete. Turbo console in vscode is a good example.

On-demand loading of third-party libraries. Echarts, which officially uses a configuration file to specify which modules to use, and the other uses babel-plugin-Equire to load on demand. The Element-UI is introduced on demand using babel-plugin-Component implementations.

Public styles, such as uniform adjustments to the styles of element-UI parts such as pop-ups, tables, drop-down checkboxes, and so on. Public components, such as date-picker, upload-file, etc. provided in the Element-UI are basically further encapsulated. Custom components include preview-file, search box, and so on.

In front and back end data exchange, I promoted the project team to use blue lake and interface documents, negotiated with students in the back end, and normalized the return of background data.

Yahoo code mentioned, avoid CSS expressions, filters, less DOM operations, optimize images, sprites, avoid images empty links and so on.

Performance issues: page loading performance, animation performance, operational performance. Performance API to record Performance data.

Front-end optimization technical scheme for Winter relearning:

Cache: strong cache policy controlled by the client.

Lower request cost: The DNS is controlled by the client. After a period of time, the client actively requests for the domain name IP address without using the system DNS. TCP/TLS connection reuse, server upgrade to HTTP2, merge domain names whenever possible.

Reduce the number of requests: JS, CSS packaging to HTML. JS control image asynchronous loading, lazy loading. Small images use data-URIs.

Less transfer volume: Use SVG\gradient instead of the image. Control picture definition according to model and network condition. Use sharpening for low definition images to improve the experience. Design to avoid large backgrounds.

Using CDN acceleration, content distribution network is a virtual distributed network based on re-hosting network, which can cache the content of the source site to the national or global node servers. Users can obtain the content nearby, improving the access speed of resources and sharing the pressure of source sites.

(The written test after the second and third interviews)

1, handwritten bind 2, handwritten simplified version of promise, basic shelf, do not write all, race and other API 3, climb stairs, leetcode-cn.com/problems/cl… (Interviewer asks about tail recursive optimization)

4, monkey eat banana leetcode-cn.com/problems/ko…

5. Number of palindrome strings leetcode-cn.com/problems/pa… (This question appears frequently, friends also encountered in the interview, the longest return text substring)

2. Talk about prototype chains. Prototype chains implement inheritance.

4. Cache related (compare cache? Strong cache? What are the properties of a cookie?

What about CommonJS and EsModule?

1, project related issues, the project still needs to be well prepared. Ask a little bit carefully

What difficulties have you encountered? How was it solved? What optimizations have been made? Is optimization quantified? Which loaders have you used? The plugin? What does this plugin do? How does that work? The sourcemap principle? (Shabi, because glanced at a blog, said I know a little bit, said a VLQ code, and then asked embarrassed, not directly say no)

2, HTTP and TCP, HTTPS, HTTP2 (queue header blocking? What problems were solved? Which problems are not solved? TCP and UDP?) . Algorithm and symmetric encryption, asymmetric encryption about what? What’s the difference between abstractions and encryption? What encryption algorithms do you know? What is the webSocket usage scenario (socket.io degraded)?

3. Front end security precautions? XSS and CSRF attacks? \

4. What do you think of the Virtual DOM? Do you know the AST syntax tree? What does Vue-Loader do? Vue diff? Vue Computed and Watch? How is the cache (dirty) implemented for computed? Vue3 bidirectional data binding implementation? CreateRender? What are the differences with VUE2? Functional programming is mentioned, and the understanding of functional programming pairs is described. (Answer very rubbish, vuE3 know little, especially big live did not watch carefully)

5. Understanding of MVC (React) MVVM (VUE)

6, Node related issues, node event loop mechanism? The difference between the two modes of stream? Koa source code will feel and express are very different, say?

7, you have written a small program, say and write vue what is the difference? And then I said setData is going to have a performance problem. Dig yourself a hole again) say jsbrige?

The Angle between the hour hand and the minute hand? 9. Why did you leave? How did you learn? What’s the problem?

Question 10: How to implement depth-first traversal and breadth-first traversal?

5

Question 11: Can you implement a copy function using depth-first and breadth-first ideas, respectively?

1. What is the problem with the project? 4. Teamwork, previous development process? 5. Career planning? What seems to be the problem?

Feel free to correct any mistakes in the comments section, and if this post helped you, feel free to like 👍 and follow 😊