Record the interview questions and answers you have recently encountered when changing jobs

The CSS part

The box model

Question: Say something about the CSS box model

Box model is divided into standard model and weird box model (IE box model)

Standard box model: The width and height of the box model are simply the width and height of the content

Weird box model: The width of the box model is the total width of the content + padding + border

Question: How does CSS set up the two models

/ / box-sizing:content-box; /* box-sizing:border-box;Copy the code

Question: Have you ever encountered margin overlap? How to solve the problem as shown in the figure below

To solve this problem, use BFC, which is described in detail below

Reference code: Take advantage of the BFC features to put another box into another independent BFC, so that the two boxes do not affect each other

<section class="top">
    <h1>上</h1>
    margin-bottom:30px;
</section>
<div style="overflow: hidden;">
    <section class="bottom">
    <h1>下</h1>
    margin-top:50px;
    </section>
</div>
Copy the code

BFC

Question: Talk about BFC

  1. What is landing

    Block Formatting Context (BFC) is a CSS rendering mode for the layout of a box model in a Web page. It refers to an independent rendering area or an isolated independent container.

  2. Conditions for the formation of BFC

    • Float element, float a value other than None
    • Position element, position (Absolute, fixed)
    • Display is one of the following inline-block, table-cell, table-caption values
    • Overflow values other than visible (hidden, auto, scroll)
  3. The characteristics of landing

    • The internal boxes will be placed one after the other vertically.
    • The vertical distance is determined by margin
    • The region of the BFC does not overlap with the element region of float.
    • When calculating the height of the BFC, floating elements are also involved
    • A BFC is a separate container on the page, and the child elements inside the container do not affect the outside elements.

Rem principle

The essence of the REM layout is proportional scaling, generally based on width. Suppose the screen width is divided into 100 parts, each width is 1rem, and the width of 1REM is the width of the screen /100, and then the child element sets the properties of the REM unit

By changing the font size of the HTML element, you can set the actual size of the child element.

Better solution than REM (disadvantages not compatible)

Vw (1vw is 1% of the viewport width, 100vw is the viewport width), VH (100vh is the viewport height)

Achieve a three-column layout

(Fixed width on both sides, adaptive in the middle)

Here are five implementations:

  1. Flex implementation
/* css */
.box {
    display: flex;
    justify-content: center;
    height: 200px;
}
.left {
    width: 200px;
    background-color: red;
    height: 100%;
}
.content {
    background-color: yellow;
    flex: 1;
}
.right {
    width: 200px;
    background-color: green;
}

/* html */
<div class="box">
    <div class="left"></div>
    <div class="content"></div>
    <div class="right"></div>
</div>
Copy the code
  1. Float mode, where the content must be at the bottom
/* css */
.box {
      height: 200px;
    }
.left {
    width: 200px;
    background-color: red;
    float: left;
    height: 100%;
}
.content {
    background-color: yellow;
    height: 100%;
}
.right {
    width: 200px;
    background-color: green;
    float: right;
    height: 100%;
}

/* html */
<div class="box">
    <div class="left"></div>
    <div class="right"></div>
    <div class="content"></div>
</div>
Copy the code
  1. Absolute positioning way to achieve
/* css */
.box {
    position: relative;
    height: 200px;
}
.left {
    width: 200px;
    background-color: red;
    left: 0;
    height: 100%;
    position: absolute;
}
.content {
    background-color: yellow;
    left: 200px;
    right: 200px;
    height: 100%;
    position: absolute;
}
.right {
    width: 200px;
    background-color: green;
    right: 0;
    height: 100%;
    position: absolute;
}

/* html */
<div class="box">
    <div class="left"></div>
    <div class="content"></div>
    <div class="right"></div>
</div>
Copy the code
  1. Table layout implementation
/* css */
.box {
    display: table;
    height: 200px;
}
.left {
    width: 200px;
    background-color: red;
    height: 100%;
    display: table-cell;
}
.content {
    background-color: yellow;
    height: 100%;
    display: table-cell;
}
.right {
    width: 200px;
    background-color: green;
    height: 100%;
    display: table-cell;
}

/* html */
<div class="box">
    <div class="left"></div>
    <div class="content"></div>
    <div class="right"></div>
</div>
Copy the code
  1. Grid layout
/* css */
.box {
    display: grid;
    grid-template-columns: 200px auto 200px;
    grid-template-rows: 200px;
}
.left {
    background-color: red;
}
.content {
    background-color: yellow;
}
.right {
    background-color: green;
}

/* html */
<div class="box">
    <div class="left"></div>
    <div class="content"></div>
    <div class="right"></div>
</div>
Copy the code

Center a box horizontally and vertically

Here are five implementations:

  1. The width and height are known
/* css */
#box{
    width: 400px;
    height: 200px;
    position: relative;
    background: red;
}
#box1{
    width: 200px;
    height: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -50px;
    background: green;
}
/* html */
<div id="box">
    <div id="box1">

    </div>
</div>
Copy the code
  1. The width and height are unknown
/* css */
 #box{
    width: 800px;
    height: 400px;
    position: relative;
    background: red;
}
#box1{
    width: 100px;
    height: 50px;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    background: green;
}
/* html */
<div id="box">
    <div id="box1">

    </div>
</div>
Copy the code
  1. Flex layout
/* css */
#box{
    width: 400px;
    height: 200px;
    background: #f99;display: flex; justify-content: center; Align -items: center; // Implement vertical center}#box1{
    width: 200px;
    height: 100px;
    background: green;
}
/* html */
<div id="box">
    <div id="box1">

    </div>
</div>
Copy the code
  1. Translation positioning + Transform
/* css */
#box{
    width: 400px;
    height: 200px;
    background: red;
    position: relative;
}
#box1{
    width: 200px;
    height: 100px;
    background: #9ff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
/* html */
<div id="box">
    <div id="box1">

    </div>
</div>
Copy the code
  1. Table – cell layout
/* css */
#box{
    display: table-cell;
    vertical-align: middle
}
#box1{
    margin: 0 auto;
}
/* html */
<div id="box">
    <div id="box1">

    </div>
</div>
Copy the code

Js part

What is a closure and what does a closure do

A function that can read variables inside other functions, or is simply defined inside a function that holds references to variables inside the external function.

Closures are useful for:

  • Reads variables inside other functions
  • Keep the value of a variable always in memory
  • JavaScript applications of closures all have the keyword return, and this is because, to quote from JavaScript’s secret garden:

Closures are a very important feature of JavaScript, which means that the current scope can always access variables in the outer scope. Because functions are the only structures in JavaScript that have their own scope, closure creation depends on functions.

Call, apply, bind How to implement the call,apply method

Similarities:

  1. Both are used to change the orientation of the function’s this object.
  2. The first argument is always the object to which this refers.
  3. Can be passed by subsequent parameters. The difference between:
  4. Fn. Call (this, 1, 2, 3)
  5. Fn. apply(this,[1, 2, 3])
  6. Bind returns a new function that needs to be called again: fn.bind(this)(1, 2, 3)

Implement the call method manually:

Function.prototype.myCall = function(context = window, ... rest) { context.fn = this; // This refers to the myCallfunction
    letresult = context.fn(... rest); // Add this to delete context.fn;return result;
};
Copy the code

Implement the Apply method manually:

Function.prototype.myCall = function(context = window, params = []) { context.fn = this; // This refers to the myCallfunction
    let result
    if(params.length) { result = context.fn(... params) }else{result = context.fn()} // Add this to delete context.fn;return result;
};
Copy the code

Manually implement the bind method:

Function.prototype.myBind = function(oThis, ... rest) {let _this = this;
    let F = function() {} // According tobindSpecifies if the new operator is used to constructbindThe first argument bound to this is invalidatedlet resFn = function(... parmas) {return_this.apply(this instanceof resFn ? this : oThis, [ ...rest, ...parmas ]); }; // Inherit the prototypeif (this.prototype) {
        F.prototype = this.prototype;
        resFn.prototype = new F;
    }
    return resFn;
};
Copy the code

What about prototypes and prototype chains

Each function has a prototype

Every object has a __proto__

The instance’s __proto__ points to the constructor’s prototype

Object. Prototype: __proto__ -> ptototype: __proto__ -> ptototype: __proto__ -> ptototype: __proto__ -> ptototype: Object. Prototype: __proto__ -> ptototype: Object

Several ways of js inheritance

Common inheritance: combination inheritance, parasitic combination inheritance

Composite inheritance: Inherits properties from the parent class using call, and inherits methods from the parent class using the child’s prototype equal to the parent class instance

Disadvantages: Call the parent class twice, resulting in wasted performance

function Parent(name) {
    this.name = name;
}

Parent.prototype.say = function() {
    console.log(this.name);
};
function Child(name) {
    Parent.call(this, name)
}
Child.prototype = new Parent;
let c = new Child("YaoChangTuiQueDuan");
c.say()
Copy the code

Parasitic combinatorial inheritance: Use call to inherit properties from the parent class, use a clean function prototype to equal the parent class prototype, and use a subclass prototype to equal the clean function instance

function Parent(name) {
    this.name = name;
}

Parent.prototype.say = function() {
    console.log(this.name);
};

function ExtendMiddle() {}

function Child(name) {
    Parent.call(this, name)
}

ExtendMiddle.prototype = Parent.prototype;
Child.prototype = new ExtendMiddle

let c = new Child("YaoChangTuiQueDuan");
c.say()
Copy the code

eventloop

Eventloop isn’t scary. It’s meeting promises

What does the process of new do? Implement a new manually

  1. The freshman became an object
  2. Link to the prototype
  3. Binding this
  4. Return a new object
functioncreate(... Rest) {// Create an empty objectletObj = new Object() // Get constructorletCon = rest.shift() // Link to the prototype obj.__proto__ = con.prototype // bind this, execute the constructorletResult = con.apply (obj, arguments) // Make sure new comes out as an objectreturn typeof result === 'object' ? result : obj
}
Copy the code

Talk about some common ES6’s

  • let/const
  • Template string
  • Deconstruction assignment
  • Block-level scope
  • Promise
  • Class
  • Function default arguments
  • modular
  • Arrow function
  • Set
  • Map
  • Array.map
  • , etc.

The basic use and principle of Promise, as well as a simple version of the Promise implementation

Several features of Promise:

  1. A Promise catches an error the same as a try/catch
  2. Promises have state changes that are irreversible
  3. Promises are microtasks
  4. The.then callback in the Promise is asynchronous
  5. Promsie. Then returns a new Promise each time
  6. Promise stores the return value

Simple implementation of Promise:

class MyPromise {
    constructor(fn) {
        this.resolvedCallbacks = [];
        this.rejectedCallbacks = [];
        this.state = "PADDING";
        this.value = "";
        fn(this.resolve.bind(this), this.reject.bind(this));
    }
    resolve(value) {
        if (this.state === "PADDING") {
            this.state = "RESOLVED";
            this.value = value;
            this.resolvedCallbacks.forEach(cb => cb());
        }
    }

    reject(value) {
        if (this.state === "PADDING") {
            this.state = "REJECTED"; this.value = value; this.rejectedCallbacks.forEach(cb => cb()); }}then(resolve = function() {}, reject = function() {}) {
        if (this.state === "PADDING") {
            this.resolvedCallbacks.push(resolve);
            this.rejectedCallbacks.push(reject);
        }
        if (this.state === "RESOLVED") {
            resolve(this.value);
        }
        if (this.state === "REJECTED") { reject(this.value); }}}Copy the code

Have you used async/await to say the difference and connection with Promise

  1. Promise is used, not in conflict with Promise
  2. It is written completely synchronously without any callbacks
  3. Await must be used in async functions
  4. If the method behind await is a Promise, it returns the result of the Promise processing and waits for the Promise processing to succeed before executing the code below. If it is not waiting for a Promise object, it returns the value itself and synchronously executes the code below
  5. The code written after await is equivalent to executing promise.resolve ()
  6. Use try/catch to catch errors

How to implement for on Object… Of the iterator

You can mount a symbol. iterator method on Object’s prototype that returns an Object containing the next method, which also returns an Object containing value and done. Done indicates whether the iteration is completed. If it is false, the iteration will continue. If it is true, the iteration is completed and the iteration will stop

Object.prototype[Symbol.iterator] = function () {
  let values = Object.values(this);
  let keys = Object.keys(this);
  let len = 0;
  return {
    next() {
      return {
        value: {
          value: values[len],
          key: keys[len++]
        },
        done: len > values.length
      }
    }
  }
}
Copy the code

The difference between CommonJS and modularity in ES6

  1. The former supports dynamic import, namely require(${path}/xx.js), which is not currently supported, but has been proposed
  2. The former is synchronous import, because for the server, the files are local, synchronous import even if the main thread is blocked. While the latter is asynchronous import, because for the browser, need to download the file, if also adopted synchronous import will have a great impact on rendering
  3. If the exported value is changed, the imported value will not change. Therefore, if you want to update the value, you must import it again. However, the latter uses real-time binding. The imported and exported values point to the same memory address, so the imported value changes with the exported value
  4. The latter will be compiled into require/exports

Module. exports and exports

For convenience, Node provides an exports variable for each module pointing to module.exports, which is a reference to the module.exports address

Exports = {}, exports = {}, exports = {}, exports = {}, exports = {}, exports = {}, exports = {}, exports = {}, exports = {}, exports = {

What is anti-shake and throttling? What’s the difference?

  • Controls the frequency of invocation of frequently invoked events
  • The purpose of both stabilization and throttling is to prevent multiple calls to the function.
  • The difference is that, if a user fires the function all the time, at intervals shorter than wait, the function will be called once in the case of stabilization, whereas the function will be called at intervals (wait) in the case of throttling.

What problem does deep copy solve? How to implement

In simple terms, it is assumed that B copies A and changes A to see if B changes. If B also changes, it is A shallow copy. If B does not change, it is A deep copy.

Js is divided into two types of variable types, basic data type and reference data type. Basic data types include number, String, Boolean, NULL, undefined and symbol.

Reference data types (Object classes) unordered objects {a:1}, arrays [1,2,3], functions, etc.

The two types of data stores look like this:

  • Basic types — names and values are stored in stack memory, such as let a=1;

    When you copy b=a, the stack will create a new memory, for example:

    Therefore, if you change a=2, it does not affect B, because B has changed its memory address and is not affected by A

  • Reference data type — the name is in stack memory, the value is in heap memory, but the stack memory provides a reference address to the value in heap memory

    When b=a is copied, it is actually copying the reference address of A, not the value in the heap.

    When a[0]=1, we modify the array, because a and B point to the same address, so naturally B is affected, this is called shallow copy.

    Then, if we want to achieve the effect of deep copy, we need to create a new memory space in the heap to hold the value of B, as shown in the figure below:

Deep copy implementation:

  1. json.parse & json.stringify

    Start by turning an object into a JSON object. The JSON object is then parsed, but this approach has several drawbacks:

    • If obj has a time object in it, after serialization, the time is just a string, not a time object
    • If there are RegExp and Error objects in obj, the serialized result will be empty
    • If obj has a function called undefined, the result of serialization will lose the function or undefined
    • If ob j contains NaN, Infinity, and -infinity, the serialized result becomes NULL
    • Only the enumerable properties of an object can be serialized; if an object in OBj is generated by a constructor, the object’s constructor is discarded after serialization
    • Deep copy cannot be correctly implemented if there are circular references in the object
  2. Deep copy is implemented recursively (ps: this is only a simple version, the full version is recommended to see the source code of Lodash cloneDeep method)

Source code address: github.com/lodash/loda…

function deepClone(obj) {
    let objClone = Array.isArray(obj) ? [] : {};
    let toString = Object.prototype.toString;
    for (key in obj) {
        if(obj.hasownProperty (key)) {// Determine whether the oJB child is an object, and if so, copy recursivelyif ( toString.call(obj[key]) === "[object Object]" || toString.call(obj[key]) === "[object Array]" ) {
                objClone[key] = deepClone(obj[key]);
            } else{// If not, simply copy objClone[key] = obj[key]; }}}return objClone;
}
Copy the code

What is a heap and what is a stack

Stack: The stack will automatically allocate memory space, will automatically free, to store basic types, simple data segments, occupy a fixed amount of space. Heap: dynamically allocated memory that varies in size and is not automatically released, storing reference types

Why is there stack memory and heap memory?

Usually related to garbage collection mechanisms. To minimize the memory footprint of the program when it runs.

When a method is executed, each method creates its own stack. Variables defined in the method are added to the stack one by one, and the method’s stack is destroyed as the method completes execution. Therefore, all variables defined in a method are placed in stack memory;

When we create an object in a program, the object is stored in the runtime data area for reuse (because objects are usually expensive to create), and this runtime data area is heap memory. Will not end with the method of objects in the heap memory and destruction, even after the method, the object may also be another reference variables referenced (method of parameter passing is common), then the object is not destroyed, only when there is no reference to an object variables refer to it, the system of garbage collection will check the recycling it.

Insert tens of thousands of DOM, how to achieve page free lag?

Solution a:

Paging, lazy loading, paging the data, and then receiving a certain amount of data at a time, to avoid receiving too much at onceCopy the code

Scheme 2:

SetInterval, setTimeout, requestAnimationFrame render in batches, allowing data to be rendered in different framesCopy the code

Solution 3:

Use virtual-Scroll.

Instead of rendering the long list in its entirety, it displays a portion of the long list data based on the height of the container element and the height of the list item element to improve the performance of infinite scrolling

Virtual – scroll principle:

Changes the rendering portion of the list in the viewable area as the user scrolls

  • StartIndex to calculate the start data of the current visible region
  • Computes the endIndex of the current visible region end data
  • Calculates the data for the current visible area and renders it to the page
  • Calculate the startIndex data offset startOffset in the entire list and set it to the list
  • Calculate endOffset, the offset position of endIndex data relative to the bottom of scrollable area, and set it to the list

As shown below:

StartOffset and endOffset will stretch the height of the contents of the container elements so that they can be rolled continuously; In addition, it keeps the scrollbar in the correct position.

What do you know about optimization?

  1. Reduce HTTP requests: use iconfont font ICONS, use Sprite diagrams, merge JS, merge CSS
  2. Reducing DNS queries
  3. Place CSS at the top of the page and JS at the bottom
  4. Compress JS and CSS: reduce file size, remove unnecessary whitespace, formatting, comments, remove duplicate, useless code, use gzip
  5. Using browser caching
  6. Avoid deep nesting of the CSS selector hierarchy
  7. High frequency trigger events use anti-shake and throttling
  8. Make Ajax cacheable
  9. Use the CDN
  10. Keep replenishing…

The browser

Enter the URL in the browser’s address bar and press Enter to go through the following process:

  1. Parse url to DNS server
  2. The DNS server returns the IP address to the browser
  3. Follow protocol to send IP to the network
  4. The server is reached over the LAN
  5. Go to the MVC architecture Controller of the server
  6. The logic is processed, the request is distributed, and the Model layer is invoked
  7. The Model interacts with the data, reads the database, and sends the final result back to the web via the View layer back to the browser
  8. The browser renders the requested HTML and associated CSS and JS
  9. During rendering, the browser generates a DOM tree from HTML and a CSS tree from CSS
  10. Dom tree and CSS tree integration, finally know the DOM node style, style rendering on the page
  11. The browser executes the JS script
  12. Final display page

The process of browser rendering can be roughly divided into five steps:

  1. The HTML code is converted to the DOM
  2. The CSS code is converted to CSSOM
  3. Combine DOM and CSSOM to generate a render tree
  4. To generate a layout, all nodes of the rendered tree are composed in a plane
  5. Draw the layout on the screen

Browser cache

When the browser accesses an already accessed resource again, it does this:

  1. See if the strong cache is hit, and if so, use the cache directly.
  2. If the strong cache is not hit, a request is sent to the server to check for a hit to the negotiation cache.
  3. If the negotiated cache is hit, the server returns 304 telling the browser to use the local cache.
  4. Otherwise, request the network to return the latest resource.

Browser cache location:

  1. Service Worker: It gives us freedom to control which files are cached, how the cache is matched, how the cache is read, and the cache is persistent.
  2. Memory Cache: Memory Cache, which reads data from Memory faster than disk. However, the memory cache, although read efficiently, has a short cache duration and will be released as the process is released. Once we close the Tab page, the cache in memory is freed.
  3. Disk Cache: A Disk Cache is a Cache stored on a hard Disk. It is slower to read, but everything can be stored on Disk. It is larger and more efficient than Memory Cache.

Implementation of caching: Both strong caching and negotiated caching are implemented based on HTTP headers

What is redraw and reflow

Backflow: Layout or geometry properties that need to be changed are called backflow. Redraw: When a node needs to change its appearance without affecting its layout, such as changing its color, it is redrawn

The difference between:

Backflow will certainly cause redrawing, and redrawing will not necessarily cause backflow. For example, when only the color changes, redrawing will occur without backflow. When the layout and geometry of the page change, backflow will be required

For example, visible DOM elements are added or removed, element positions change, element dimensions change — margins, padding, borders, widths, and heights — and content changes

vue&react

The way the MVVM

MVVM is bidirectional data binding

  • M: Model data layer
  • V: View View layer
  • VM: The bridge between the view layer and the data layer, the bridge between the view layer and the data layer communication

The View layer binds the Model layer through events, and the Model layer binds the View layer through data

What is the Virtual DOM and why is it used

Before, when rendering data, all elements in DOM would be directly replaced with new data. In order to waste performance caused by rendering useless DOM, Virtual DOM emerged. Virtual DOM is a Virtual DOM, which is a tree structure represented by JS objects. Attribute mapping in DOM to JS object attribute, its core definition is nothing more than a few key attributes, tag name, data, child node, key value and so on. When the data changes, re-render the js object structure to find the DOM nodes that really need to be updated, and then render the real DOM. The Virtual DOM is essentially a cache between JS and DOM

Why are there performance issues with the real DOM

Because DOM is something that belongs in the rendering engine, and JS is something that belongs in the JS engine. When we manipulate the DOM through JS, which actually involves communication between two threads, there is bound to be some performance loss. Manipulating the DOM more than once means that threads are communicating with each other all the time, and manipulating the DOM can cause redraw backflow, which can lead to performance issues.

The responsive principle of Vue

Vue internally uses Object.defineProperty() for data responsiveness, which listens for set and GET events.

  1. The first use ofObject.defineProperty()Set properties in dataset.getThe event
  2. Recursively register each property in data as being observed
  3. When parsing a template, the attributes ofgetEvent to collect observer dependencies
  4. When the value of a property changes, thesetNotify every observer in the event to make all updates

How are Vue templates rendered into HTML? And the rendering process

  1. The essence of vUE template is a string, using a variety of re, the attributes in the template to js variables, VIf,vshow,vfor and other instructions into JS logic
  2. The template will eventually be converted to the render function
  3. The render function executes to return vNode
  4. Render vNode as a real DOM using the path method of vNode

The whole implementation process of Vue

  1. First parse the template into render function, turn the attributes in the template into variables in JS, vif,vshow,vfor and other instructions into logic in JS
  2. Execute render function, bind attribute monitor in the process of render function execution for the first time, collect dependencies, finally get vNode, use vNode Path method, render vNode into a real DOM
  3. After the properties are updated, the render function is re-executed, but there is no need to bind the properties and collect dependencies, and a new vNode is generated
  4. Compare the new vNode with the old vNode to find the DOM that really needs to be updated and render it

What is a diff algorithm, or what does a diff algorithm do

  • Diff is a basic Linux command that can be used to compare files and contents
  • The diff algorithm is used in VNodes to find nodes that need to be updated and avoid unnecessary updates

What is Vuex

Vuex is like a global repository of common states or states of complex component interactions that we pull out and put in.

The core of VUEX consists of the following parts:

  • State: State is stored in the state that we need to use. It is a one-way data flow, and it is not allowed to be modified directly in VUE, but modified using mutations
  • Mutations: Mutations are methods that store how to change the status
  • Actions: Actions are used for asynchronous changes and can wait until the asynchrony endscommit mutationsTo modify the state
  • Getters: equivalent to a computed property of state

Use:

  • Get the state using this.$store.state in computed within the component to get the desired state
  • Use this. Codestore.mit method in the component to change the state
  • If you use too many methods and states in a component. You can use the mapState, mapMutations auxiliary function

Communication between components in Vue

Parent component: The parent component passes the child component through Props, and the child component informs the parent sibling component through $emit: it can use vuEX global shared state, or eventBus

How do I solve the Vuex data loss problem after the page is refreshed

You can use vuex-PersistedState to solve the problem. It uses the local storage of HTML5 + vuex. Store to synchronize local and Store data

Slot usage in Vue

To complement…

What does Vue’s life hook function do when it calls each hook

  • BeforeCreate: The component instance has just been created. At this point, the properties within the component cannot be used
  • Created: A component instance is created and its properties are bound, but the DOM is not created. It is generally used to request interfaces and cannot operate the DOM
  • BeforeMount: before a template is mounted
  • Mounted: Specifies that a DOM can be accessed after a template is mounted
  • BeforeUpdate: before a component is updated
  • Update: after a component is updated
  • Activated: The hook function that is used with keep-alive and is called when the component is activated
  • Deactivated: This hook function is called when a component is removed using keep-alive
  • BeforeDestory: Called before a component is removed
  • Destoryed: Used to clear the timer after the component is removed
  • If there are child components, the call order is: Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted

Two implementation principles of front-end routing

The two routing modes are classified into hash mode and history mode

Hash mode:

The idea behind hash mode is the onHashChange event, which can be listened for on the window object. As the hash changes, the browser records history and triggers the event callback. In Hash mode, the address bar is marked with a #

The history mode:

With hashchange, you can only change the url fragment after #, whereas the History API gives the front end complete freedom

The History API can be divided into two main parts, toggle and modify, and refer to MDN

Using history requires server support. In hash mode, the front-end route modiates the information in #, which the browser does not carry when requesting it, so there is no problem. Under History, however, you are free to change the path, and if there is no response or resource on the server when it is refreshed, it will spawn a 404

What is SSR and what is the difference between SSR and previous background templates

To complement…

What does provide do in Vue?

To complement…

What are mixins generally used for?

To complement…

What is nextTick?

To complement…

algorithm

Sorting algorithm (quick row, bubble)

To complement…

How to implement depth-first traversal and breadth-first traversal?

To complement…

Written algorithm questions

Known as an array: var arr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10]. Write a program to flatten the array and divide the duplicate part of the data, and finally get an ascending and not repeating array method 1:function handleArr(arr) {
  let flatten = (arr) => arr.push ? arr.reduce((pre, current) => [...pre, ...flatten(current)], []) : [arr];
  return[...new Set(flatten(arr))].sort((a, b) => a - b); } new Set(arr.tostring ().split()","). The map (Number))]. Sort (a, b) = > (a - b) method three: [... new Set (arr. Flat (Infinity)]. Sort ((a, b) = > {return a - b})
Copy the code

Written execution questions

let test = (function (a) {
  this.a = a;
  return function (b) {
    console.log(this.a + b);
  }
})((function(a){
  returna; }) (1, 2))test(4)
Copy the code

Answer: 5

(function (a) {this.a = a; return function (b) { console.log(this.a + b); The body of the () self-executing function is called z1

The (function (a) {return a; Called z2}) (1, 2)

Function (b) {console.log(this.a + b); } is called n1

Test is the return value of the anonymous self-executing function z1. In fact, test is n1. Z1 takes a as an argument, where a is the self-executing function z2 and returns 1. In function z1 this.a = a where this refers to window so an attribute of A with a value of 1 is mounted on window

When text(4) is executed, b is passed in as 4, and this in n1 refers to window, which has a previously mounted attribute a of 1, so the result of the function is 5

The above interview topic is personal understanding, if have wrong place, welcome everybody big guy to point out in the comment area, mutual encouragement!