Summary of 2021 high frequency core front end interview questions





1. How to understand HTML semantics

HTML5 semantics

  • Make it easier for people to read (clear code structure, increase code readability)
  • To make search engines easier to read (SEO), search engine crawlers will give different weights according to different tags

Semantic tags:header nav main article section aside footer

2. By default, which HTML tags are block level elements and which are inline elements

  • Block level elements:display: block/tablehavediv div h1 h2 table ul ol li petc.
  • Inline element:display: inline/inline-blockhavespan img input button i betc.

3. HTML5 new content and API

HTML5 new content and API

  • Classlist property
  • Queryselector() and queryselectorall()
  • getElementsByClassName()
  • Custom data properties
  • Local storage
  • insertAdjacentHtml()、insertAdjacentText()、insertAdjacentElement()
  • Content editable
  • Preload


1. Box model

CSS box model

Box sizing properties

The CSS box model contains two types:

  • W3C standard box model(box-sizing: content-box, default), width and height are not affected by padding and border
  • Ie weird box model(box-sizing: border-box)The width and height are affected by padding and border

2. Margin vertical overlap

  • Of adjacent elementsmargin-topandmargin-bottomWill overlap
  • Elements of empty content also overlap

Think: the following code,AAAandBBBWhat is the spacing between?



The answer is 15px

3. Margin negative value

  • margin-topNegative values move the element up
  • margin-leftNegative values move the element to the left
  • margin-rightIf the value is negative, the right element moves to the left and is not affected
  • margin-bottomIf it is negative, the lower element will move up and will not be affected

4. BFC (block level formatting context)

3 minutes to understand BFC

Elements with BFC characteristics can be regarded as isolated independent containers, and the elements in the container will not affect the external elements in layout

The BFC characteristic can be triggered as long as the element meets any of the following conditions:

  1. Root element (i.e(label)
  2. Floating element float is not noneleftright
  3. Absolute positioning element position is not static or relative. (forabsolutefixed
  4. Block element whose value of overflow is not visible (yes)autoscrollhidden)
  5. The value of display isinline-blockflexgrid tabletable-celltable-caption

In the same BFC:

  1. Boxes are placed vertically one by one
  2. The distance in the vertical direction is determined by the margin (the margins of two adjacent boxes belonging to the same BFC will overlap, independent of the direction)
  3. The left side of the margin box of each element contacts the left side of the containing block border box (for formatting from left to right, otherwise the opposite). Even if there is a float
  4. The area of BFC does not overlap with the element area of float
  5. When calculating the height of BFC, floating sub elements also participate in the calculation
  6. BFC is an isolated independent container on the page. The child elements in the container will not affect the external elements, and vice versa


  1. When belonging to different BFCs, margin overlap can be prevented
  2. Clear internal float
  3. Adaptive multi column layout

5. Float layout

.fl {
    float: left;

.fr {
    float: right;

.clearfix {
    zoom: 1; //  Compatible with IE

.clearfix:after {
    content: '';
    display: block;
    clear: both;
    visibility: hidden;
    overflow: hidden;

6. Flex layout

Flex layout

Flex bisection layout


7. Three column layout

There are 8 ways to realize the three column layout:

  1. Floating layout
  2. Positioning layout
  3. Flex layout
  4. Table layout
  5. Grid layout
  6. Calc function layout
  7. Grail layout
  8. Dual wing layout

The Holy Grail layout and double wing layout often considered in interviews:

  • Three column layout, the middle column is loaded and rendered first (the content is the most important)
  • The content on both sides is fixed, and the content in the middle is adaptive with the width
  • Generally used for PC terminal

8. CSS positioning

Detailed explanation of position attribute in CSS

reflection:relativeabsolutefixedBased on what positioning?


  • relativeAccording to their own positioning(relative to its original position in the document stream).In the outermost layerThe label is to locate the origin
  • absoluteLocate according to the location element of the nearest layer(according topostionwrongstaticThe ancestor class element of the. When no parent ispostionwrongstaticWhen positioning,SoPosition as origin
  • fixedOffset positioning according to the window as the origin(that is, it will not be offset according to the scrolling of the scroll bar)

9. Center alignment implementation

Summary of common methods of CSS centering

10. Inheritance of line height

Think: in the following codepWhat is the row height of the label?

body {
        font-size: 20px;
        line-height: 200%;

    p {
        font-size: 16px;


The answer is 40px


  • Write specific values, such asbody{ line-height: 30px;}, inherit the value(pThe row height is30px
  • Write scale, e.gbody{ line-height: 2;}, inherit the proportion(pThe row height is16px*2 = 32pxP twice the font size
  • Write percentage (PIT), e.gbody{ line-height: 200%;}, inherit the calculated value(pThe row height is20px*2 = 40px2 times the font size of body

11. CSS length unit

  1. pxFixed pixels, once set, cannot be changed to fit the page size.
  2. em Relative to parent elementUnit of length. (not commonly used)
  3. rem Relative to rootelementUnit of length. (common)
  4. rpxRelative length unit of wechat applet. The applet specifies a screen width of 750 rpx. If the screen width is 375px and there are 750 physical pixels on the iPhone 6, then 750rpx = 375px = 750 physical pixels and 1rpx = 0.5px = 1 Physical pixel. (wechat applet only)

12. CSS responsive media query

If the resolution of a terminal is less than 980px, it can be written as follows:

@media only screen and (max-width: 980px) {
  #head { … }
  #content { … }
  #footer { … }

If we want to set the view compatible with iPad and iPhone, we can set it as follows:

/** iPad **/
@media only screen and (min-width: 768px) and (max-width: 1024px) {}
/** iPhone **/
@media only screen and (min-width: 320px) and (max-width: 767px) {}

General cooperation for media queryremUnits achieve responsiveness, soremhaveLadder natureDisadvantages of

13. Web page viewport size

  • Screen heightwindow.screen.height(display screen device height)
  • Web page viewport heightwindow.innerHeight(the height after removing the head and bottom of the browser itself, including the height of the scroll bar)
  • Body heightdocument.body.clientHeight(true height of page content)


Divine map
Width is the same as theory~

14. CSS3 vw / vh

  • vw1% of web page viewport width(window.innerWidth = 1vw
  • vh1% of web page viewport height(window.innerHeight = 1vh )
  • vminselectionvwandvhThe smallest of the
  • vmaxselectionvwandvhThe biggest one in the


1. ES6

View ES6 album

  1. Let and const keywords of ES6

  2. Deconstruction assignment of ES6

  3. Extension operator of ES6

  4. New string features of ES6

  5. New numerical features of ES6

  6. New array features of ES6

  7. Function optimization of ES6 (default parameters, residual parameters, arrow function)

  8. Promise of ES6

  9. Async / await of ES6

  10. Class of ES6

  11. Map and set of ES6

  12. Import and export of ES6

  13. Generator function of ES6

  14. ES6 for Of cycle

2. Data type and detection

Summary of several methods of detecting data types in JS

JavaScript data type:

  1. Number (basic type)
  2. String (basic type)
  3. Boolean (basic type)
  4. Null (basic type)
  5. Undefined (basic type)
  6. Symbol (ES6 – basic type)
  7. Bigint (ES10 – basic type)
  8. Object (reference type, including function, [], {})

Characteristics of the basic type: data directly stored in stack memory
Characteristics of reference type: the stored object is referenced in the stack, and the real data is stored in the heap memory


3. Deep and shallow copies

Deep and shallow copies in JavaScript

The fundamental difference between deep copy and shallow copy is whether an object is actually obtainedCopy entities, not references

A shallow copy copies only one layer of object properties, while a deep copy copies only one layer of object propertiesrecursive copyingAll levels are.

  • Deep copy opens up a new memory address in the computer for storing copied objects
  • Shallow copy only points to the copied memory address. If the object in the original address is changed, the shallow copied object will be changed accordingly


4. Prototype and prototype chain (one of the three mountains)

Deeply understand the prototype and prototype chain of JavaScript

Prototype (explicit prototype)

All functions (functions only) haveprototypeattribute

prototypeObject is used to put the shared properties and methods of an instance of the same type. In essence, it is for the sake of memory.

Person.prototype.sayHello = function() {
console. Log (person1. Sayhello = = = person2. Sayhello) // true, the same method


_ proto _ (implicit prototype)

All objects have_proto _attribute

_proto _To whom? There are three situations:

/*1. Literal mode*/
var a = {};
console. log(a.constructor === Object); //  True (constructor object)
console.log(a.__proto__ === a.constructor.prototype); // true
console.log(a.__proto__ === Object.prototype); // true

/*2. Constructor mode*/
var A = function (){}; 
var a = new A();
console. log(a.constructor === A); //  True (constructor function a)
console.log(a.__proto__ === a.constructor.prototype); // true

/*3、Object. Create() method*/
var a1 = {a:1} 
var a2 = Object.create(a1);
console. log(a2.constructor === Object); //  True (constructor object)
console.log(a2.__proto__ === a1); // true 
console. log(a2.__proto__ === a2.constructor.prototype); // False (this is the exception in Figure 1)


Constructor (pointing to the constructor that created the object)

Each prototype object can pass through the object.constructor Points to the constructor that created the object

function Person() {};
var person1 = new Person();
var person2 = new Person();

//The constructor property of the instantiated object points to the constructor itself
person1.constructor === Person; 

//The prototype property of the constructor has a constructor property that points to the constructor itself
Person.prototype.constructor === Person;

//From the above two
person1.constructor === Person.prototype.constructor

person1.__proto__ === Person.prototype

Person.constructor === Function; 
Function.constructor === Function;


Prototype chain


a.__proto__ === A.prototype
A.prototype.__proto__ === Object.prototype
Object.prototype.__proto__ === null

In the figure belowThe chain structure composed of interrelated prototypes is the prototype chain, that isblueThis line.

Ultimate diagram of prototype and prototype chain

If you understand this figure, the prototype and prototype chain will be basically understood.

Instanceof principle

instanceof It can only be used to judge the object type, not the original type。 And all object types instanceof ObjectAlltrue

instanceofThe internal mechanism isBy judging whether the type can be found in the prototype chain of the objectprototype

class People {};
class Student extends People {};

let s1 = new Student();

console.log(s1 instanceof Student); // true
console.log(s1 instanceof People);  // true
console.log(s1 instanceof Object);  // true

console.log(s1.__proto__ === Student.prototype); // true
console.log(Student.prototype.__proto__ === People.prototype); // true
console.log(People.prototype.__proto__ === Object.prototype); // true

s1.__proto__ === Student.prototype                =>   s1 instanceof Student
Student.prototype.__proto__ === People.prototype  =>   Student.prototype instanceof People
People.prototype.__proto__ === Object.prototype   =>   People.prototype instanceof Object

The judgment team of instanceof is: along S1__ proto__ Use this line to find and follow the student’s prototype line at the same time. If the two lines can find the same reference, that is, the same object, then true will be returned. If the end points are not coincident, false is returned. This well explains the output of the above code.

Inheritance mode

Inheritance in JavaScript

5. Scope, this and closure (two of the three mountains)


In JavaScript, scopes are divided intoglobal scopeandFunction scope

global scope
The code can be accessed anywhere in the program,Window objectAll built-in properties have global scope.

Function scope
Only fixed code fragments can be accessed
The scope has a parent-child relationship. The determination of the parent-child relationship depends on the scope in which the function is created. As mentioned above, if the bar function is created under FN scope, “FN scope” is the parent of “bar scope”.

The greatest use of scope isIsolate variablesThere will be no conflict between variables with the same name under different scopes

Scope chain

Block level scope of ES6

Let keyword of ES6

Variable value:reachestablishThis variable takes an upward value in the scope of the function, andNot callThis function takes an upward value
If no value is found in the current scope, it will be queried from the parent scope until the global scope is found. The chain formed by such a search process is calledScope chain

Think: what does the following code output?

function create() {
    const a = 100;
    return function () {
const fn = create();
const a = 200;
fn();  // 100
function print(fn) {
    const a = 200;
const a = 100;
function fn() {
print(fn); // 100

fromestablishThe function of takes an upward value, andNot callValue up when function


Thoroughly understand this point in JavaScript

This always points to the object that finally calls it, that is, when it is executed, who calls it?

Special attention:

  • The anonymous function executes itself and is not called by the parent object, so this points to window
  • setTimeout(function () { console.log(this) });, this points to window
  • setTimeout(() => { console.log(this) });, this points to the context
  • This in the constructor points to the instance object
  • bindcallapplyYou can change the direction of this

Summary of call, apply and bind methods in JavaScript


JavaScript closure

A closure is a function that has access to a variable in the scope of another function.

The most common way to create a closure is to create another function within one function and access the local variables of this function through another function

Characteristics of closures:

  1. Function nested function
  2. Internal functions can reference external parameters and variables
  3. Parameters and variables are not collected by the garbage collection mechanism
function aaa() {  
    var a = 1;  
    return function(){
var fun = aaa();  
fun();//  1 after the execution of a + +, then a is still in ~ a will be stationed in memory for a long time
fun();// 2   
fun = null;// A is recycled!!

6. Asynchronous (the third of the three mountains)

Single thread and multithreading

  • JavaScript is a single threaded language(it can be said that this is the core and basic feature of JavaScript)
  • The browser kernel is multithreaded

Although JavaScript is single threaded, it is not single threaded inside the browser.
Some I / O operations, timer timing and event listening (click, Keydown…) are completed by other threads provided by the browser.

Synchronous and asynchronous

  • Synchronization: refers to tasks queued for execution on the main thread. The next task can be executed only after the previous task is executed.
    When we open the website, the rendering process of the website, such as the rendering of elements, is actually a synchronization task

  • Asynchronous: refers to a task that does not enter the main thread but enters the task queue. Only when the task queue notifies the main thread that an asynchronous task can be executed will the task enter the main thread.
    When we open a website, network requests such as image loading (Ajax, Axios) and timed tasks (setTimeout) are actually asynchronous tasks

alert(2); //  Synchronization will block the execution of code
    console. log(1); //  Asynchronous, does not block code execution


Event loop

On event loop

Event cycle mechanism:

  1. First, judge whether JS is synchronous or asynchronous,Synchronization enters the main thread and asynchrony enters the main threadevent table
  2. Asynchronous tasks inevent tableWhen the trigger conditions are met, the function registered in is pushedMessage queueevent queue
  3. After entering the main thread, the synchronous task will be executed until the main thread is idle. It will not check whether there are executable asynchronous tasks in the message queue. If so, it will be pushed into the main thread


Asynchronous tasks can be divided into:

  • Macrotask
    Wait until the execution stack and micro task queue are executed. After each macro task is executed, you will check whether there are new tasks in the micro task queue. If so, you will empty the tasks in the micro task queue before continuing to execute the next macro task
    Including: script code block, setTimeout, setinterval, I / O

  • Microtask
    When the code in the execution stack is executed, check whether there are tasks in the micro task queue before executing the macro task queue. If so, empty the tasks in the micro task queue before executing the macro task queue
    Including promise, nexttick, callback, object observe,MutationObserver

The order of execution isExecute code in stack = > micro task = > macro task = > micro task = > macro task = >

DOM events are also based on event loop, but not asynchronous

Asynchronous tasks are executed in order:

  1. If a micro task is encountered during the execution of a macro task, it will be placed in the [event queue] of the micro task
  2. After the current macro task is executed, the event queue of the micro task will be viewed and all micro tasks in it will be executed in turn



Master promise thoroughly

Write a promise

PromiseIt is a solution for asynchronous programming and has three states:

  • pending(waiting state)
  • fulfiled(successful status)
  • rejected(failure status)

oncePromisecoverresolveorreject, you can no longer migrate to any other state (i.e. state)immutable)。 createpromiseInstance, it executes immediately.

Basic process:

  1. initializationPromiseStatus(pending);
  2. Execute nowPromisePassed infnFunction that willPromiseinsideresolverejectFunction is passed as an argument tofn, handle according to the time of event mechanism;
  3. implementthen(…)Register callback processing array(thenMethod can be the samepromiseCall multiple times);
  4. PromiseThe key is to ensure that,thenMethodonFulfilledandonRejected, must bethenThe method is executed in the new execution stack after the event loop of the called round;

Simple usage:

let p = new Promise((resolve, reject) => {
    var num = Math. ceil(Math.random() * 10); // Generate random numbers of 1-10
    if (num <= 5) {
    } else {
        Reject ('the number is too large ');

//Then usage
p.then((data) => {
    console.log('resolve:' + data);
}, (err) => {
    console.log('reject:' + err);

//Catch usage
p.then((data) => { console.log('resolve:' + data); })
 .catch((err) => { console.log('reject:' + err); })

Async and await

More about async / await


  1. Execute the async function and return a promise object by default
  2. Await is equivalent to promise’s then
  3. try… Catch can catch exceptions instead of promise’s catch
function dice(val) {
    return new Promise((resolve, reject) => {
        let sino = parseInt(Math.random() * 6 + 1);
        if (sino > 3) {
            Val = = = 'big'? resolve(sino) : reject(sino);
        } else {
            Val = = = 'big'? reject(sino) : resolve(sino);
async function test() {
	// try... Catch can catch exceptions instead of promise's catch 
    try {
        //Put await and the operation to get its value in try
        Let n = await dice ('Big ')// Await is equivalent to promise's then
        console. Log ('won '+ n);
    } catch (error) {
        //Failed operations are placed in catch
        console. Log ('lost '+ error)// Catch equivalent to promise

Think: the following code output order

async function async1() {
    console. log(1); //  Synchronization 2
    await async2(); //  Execute async2 () before await 
    console. log(2); //  Asynchronous (all the code below await is asynchronous)

async function async2() {
    console. log(3); //  Synchronization 3

console. log(4); //  Sync 1

setTimeout(() => {
    console. log(5); //  Asynchronous 2 macro task
}, 0);


console. log(6); //  Synchronization 4



All the code below await is asynchronous

Asynchronous loading JS mode

1. The anonymous function automatically creates a script tag and loads JS

    var scriptEle = document.createElement("script");
    scriptEle.type = "text/javasctipt";
    scriptEle.async = true;
    scriptEle.src = "";
    var x = document.getElementsByTagName("head")[0];
    x.insertBefore(scriptEle, x.firstChild);		

2. Async attribute

//The async attribute specifies that the load script will execute asynchronously once it is available

3. Defer attribute

//The defer attribute specifies whether script execution is delayed until the page is loaded

7. Dom and BOM

DOM object and BOM object


DOM (document object model) is the W3C standard, which isRefers to the document object model(tree structure).
DOM defines standard methods for accessing and manipulating HTML documents. Through it, you canAccess all elements of an HTML document

1. HTML DOM tree:

2. DOM node:

According to the W3C HTML DOM standard, all contents in HTML documents are nodes:

  • Document node: entire document (document object)
  • Element node: each HTML element (element object)
  • Text node: text within an HTML element (text object)
  • Attribute node: each HTML attribute (attribute object)
  • Comment Nodes : comment (comment object)

3. DOM lookup:

//Get the tag collection according to the tag name
const div1 = document. getElementsByTagName("div"); //  Div1 div2 div3 div4 div5 (element collection htmlcollection)
const div2 = document. querySelectorAll("div"); //  Div1 div2 div3 div4 div5 (node set NodeList)

//Get according to class attribute
const div3 = document. getElementsByClassName("div"); //  Div1 div2 (element collection htmlcollection)
const div4 = document. querySelectorAll(".div"); //  Div1 div2 (node set NodeList)

//Get from ID attribute value
const div5 = document. getElementById("div"); //  Div3 (one label)
const div6 = document. querySelectorAll("#div"); //  Div3 (node set NodeList)

//Obtained according to the value of the name attribute
const div7 = document. getElementsByName("div"); //  Div4 div5 (node set NodeList)

//Gets the first tag from the tag name
const div8 = document. querySelector("div"); //  Div1 (one label)

4. DOM operation:

//Create node
var divEle = document.createElement("div");
var pEle = document.createElement("p");
var aEle = document.createElement("a");

//Add node
document. body. appendChild(divEle);  //  Add the div element created above to the tail of the body
document. body. insertBefore(pEle, divEle);  //  Under body, add the P element in front of the div element

//Replace node
document. body. replaceChild(aEle, pEle);  //  Under body, replace the P element with the a element

//Set text node
aEle. InnerText = "what are you doing?"
divEle . InnerHTML = "what are you doing?"

//Set properties
divEle . setAttribute("class","list"); //  Add a class ='List 'attribute to the div element

//Get class value
divEle. Classname // get the class on div element

//Set style
divEle. style. color = "red"; //  Set the color style of div element to red = "10px" = "10px" = "10px" = "relative"

5. DOM Optimization:

DOM operations are expensive operations, which will lead to slow UI response of web applications. Therefore, the occurrence of such processes should be reduced as much as possible.

//Do not cache DOM query results
for (let i = 0; i < document.getElementsByTagName("div").length; i++) {
    //In each loop, the length is calculated and DOM queries are performed frequently

//Cache DOM query results
const div = document.getElementsByTagName("div");
const length = div.length;
for (let i = 0; i < length; i++) {
    //DOM query only once

Change frequent DOM operations toOne time operation:

var el = document.getElementById('mydiv');

//DOM operations before optimization will result in three rearrangements = '1px'; = '2px'; = '5px';

//The optimized DOM operation will be rearranged only once = 'border-left: 1px; border-right: 2px; padding: 5px;';


BOM (browser object model) refers toBrowser object model, yesAccess and operate on browser windows
Using BOM, developers can move the window, change the text in the status bar, and perform other actions that are not directly related to the page content. Enable JavaScript to “talk” with the browser.

  1. WindowObject(window.alert() …)
  2. NavigatorObject(navigator.userAgent …)
  3. ScreenObject(screen.widthscreen.height …)
  4. LocationObject(location.hreflocation.reload()location.replace() …)
  5. HistoryObject(history.forward()history.back() …)

8. Event flow

JavaScript event flow

The sequence of event propagation corresponds to two event flow models of the browser:

  • Bubbling event flowThe propagation order of click events in is=>= > = > document (default)
    The propagation order of click event in captured event flow is document = > = > = >

    Click me!

    document.getElementById("div").addEventListener("click", (event) => {
    console.log('this is div');

    document.body.addEventListener("click", (event) => {
    console.log('this is body');

    document.documentElement.addEventListener("click", (event) => {
    console.log('this is html');

    document.addEventListener("click", (event) => {
    console.log('this is document');

    //The default is event capture, so output in order:
    // this is div
    // this is body
    // this is html
    // this is document

    Event capture

    Event bubbling (default)

    DOM standard event flow

    绑定事件时通过addEventListener函数,它有三个参数,第三个参数若是true,则表示采用Event capture,若是false(默认),则表示采用事件冒泡。

    box1.addEventListener('click', function () {
    console. Log ('box1 capture stage ');
    }, true);
    box2.addEventListener('click', function () {
    console. Log ('box2 capture stage ');
    }, true);
    box3.addEventListener('click', function () {
    console. Log ('box3 capture stage ');
    }, true);
    box1.addEventListener('click', function () {
    console. Log ('box1 bubbling stage ');
    }, false);
    box2.addEventListener('click', function () {
    console. Log ('box2 bubbling stage ');
    }, false);
    box3.addEventListener('click', function () {
    console. Log ('box3 bubbling stage ');
    }, false);

    element.addEventListener(event, function, useCapture)
    The third parameter, usecapture, is optional. Boolean value that specifies whether the event is executed during the capture or bubbling phase:

    True - the event handle is executed during the capture phase
    False (default) - the event handle executes during the bubbling phase

    Prevent event bubbling / capture
    Use event Stoppropagation() prevents further propagation of the current event in the capture and bubbling phases.

    The W3C method is: event stopPropagation()
    Ie uses: event cancelBubble = true

    p.addEventListener("click", (event) => {
    event. stopPropagation(); // Prevent event bubbling
    console. log('this is p'); // Only 'this is p' will be output

    document.addEventListener("click", (event) => {
    event.stopPropagation(); // 阻止Event capture
    console. log('this is document'); // Only 'this is document' will be output
    }, true);

    Ie compatible writing:
    window.event? window.event.cancelBubble = true : event.stopPropagation();

    Block default events

    The W3C method is: event preventDefault()
    Ie uses: event returnValue = false

    Since the default behavior is said, of course, the element must have a default behavior to be cancelled. If the element itself has no default behavior, the call is of course invalid.
    Block default jump

    document.getElementById("a").addEventListener("click", (event) => {
    console. Log ('a link jump blocked ');

    Event agent / delegate
    The principle of event agent uses event bubbling and target element. Add the event processor to the parent element and wait for the event bubbling of the child element. The parent element can judge which child element it is through target (ie is srcalelement) and handle it accordingly.


    //Do not use event proxy
    var colorList = document.getElementById("color-list");
    var colors = colorList.getElementsByTagName("li");
    for (var i = 0; i < colors.length; i++) {
    colors[i]. addEventListener('click', showColor); // Bind a click event to each Li

    function showColor(e) {
    e = e || window.event;
    var targetElement = || e.srcElement;

    //Use event proxy
    var colorList = document.getElementById("color-list");
    colorList. addEventListener('click', showColor); // By bubbling, you only need to give Li's parent a click event

    function showColor(e) {
    e = e || window.event;
    var targetElement = || e.srcElement;

    9. Cross domain

    JS cross domain explanation
    Cross domain refers to requesting resources of another domain name from a web page of one domain name. For example, from Com page to request Com resources.
    Non homologous. When requesting data, the browser will report an exception in the console to prompt that access is denied. It is caused by the browser's homology policy and is the security restriction imposed by the browser on JavaScript.

    Homology strategy
    Homology strategy是浏览器最核心也最基本的安全功能。如果缺少了Homology strategy,则浏览器的正常功能可能都会受到影响。可以说Web是构建在Homology strategy基础之上的,浏览器只是针对Homology strategy的一种实现。

    Homology: protocol, domain name and port are all the same, which is homology.
    Cross domain: as long as there is one difference in protocol, domain name and port, it is cross domain.

    不存在跨域的情况(无视Homology strategy)

    服务端请求服务端不存在跨域(浏览器请求服务器才存在Homology strategy)
    (the SRC attribute of the tag does not exist across domains)
    (the href attribute of the label does not exist across domains)
    (< code > SRC < / code > attribute of < / code > tag does not exist cross domain)</li>
    < H3 id = "several common cross domain methods" > several common cross domain methods</h3>
    <li>Jsonp cross domain (dynamically add < code > < script > < / code > tags and cross domain using SRC attribute. Common)</li>
    <li>CORS cross domain resource sharing (implemented by the server. Common and mainstream)</li>
    <li>Node proxy cross domain (use < code > proxytable < / code > to make the local node server proxy request the real server. Common)</li>
    <li>document. Domain + iframe cross domain</li>
    <li>PostMessage cross domain</li>
    < H3 id = "security" > Security</h3>
    <li><a href=" " target="_ Blank "> XSS cross site scripting attack</a></li>
    <li><a href=" " target="_ Blank "> CSRF Cross Site Request Forgery</a></li>
    <h2 id="10-http">10. HTTP</h2>
    <p><strong><a href=" " target="_ Blank "> on HTTP < / a > < / strong ></p>
    <p>HTTP protocol is a transmission protocol based on < code > TCP / IP < / code > communication protocol to transfer data (HTML files, picture files, query results, etc.) for transmitting hypertext from the server to the local browser</p>
    <p><strong><a href=" " target="_ Blank "> TCP's three handshakes and four waves < / a > < / strong ></p>
    < H3 id = "HTTP three features" > HTTP three features</h3>
    <li>< strong > HTTP is connectionless < / strong >: connectionless means that < strong > only one request is processed for each connection < / strong >. After the server processes the customer's request and receives the customer's response, it disconnects. In this way, the transmission time can be saved</ li>
    <li>< strong > HTTP is media independent < / strong >: this means that as long as the client and server know how to process the data content, < strong > any type of data can be sent through HTTP < / strong >. The client and server specify to use the appropriate MIME type content type</ li>
    <li>< strong > HTTP is stateless < / strong >: stateless means that the protocol < strong > has no memory ability for transaction processing < / strong >. Missing status means that if the previous information is required for subsequent processing, it must be retransmitted, which may increase the amount of data transmitted per connection. On the other hand, when the server does not need previous information, its response is faster</ li>
    < H3 id = "HTTP message structure" > HTTP message structure</h3>
    <p>< strong > request headers: < / strong > < br >
    The request message that the client sends an HTTP request to the server includes the following formats: request line, request header, blank line and request data. The following figure shows the general format of the request message. < br >
    <img src=" "ALT =" insert picture description here "loading =" lazy "></p>
    <p>< strong > server response headers: < / strong > < br >
    The HTTP response also consists of four parts: status line, message header, blank line and response body< br>
    <img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "></p>
    < H3 id = "HTTP status code" > HTTP status code</h3>
    <p><strong><a href=" " target="_ Blank "> HTTP status code details < / a > < / strong ></p>
    <p>< strong > RFC stipulates that HTTP status codes are three digits, which are divided into five categories: < / strong ></p>
    <li>1XX: < strong > information < / strong >, the server receives the request and needs the requester to continue the operation</li>
    <li>2XX: < strong > successful < / strong >, the operation is successfully received and processed (200 - Request successful)</li>
    <li>3xx: < strong > redirect < / strong >, further operations are required to complete the request (302 - resources (web pages, etc.) are temporarily transferred to other URLs, and the browser will process them automatically)</li>
    <li>4xx: < strong > client error < / strong >, the request contains syntax error or the request cannot be completed (404 - the requested resource (web page, etc.) does not exist)</li>
    <li>5xx: < strong > server error < / strong >, the server encountered an error while processing the request (500 - internal server error)</li>
    < H3 id = "HTTP request method" > HTTP request method</h3>
    <p><strong><a href=" " target="_ Blank "> the most detailed summary of get and post < / a > < / strong ></p>
    < th > method < / th >
    < th > protocol version < / th >
    < th > description < / th >
    <td>Request the specified page information and return the entity body. (< strong > get data < / strong >)</td>
    <td>It is similar to a get request, except that there is no specific content in the returned response to get the header</ td>
    <td>Submit data to the specified resource for processing requests (such as submitting forms or uploading files). The data is contained in the request body. Post requests may lead to the establishment of new resources and / or the modification of existing resources. (< strong > new data < / strong >)</td>
    <td>The data transmitted from the client to the server replaces the contents of the specified document</ td>
    <td>Requests the server to delete the specified page. (< strong > delete data < / strong >)</td>
    <td>Reserved for proxy servers that can change the connection to pipeline mode</ td>
    <td>Allows clients to view the performance of the server</ td>
    <td>Echo the request received by the server, which is mainly used for testing or diagnosis</ td>
    <td>It is a supplement to the put method and is used to locally update known resources. (< strong > update data < / strong >)</td>
    < H3 id = "HTTP cache" > HTTP cache</h3>
    <p><strong><a href=" " target="_ Blank "> read HTTP cache (super detailed) < / a > < / strong ></p>
    <p>When a client requests a resource from the server, it will first arrive at the browser cache. If the browser has a copy of the "resource to request", it can extract the resource directly from the browser cache rather than from the original server</ p>
    <p>The common HTTP cache < strong > can only cache the get request < / strong > response resources, but it can't do anything about other types of responses</ p>
    <p>< strong > advantages of caching: < / strong ></p>
    <li>Reduce redundant data transmission and save your network cost</ li>
    <li>It alleviates the problem of network bottleneck. Pages can be loaded faster without more bandwidth</ li>
    <li>Reduced requirements for the original server. The server can respond faster and avoid overload</ li>
    <li>The distance delay is reduced because it is slower to load pages from far away places</ li>
    <p>< strong > strong cache and negotiation cache: < / strong ></p>
    <li>When requesting a resource for the first time, the server returns the resource and returns the resource and < strong > resource ID < / strong > (< code > last modified < / code >, < code > Etag < / code >) in < code > response header < / code >)</li>
    <li>When requesting resources for the second time, the browser will judge whether the < code > response headers < / code > hit (< code > cache control attribute < / code >) < strong > strong cache < / strong >. If it hits, it will directly read the cache locally (status code 200) and will not send a request to the server</li>
    <li>When the strong cache fails to hit, the request parameters (including < code > if modified since < / code >, < code > if not match < / code >) are added to the < code > request header < / code > header and passed to the server to judge whether the < strong > negotiation cache < / strong > is hit, If it hits (< code > if modified since = = last modified < / code >, < code > if not match = = Etag < / code >), the server will request to return (status code 304), will not return resources, and tells the browser to read the cache locally</ li>
    <li>When the negotiation cache misses (< code > if modified since! = last modified < / code >, < code > if not match! = Etag < / code >), the server directly returns a new resource (status code 200) and a new resource ID (new < code > last modified < / code >, new < code > Etag < / code >)</li>
    <p>< strong > resource ID: < / strong ></p>
    <li>Last modified: the last modified time of the resource (only accurate to seconds)</li>
    <li>Etag: the unique identification of the resource, which will be used preferentially (a string, similar to human fingerprints)</li>
    <p>Etag is more accurate if resources are repeatedly produced and the content remains unchanged</p>
    <p><img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "></p>
    <p>< strong > difference: < / strong ></p>
    <li>Strong cache hit: do not request the server, but directly request the cache; (very fast)</li>
    <li>Negotiation cache hit: the server will be requested, the content will not be returned, and then the cache will be read; (server cache policy) < br >
    <img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "></li>
    < H2 id = "11 - Common JS methods of handwriting" > 11 Common JS methods for handwriting</h2>
    <p><strong><a href=" " target="_ Blank "> common JS methods for handwriting < / a > < / strong ></p>
    <li>Judge data type</li>
    <li>Deep copy</li>
    <li>Is the object congruent</li>
    <li>Anti shake</li>
    <li>Array flattening</li>
    <li>Array de duplication</li>
    <li>New function</li>
    < H1 id = "tool" > tool</h1>
    <h2 id="1-git">1. Git</h2>
    <p><strong><a href=" " target="_ Blank "> git detailed tutorial < / a > < / strong ></p>
    <p><img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "></p>
    <p>< strong > common project commands: < / strong ></p>
    <pre><code><code>1. git init // Create a git code base in the current directory

    2. git branch dev-bing // Create local branch (DEV Bing)

    3. git checkout dev-bing // Switch to local branch (DEV Bing)
    Git checkout - B dev bind // create and switch to the local branch (DEV binding), which is equivalent to the abbreviation of the 2nd + 3rd above

    4. Git branch // view branches

    5. git push --set-upstream origin dev-bing // Upload the current local branch code to the master branch

    6. git status // The changed files are displayed. If the font is red, it means that all the files in the current directory that have not been managed by GIT and the files managed by GIT and modified but not submitted (GIT commit) are listed, that is, all the changed files.

    7. Git diff // view all modifications
    git diff test. Txt // view the modified contents of the specific file

    8. Git log // view the submitted log
    git log test. txt // View the record log of specific file submission

    9. Git stash // temporarily saved, cross branch (can only be used before adding)

    10. Git stash pop // cache before recovery

    11. git checkout . // (with a dot) undo all current modifications
    git checkout test. Txt // undo the modification of a specific file

    12. git add . // (with a dot) means to add all files and subdirectories in the current directory (or git add - a)
    git add test. Txt // add a specific file (test. Txt)

    13. Git commit - M 'test' // upload the file to the remote master branch and add the remark "test"

    14. Git pull origin dev Bing // download from the remote warehouse to the dev Bing warehouse
    Git pull // if the current branch is dev binding, GIT pull is equivalent to git pull origin dev binding

    15. Git push origin dev Bing // upload from local warehouse to remote warehouse (submit)

    16. Git checkout master. // switch to the master main branch 

    17. Git merge -- no FF dev Bing // merge the dev Bing branch into the master: WQ

    18. Git push origin master // submit the merged master branch
    Git push - U origin master // push the local master branch to the origin host, and specify origin as the default host. Then you can use git push without adding any parameters.
    Git push // after setting the default host (GIT push - U origin Master), it can be abbreviated

    19. Git checkout dev Bing // the dev Bing branch is returned
    < H2 id = "2-browser" > 2 Browser</h2>
    < H3 id = "the whole process of the browser from entering the URL to rendering the page" > < a href=“ " target="_ Blank "> the whole process of the browser from entering the URL to rendering the page</a></h3>
    <li>Get IP address</li>
    <li>TCP / IP triple handshake to establish connection</li>
    <li>The browser sends an HTTP request to the web server</li>
    <li>Browser rendering</li>
    <li>Four waves to disconnect</li>
    < H3 id = "browser render pass" > < a href=“ " target="_ Blank "> browser render pass</a></h3>
    <li>DOM tree: parsing HTML to build DOM (DOM tree)</li>
    <li>CSS tree: parsing CSS to build cssom (CSS tree)</li>
    <li>Render tree: cssom and DOM generate render tree together</li>
    <li>Layout: according to the render tree browser, you can know which nodes are in the web page and the relationship between each node and CSS, so as to know the location and geometric attributes (rearrangement) of each node</li>
    <li>Paint: paint the entire page (redraw) according to the calculated information</li>
    < H2 id = "3-other" > 3 Other</h2>
    <h3 id="yarn"><a href="" target="_blank">yarn</a></h3>
    <h3 id="gulp"><a href="" target="_blank">gulp</a></h3>
    <h3 id="babel"><a href="" target="_blank">babel</a></h3>
    <h3 id="vconsole"><a href="" target="_blank">vConsole</a></h3>
    <h1 id="vue">Vue</h1>
    <p><strong><a href=" " target="_ Blank "> Vue 3.0 super detailed introductory tutorial < / a > < / strong ></p>
    <h2 id="1-mvvm">1. MVVM</h2>
    <p><strong><a href=" " target="_ Blank "> understanding of MVVM < / a > < / strong ></p>
    <p>< strong > MVVM is divided into < code > model < / code >, < code > View < / code >, < code > ViewModel < / code >: < / strong ></p>
    <li>< code > model < / code >: < strong > data layer < / strong >, data and business logic are defined in the model layer</ li>
    <li>< code > View < / code >: < strong > the view layer < / strong >, that is, the user interface, is responsible for the display of data</ li>
    <li>< code > ViewModel < / code >: < strong > view data layer < / strong >, the ViewModel layer connects the view layer and the model layer through two-way data binding (< strong > bridge between view and model layer < / strong >), so that the synchronization of view layer and model layer is completely automatic. < br >
    <img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "> < br >
    Model and view are not directly related, but are connected through the bridge of ViewModel. ViewModel is the connector between view and model, and view and model realize two-way binding through ViewModel</ li>
    < H2 id = "2-lifecycle" > 2 Life cycle</h2>
    < H3 id = "vue2 lifecycle" > < a href=“ " target="_ Blank "> vue2 lifecycle</a></h3>
    <li>< strong > beforecreate: before creating < / strong > (< code > El < / code >, < code > Data < / code > and < code > message < / code > are still < code > undefined < / code >, which are not available)</li>
    <li>< strong > created: created < / strong > (the value of data < code > Data < / code > can be read, but < code > DOM < / code > has not been generated)</li>
    <li>< strong > beforemount: before mounting < / strong > (generate < code > DOM < / code >, but < code > {message}} < / code > has not mounted the data in < code > Data < / code >)</li>
    <li>< strong > mounted: Mount completed < / strong > (< code > {message} < / code > the value of rendering < code > Data < / code > has been successfully mounted)</li>
    <li>< strong > BeforeUpdate: before updating < / strong ></li>
    <li>< strong > updated: updated < / strong ></li>
    <li>< strong > beforedestroy: Before destruction < / strong ></li>
    <li>< strong > destroyed: destroyed < / strong > (untie the relationship between the instance and the view, and then modify the value of < code > message < / code >, and the view will not be updated again)</li>
    <li>Activated: < code > keep alive < / code > called when the component is activated</li>
    <li>Deactivated: < code > keep alive < / code > called when the component is deactivated</li>
    <li>< code > activated < / code > and < code > deactivated < / code > are two special hooks, which need to be used together with < code > keep live < / code ></li>
    <li>When < code > keep alive < / code > is introduced, the page enters for the first time, the trigger sequence of the hook is < code > created < / code > = > < code > mounted < / code > = > < code > activated < / code >, and < code > deactivated < / code > is triggered when exiting. When entering (forward or backward) again, only < code > activated < / code > is triggered</li>
    < H3 id = "vue3 lifecycle" > < a href=“ " target="_ Blank "> vue3 lifecycle</a></h3>
    < H2 id = "3-computed - and - Watch" > 3 Computed and watch</h2>
    <p><strong><a href=" " target="_ Blank "> calculated and watch in Vue < / a > < / strong ></p>
    < H3 id = "computed" > computed</h3>
    <li>The < strong > result of the attribute will be cached (by default) < / strong >. When the attribute on which the function in < code > calculated < / code > depends has not changed, the result will be read from the cache when calling the current function, and will be recalculated unless the dependent responsive attribute changes</li>
    <li>< strong > asynchronous < / strong > is not supported. When there are asynchronous operations in < code > computed < / code >, it is invalid and cannot monitor data changes</ li>
    <li>The function < strong > in < code > computed < / code > must return the < / strong > final result with < code > return < / code >< Code > computed < / code > is more efficient and gives priority to use</ li>
    <li>< strong > when an attribute is affected by multiple attributes, generally use < code > calculated < / code > < / strong > (for example, detailed address = province + city + District + street + building + house number)</li>
    < H3 id = "watch" > Watch</h3>
    <li>< strong > caching < / strong > is not supported. If the data changes, the corresponding operation will be triggered directly</ li>
    <li>< strong > support asynchronous < / strong ></ li>
    <li>The listening function receives two parameters. The first parameter is the latest value (newval); The second parameter is the value before input (oldval)</ li>
    <li>< strong > when one piece of data affects multiple pieces of data, generally use < code > watch < / code > < / strong > (for example, search data (asynchronous) to trigger a series of data changes)</ li>
    < H2 id = "4-v-if - and - v-show" > 4 V-IF and v-show</h2>
    <h3 id="v-if">v-if</h3>
    <li>It controls the explicit and implicit of DOM elements by controlling the existence of DOM elements</ li>
    <li>< strong > during switching, you create and destroy DOM elements < / strong ></ li>
    <li>It is < strong > inert < / strong >. If the initial condition is false, nothing will be done; Local compilation starts only when the condition first becomes true</ li>
    <li>Higher switching consumption</ li>
    <h3 id="v-show">v-show</h3>
    <li>By setting the < code > display < / code > style of DOM elements, < code > block < / code > is displayed and < code > none < / code > is hidden</ li>
    <li>< strong > when switching, simply switch based on CSS < / strong ></ li>
    <li>It is compiled under any condition (whether the first condition is true or not) and then cached, and the DOM elements are retained</li>
    <li>Higher initial rendering consumption</ li>
    <p>Based on the above differences, < strong > if you need to switch very frequently, it is better to use < code > v-show < / code > < / strong >< Strong > if the conditions rarely change at run time, it is better to use < code > V-IF < / code > < / strong ></ p>
    < H2 id = "5-data - must be a function, not an object" > 5 Data must be a function, not an object</h2>
    <p>If the data in the Vue component is an object, just like all places that reuse the component are using the only data in the component, the data in all places that use the component will point to the address of this data in the stack, which will cause a change in the value of data and the data of all other components will be changed</ p>
    <p>If an object is returned in a function, each time a component is created, a new object (object instance) will be returned, and a space will be opened up in memory to store data for the current component. In this way, the phenomenon of sharing one data will not occur</p>
    < H2 id = "6-diff algorithm" > 6 Diff algorithm</h2>
    <p><strong><a href=" " target="_ Blank "> diff algorithm in Vue < / a > < / strong ></p>
    <p>Diff algorithm is an optimization method. For example, sometimes when we modify some data, if we directly render it to the real DOM, it will cause the redrawing and rearrangement of the whole DOM tree, which is very expensive</ p>
    <p>We can first generate a virtual DOM tree based on the real dom. When the data of a node in the virtual DOM changes, a new < code > vnode < / code > will be generated (virtual node). Then, compare < code > vnode < / code > with < code > oldvnode < / code >, and if there is any difference, directly modify it on the real DOM, and then make the value of < code > oldvnode < / code > as < code > vnode < / code >. At this time, we only update the small DOM we modified, not the whole dom</p>
    <p>The diff process is to call the patch function, compare the old and new nodes, and patch the real DOM while comparing< br>
    < strong > when diff algorithm is used to compare old and new nodes, the comparison will only be conducted at the same level, not cross level</ strong><br>
    <img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "> < br >
    To sum up, compare the nodes of the same layer of the DOM tree before and after the operation, compare layer by layer, and then insert it into the real DOM to re render</ p>
    < H2 id = "7-for-key-role in loop" > 7 Role of key in for loop</h2>
    <p>The list cycle in Vue needs to add < code >: key = "unique ID" < / code >, and the unique ID can be < code > ID < / code >, < code > index < / code >, etc</ p>
    <li>Key is mainly used to more efficiently compare whether each node in the virtual DOM is the same node</ li>
    <li>Vue judges whether two nodes are the same node during the patch process. Key is a necessary condition. When rendering a group of lists, the key is often the unique identifier. Therefore, if the key is not defined, Vue can only think that the two nodes compared are the same, even if they are not. This leads to frequent updating of elements, making the whole patch process inefficient, Affect performance</ li>
    <li>It can be seen from the source code that Vue judges whether the two nodes are the same, mainly judging their key and element type. Therefore, if the key is not set and its value is undefined, it may always be considered that these two nodes are the same and can only be updated, resulting in a large number of DOM update operations, which is obviously undesirable</ li>
    <p>It is not recommended to use < code > index < / code > as < code > key < / code >, which is basically the same as not writing, because no matter how you reverse the order of the array, < code > index < / code > is arranged in such a way that 0, 1 and 2, resulting in Vue reusing the wrong old child nodes and doing a lot of extra work</p>
    < H2 id = "8-bidirectional binding" > 8 Bidirectional binding</h2>
    <p>When a Vue instance is created, Vue will traverse the attributes of the data option, using < strong > < code > object Defineproperty < / code > < / strong > convert them to < code > getter / setter < / code > and track relevant dependencies internally to notify changes when properties are accessed and modified. Each component instance has a corresponding < code > watcher < / code > program instance. It will record the attribute as a dependency during component rendering. Then, when the < code > setter < / code > of the dependency is called, it will notify the < code > watcher < / code > to recalculate, so that its associated components can be updated</ p>
    <p><img src=" -oss-process=image/watermark,type_ ZmFuZ3poZW5naGVpdGk,shadow_ 10,text_ aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3g1NTAzOTIyMzY=,size_ 16,color_ FFFFFF,t_ 70#pic_ Center "ALT =" insert picture description here "loading =" lazy "> < br >
    Minimalist bidirectional binding:</p>
    <pre><code><code><input type="text" id="input" value="">
    <span id="span"></span>
    let obj = {}
    Object. Defineproperty (obj, 'text', {// listen for obj's text property
    set(newVal = '') {
    document.getElementById('input').value = newVal;
    document.getElementById('span').innerHTML = newVal;

    document.addEventListener('keyup', function (e) {
    obj.text =;

    Bidirectional binding in Vue is an instruction V-model, which can bind a dynamic value to the view, and changes in the view can change the value.
    V-model is a syntax sugar. By default, it is related to: value and @ input:


    export default {
    name: 'App',
    data() {
    return {
    username: ''

    9. Communication of components

    Vue component communication summary
    Pass values from parent component to child component (props)

    var a = new Vue({
    components: {
    //Subcomponent < test >
    props: ['ss'], // 2. Receive data from parent component

    Child component passes value to parent component ($emit)

    {{ total }}

    Vue.component('button-counter', {
    Template: '< button @ Click = "increment" > {counter} < / button >' // step 1
    data: function () {
    return {
    Counter: 'data of sub components'
    methods: {
    increment: function () {
    //Define a custom event increment through $emit and pass in this Counter parameter, thrown externally
    this.$ emit('increment', this.counter); // Step 2

    new Vue({
    el: '#app',
    data: {
    Total: 'data of parent component:'
    methods: {
    //Can receive the data transmitted by the sub component (E)
    Incrementtotal: function (E) {// step 4 = + e[0]

    Sibling component value transfer (eventbus)

    Create a new event bus JS file

    // event-bus.js
    import Vue from 'vue'
    export const EventBus = new Vue();

    A page sending data


    import { EventBus } from "../event-bus.js";
    export default {
    methods: {
    sendMsg() {
    EventBus.$ Emit ("amsg", 'message from page a')// Send data externally

    B page receiving data


    import { EventBus } from "../event-bus.js";
    export default {
    data() {
    return {
    msg: ''
    mounted() {
    EventBus.$ On ("amsg", (MSG) = > {// receive the message sent by a
    this.msg = msg;

    Remove event listener

    import { EventBus } from "../event-bus.js";
    EventBus.$ off('aMsg', {}); // Remove all listeners for this event in the application
    EventBus.$ off(); // Remove all event listeners

    Detailed explanation of vuex

    State: defines the data structure of the application state. You can set the default initial state here.
    Getter: it can be considered as the calculation attribute of the store (there is a cache, and it will be recalculated only when its dependency value changes).
    Mutation: is the only way to change the state in the store, and must be a synchronization function.
    Action: it is used to submit a mutation (and then change the state in the store) instead of directly changing the state. It can include any asynchronous operation.
    Module: the store can be divided into modules. Each module has its own state, mutation, action, getter, and even nested sub modules

    Basic usage:
    //Create a store
    const store = new Vuex.Store({
    //State stores the status of the application tier
    state: {
    Count: 5 // pass in the component$ store. state. count; obtain
    getters: {
    newCount: state => state. Count * 3 // pass this. In the component$ store. getters. newCount; obtain
    //Changes is the only way to modify data in a state
    mutations: {
    increment(state, value) {
    state. count += value; // Component through this$ store. commit("increment", 'hello'); modify
    actions: {
    getParamSync(store, value) {
    //Handling asynchronous operations
    setTimeout(() => {
    store. commit('increment', value); // Component through this$ store. dispatch('getParamSync','hi'); modify
    }, 1000);

    Module usage
    const moduleA = {
    state: () => ({ ... }),
    mutations: { ... },
    actions: { ... },
    getters: { ... }

    const moduleB = {
    state: () => ({ ... }),
    mutations: { ... },
    actions: { ... }

    const store = new Vuex.Store({
    modules: {
    a: moduleA,
    b: moduleB

    store. state. A // - > module a status
    store. state. B // - > status of moduleb

    10. Routing

    Vue route navigation router link and router push
    1. No parameters are carried
    to login
    to login

    to login

    //Named route
    to login

    2. Carry parameters through query:

    The address bar becomes / login? color=red
    You can use {{$route. Query. Color}} or this$ route. query. Color get parameters

    to login

    to login

    3. Carry parameters through params:

    The address bar becomes / login / red
    You can use {{$route. Params. Color}} or this$ route. params. Color get parameters

    //Unable to get parameters
    //Path "/ login" was passed with params but they will be ignored. Use a named route along side params instead
    to login

    //Via {{$route. Params. Color}} or this$ route. params. Color gets the parameter.
    to login

    The router JS needs to set path: '/ login /: color?'
    // router.js

    var router = new Router({
    routes: [{
    path: '/login/:color?', // : color? => ? The question mark means that the parameter is not mandatory and no error will be reported if it is not passed
    name: 'Login',
    component: Login

    1. No parameters are carried


    //Named route
    router.push({name: 'Login'})

    2. Carry parameters through query:
    // You can use {{$route. Query. Color}} or this$ route. query. Color get parameters
    router.push({path: '/login', query: {color: 'red' }})

    // You can use {{$route. Query. Color}} or this$ route. query. Color get parameters
    router.push({name: 'Login', query: {color: 'red' }})

    3. Carry parameters through params:
    //Unable to get parameters
    router.push({path:'/login', params:{ color: 'red' }})

    //Via {{$route. Params. Color}} or this$ route. params. Color gets the parameter.
    router.push({name:'Login', params:{ color: 'red' }})

    The difference between $router and $route

    $Router: refers to the entire routing instance. You can control the entire route. The usage is as follows: this$ router. go(-1); // Jump forward or backward to N pages. N can be a positive integer or a negative integer
    this.$ router. push('/'); // Jump to the specified URL path, there will be a record in the history stack, and click return to jump to the previous page
    this.$ router. replace('/'); // Jump to the specified URL path, but there will be no record in the history stack. Clicking return will jump to the previous page

    $route: refers to the route object to which the current route instance $route jumps; A routing instance can contain multiple routing objects, which are parent-child relationships. // get the parameters passed from the route

    router. JS (including route lazy loading and route authentication)
    router. JS related configuration
    import Vue from 'vue'
    import Router from 'vue-router'
    import { getStore } from 'js/store'


    var router = new Router({
    routes: [
    path: '*',
    redirect: '/'
    path: '/',
    name: '/',
    Component: () = > Import ('. / views / index. Vue'), // Vue route lazy loading asynchronous loading
    meta: {
    Title: 'home page',
    Requireauth: false // this field is false. Authentication is not required
    path: '/test',
    name: 'test',
    Component: () = > Import ('. / views / test. Vue'), // Vue route lazy loading asynchronous loading
    meta: {
    title: 'test',
    Requireauth: true // as long as this field is true, authentication must be performed
    path: '/login',
    name: 'login',
    Component: () = > Import ('. / views / login. Vue'), // Vue route lazy loading asynchronous loading
    meta: {
    Nonav: true // no NAV is displayed

    let indexScrollTop = 0;

    router.beforeEach((to, from, next) => {
    //Route authentication: there is a requireauth field in the route meta object. As long as this field is true, authentication must be performed
    if (to.matched.some(res => res.meta.requireAuth)) {
    const token = getStore({ name: 'access_token', type: "string" });// Get access in localstorage_ token
    //Before the route enters the next route object, judge whether to log in
    if (!token) {
    //Not logged in
    path: '/login',
    query: {
    redirect: to. Path // take the jump route path as the parameter. Log in successfully and then jump to the route
    } else {
    //Whether the user information has expired
    let overdueTime = token.overdueTime;
    let nowTime = +new Date();
    //Login expired and not expired
    if (nowTime > overdueTime) {
    //For the processing of login expiration, you can process it as needed and then execute the following methods to log in to the page
    //I didn't deal with anything else here. I went directly to the login page
    path: '/login',
    query: {
    redirect: to.path
    } else {
    } else {
    if (to.path !== '/') {
    //Record the current scroll position
    indexScrollTop = document.body.scrollTop
    document.title = to.meta.title || document.title

    router.afterEach(route => {
    if (route.path !== '/') {
    document.body.scrollTop = 0
    } else {
    Vue.nextTick(() => {
    //Return to the previous scroll position
    document.body.scrollTop = indexScrollTop

    export default router;

    Different ways to write route lazy loading:

    Lazy loading of webpack < version 2.4 (vue-cli2)

    const Index = resolve => require(['./views/Index.vue'], resolve);

    Lazy loading of webpack > version 2.4 (vue-cli3)

    const Index = () => import('./views/Index.vue');

    11. Others

    Composition API in vue3
    Encapsulation of Axios in Vue (including interceptor)

Recommended Today

Big data Hadoop — spark SQL + spark streaming

catalogue 1、 Spark SQL overview 2、 Sparksql version 1) Evolution of sparksql 2) Comparison between shark and sparksql 3)SparkSession 3、 RDD, dataframes and dataset 1) Relationship between the three 1)RDD 1. Core concept 2. RDD simple operation 3、RDD API 1)Transformation 2)Action 4. Actual operation 2)DataFrames 1. DSL style syntax operation 1) Dataframe creation 2. SQL […]