[Interview] Summary of common front-end interview questions

1. What are the mvvm and mvc models? 

MVVM is shorthand for Model-View-ViewModel. That is Model-View-ViewModel.

[Model] refers to the data passed by the backend.

[View] refers to the page you see.

[View Model] The core of the mvvm pattern, it is a bridge connecting view and model.

Summary: Under the framework of MVVM, the view and the model cannot communicate directly. They communicate through the ViewModel. The ViewModel usually implements an observer. When the data changes, the ViewModel can monitor the change of the data, and then notify the corresponding view for automatic update. When the user operates the view, the ViewModel can also monitor To the change of the view, and then notify the data to make the change, which actually realizes the two-way binding of the data. And the View and ViewModel in MVVM can communicate with each other.

MVC is short for Model-View-Controller. That is Model-View-Controller. M and V refer to the same meaning as M and V in MVVM. C means Controller refers to the page business logic. The purpose of using MVC is to separate M and V codes. 'MVC is one-way communication. That is, the View and the Model must be connected through the Controller. The difference between MVC and MVVM is not that VM completely replaces C. The purpose of ViewModel is to extract the business logic displayed in the Controller, not to replace the Controller. Other view operations should be implemented in the Controller. That is to say, MVVM realizes the reuse of business logic components.

2. The principle of vue two-way data binding? 

It is realized by using the method of Object.defineProperty() to redefine the operation of obtaining property value (get) and setting property value (set) of the object.

We use v-model in vue to implement two-way data binding. The principle is to detect user input, get the input value, and then update the elements of the page synchronously.

3. What are the life cycles of Vue? 

Life cycle: the process of each vue instance from creation to destruction. In this process, he has gone through a series of processes from the beginning of creation, initialization of data, compilation of templates, mounting of Dom, rendering→update→rendering, and uninstallation.

The life cycle of vue is divided into 11 stages, 4 periods
1, beforeCreate (before creation)

2, created (after creation)

3. beforeMount (before loading)

4. mounted (after loading)

5. beforeUpdate (before update)

6. updated (updated)

7. activated (called when keep-alive is activated)

8. deactivated (called when keep-alive is deactivated)

9. beforeDestroy (before destruction)

10. destroyed (after destruction)

11. errorCaptured (2.5.0+ new)
Vue's first page load will trigger four hook functions
: beforeCreate, created, beforeMount, mounted.

4. What is the difference between v-if and v-show?   

Control method : v-show hiding is to add css--display:none to the element, and the dom element is still there. v-if show hide is to add or delete the whole dom element

Compilation process : v-if switching has a partial compilation/unloading process, during which the internal event listeners and sub-components are properly destroyed and rebuilt; v-show is simply based on css switching

Compile conditional : v-if is true conditional rendering, it will ensure that event listeners and subcomponents inside the conditional block are properly destroyed and recreated during the switch. Only when the rendering condition is false, no operation is performed until it is true before rendering

When v-show changes from false to true, the life cycle of the component will not be triggered

When v-if changes from false to true, trigger the beforeCreate, create, beforeMount, mounted hooks of the component, and trigger the beforeDestory and destroy methods of the component when it changes from true to false

Performance consumption: v-if has higher switching consumption; v-show has higher initial rendering consumption.

5. What is async await? What does it do?

async / await is a new way of writing asynchronous or blocking code built on top of Promise, and is generally considered to be the ultimate and most elegant solution for js one-step operations.

Compared to Promises and callbacks, it is more readable and concise. All the time .then() is not pretty either.

Advantages and disadvantages:

Compared with Promise, async/await can handle the then chain better.
The await keyword can only be used in async function. Using the await keyword in any non-async function will throw an error. The await keyword waits for the right-hand expression (which may be a Promise) to return before executing the next line of code.
The advantage of async/await is that it handles the call chain of then, can write code more clearly and accurately, and can also solve the problem of callback hell. Of course, there are also some disadvantages, because await transforms asynchronous code into synchronous code. If multiple asynchronous codes have no dependencies but use await, performance will be reduced.

6. What are the commonly used array methods?

1. push() adds data to the array
2. pop() deletes the last data in the array
3. unshift() adds data to the front of the array
4. shift() deletes the 0th data in the array
5. concat () splicing the array
6. splice() intercepting the array
7. slice() intercepting the values ​​in the array
8. sort() sorting the array
9. reverse() reversing the array
10. join() linking the array into one string

7. How many loops are there in the array? What is the role of each?

1.forEach

Executes the provided function once for each element of the array.

2.map needs return to return a new array

3.filter filter cycle

Creates a new array containing all elements of the tests implemented by the provided function.

4.reduce

5.every cycle, each match returns true, otherwise returns false

Tests whether all elements in an array pass the test of a specified function. It returns a boolean value.

6. some loop, if there is a match, return true, otherwise return false

Tests whether at least one element is available via the provided function method. This method returns a value of type Boolean.

8. What are the commonly used string methods?

The charAt() method returns the specified character from a string.

The concat() method concatenates one or more strings with the original string to form a new string and returns it.

The includes() method is used to determine whether a string is included in another string, and returns true or false depending on the situation.

The indexOf() method returns the index of the first occurrence of the specified value in the String object on which it is called, searching from fromIndex. Returns -1 if the value is not found.

The match() method retrieves the results of returning a string matching the regular expression.

The padStart() method pads the current string with another string (repeatedly, if necessary) so that the resulting string reaches the given length. Padding is applied from the beginning (left) of the current string. (commonly used for time filling 0)

The replace() method returns a new string with some or all matching patterns replaced by the replacement value. The pattern can be a string or a regular expression, and the replacement value can be a string or a callback function to be called for each match.

The original string will not be changed.

The slice() method extracts a part of a string and returns a new string without changing the original string.

The **split()** method splits a String object into an array of strings using the specified delimiter string to separate the string into substrings to determine the position of each split.

The **substr()** method returns the characters from the specified position to the specified number of characters in a string.

The trim() method removes whitespace characters from both ends of a string. Whitespace characters in this context are all whitespace characters (space, tab, no-break space, etc.) and all line terminator characters (such as LF, CR).
 

9. What is the prototype chain?

Each instance object has a proto attribute, which points to the prototype object of the constructor, and the prototype of the constructor

An object is also an object, and it also has proto attributes, so that the process of looking up layer by layer forms a prototype chain.

10. What is a closure? Write a closure function by hand? What are the pros and cons of closures?

A closure is a function that has access to variables in the scope of another function. A simple understanding is that a function

Fields can access local variables inside another function.

 function fn() {
     var num = 10;
     function fun() {
         console.log(num); 
     }
     return fun;
 }
 var f = fn(); 
 f();

Function: Extend the scope of variables, and access local variables inside the function outside the function, which is easy to cause inner leaks, because the local variables in the closure will never be recycled.

11. What are the common inheritance?

1. Prototype chain inheritance

Features: 1. The properties that can be inherited by an instance include: the properties of the instance constructor, the properties of the parent class constructor, and the properties of the parent class prototype. (The new instance will not inherit the properties of the parent class instance!

Disadvantages: 1. The new instance cannot pass parameters to the parent class constructor.

   2. Single inheritance.

   3. All new instances will share the attributes of the parent class instance. (The properties on the prototype are shared, if one instance modifies the prototype property, the other instance's prototype property will also be modified!)

2. Borrow constructor inheritance

Key point: use .call() and .apply() to introduce the parent class constructor into the subclass function (the self-execution (copying) of the parent class function is done in the subclass function)

Features: 1. Only inherits the properties of the parent class constructor, not the properties of the parent class prototype.

   2. Solve the disadvantages 1, 2, and 3 of prototype chain inheritance.

   3. You can inherit multiple constructor attributes (call multiple).

   4. In the child instance, parameters can be passed to the parent instance.

Disadvantages: 1. It can only inherit the properties of the parent class constructor.

   2. The reuse of constructors cannot be realized. (recall every time you use it)

   3. Each new instance has a copy of the parent class constructor, which is bloated.

3. Combined inheritance (combined prototype chain inheritance and borrowed constructor inheritance) (commonly used)

Focus: Combining the advantages of the two modes, parameter passing and reuse

Features: 1. It can inherit the properties on the prototype of the parent class, can pass parameters, and can be reused.

   2. The constructor attribute introduced by each new instance is private.

Disadvantage: The parent class constructor is called twice (memory consumption), and the subclass constructor will replace the parent class constructor on the prototype.

4. Prototype Inheritance

Key point: Wrap an object with a function, and then return the call of this function, this function becomes an instance or object that can add properties at will. object.create() is the principle.

Features: Similar to copying an object and wrapping it with a function.

Disadvantages: 1. All instances will inherit the properties on the prototype.

   2. Unable to achieve multiplexing. (New instance attributes are added later)

Fifth, the class class implements inheritance

Inheritance through extends and super

6. Parasitic inheritance

Key point: It is to put a shell on the prototype inheritance.

Advantages: No custom type is created, because it just returns an object (this) with a shell, and this function naturally becomes a new object created.

Disadvantages: The prototype is not used and cannot be reused.
 

12. How is the authority management in the background management system realized?
Login: After the user fills in the account number and password, verify to the server whether it is correct. After the verification is passed, the server will return a token. After getting the token (I will store this token in a cookie to ensure that it can be remembered after refreshing the page User login status), the front end will pull a user_info interface according to the token to obtain the user's detailed information (such as user rights, user name, etc.).

Authority verification: Obtain the user's corresponding authority through token, dynamically calculate the corresponding authorized route according to the user's authority, and dynamically mount these routes through router.addRoutes.

Specific ideas:

After successful login, the server will return a token (the token is a key that can uniquely identify the user’s identity), and then we will store the token in a local cookie, so that it can be remembered when the page is opened or refreshed next time The user's login status, no need to go to the login page to log in again.

ps: In order to ensure security, all token validity periods (Expires/Max-Age) of our company in the background are Session, that is, they will be lost when the browser is closed. Re-opening the browser requires re-login verification, and the back-end will re-refresh the token at a fixed time every week to allow all background users to log in again to ensure that the background users will not be used at will due to computer loss or other reasons.

After the user logs in successfully, we will intercept the route in the global hook router.beforeEach to determine whether the token has been obtained. After obtaining the token, we will obtain the basic information of the user

The page will first check whether there is a token in the cookie. If not, go through the previous part of the process to log in again. If there is a token, it will return the token to the backend to pull user_info to ensure that the user information is up to date. Of course, if the single sign-on function is implemented, it is also possible to store user information locally. When you log in on one computer, the other is pulled offline, so always log back in to get the latest content.

Let me talk about the main idea of ​​my authority control first. There will be a routing table at the front end, which indicates the accessible authority of each route. After the user logs in, obtain the user's role through the token, dynamically calculate the corresponding authorized route according to the user's role, and then dynamically mount the route through router.addRoutes. But these controls are only at the page level. To put it bluntly, no matter how the front-end permission control is done, it is not absolutely safe, and the back-end permission verification cannot escape.

Our company is now using the front-end to control page-level permissions. Users with different permissions display different sidebars and limit the pages they can enter (also do a little button-level permission control), and the back-end will verify each involved For the requested operation, verify whether it has the permission for the operation. Every background request, whether it is get or post, will let the front-end carry the user's token in the request header, and the back-end will verify whether the user has permission to perform the operation based on the token. . If there is no permission, a corresponding status code is thrown, and the front end detects the status code and makes corresponding operations.

Use vuex to manage the routing table, and render sidebar components according to the routes accessible in vuex.

Implementation:

When creating a vue instance, mount vue-router, but at this time, vue-router mounts some login or public pages that do not require permissions.

After the user logs in, obtain the role, compare the role with the required permissions of each page of the routing table, and generate a routing table accessible to the end user.

Call router.addRoutes(store.getters.addRouters) to add user-accessible routes.

Use vuex to manage the routing table, and render sidebar components according to the routes accessible in vuex.

14. What are the new features of es6?
ES6 is a new version launched in 2015. This version has made a lot of optimizations compared to the syntax of ES5, for example: new let, const

let and const have block-level scope, and there is no problem of variable promotion. Arrow functions are added, which simplifies the writing of defining functions. At the same time, you can use the this of arrow functions (note that the arrow function itself does not have this, and its this depends on the external environment), and add promise to solve the problem of callback regions. , Added modularization, using import and export to realize import and export. Structural assignment has been added. ES6 allows to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern. This is called Destructuring. Added the concept of a class class, which is similar to an object.

15. Why does the v-for loop have to bind the key?
The labels on the page correspond to specific virtual dom objects (virtual dom is the js object). In the loop, if there is no unique key, delete a label on the page, because I don’t know That one is deleted! So all the virtual dom should be re-rendered. If you know that the key is x and the label is deleted, you only need to remove the rendered dom with x label!

16. Why should the data in the component be defined as a function instead of an object?
Every component is an instance of Vue. Components share the data attribute. When the value of data is the value of the same reference type, changing one of them will affect the other.

17. What are the common methods of vertically centering boxes? Please give examples of 3 methods?
Realize by using the positioning of son and father

 #container{
     width:500px;
     height:500px;
     position:relative;
 }
 #center{
     width:100px;
     hight:100px;
      position: absolute;
      top: 50%;
      left: 50%;
     margin-top:-50px;
     margin-left:-50px;
     
 }

Using the transform of Css3, you can easily realize the vertical centering of the element when the height and width of the element are unknown.

 #container{
     position:relative;
 }
 #center{
     position: absolute;
     top: 50%;
     left: 50%;
     transform: translate(-50%, -50%);
 }
flex

 #container{
     display:flex;
     justify-content:center;
     align-items: center;
 }
 ​
 #center{
 ​
 }


18. What do you usually use to achieve cross-domain?
jsonp: Taking advantage of the loophole that the <script> tag does not have cross-domain restrictions, the web page can obtain JSON data dynamically generated from other sources. JSONP requests must be supported by the other party's server.

The advantage of JSONP is that it is simple and compatible, and can be used to solve the problem of cross-domain data access by mainstream browsers. The disadvantage is that only the get method is supported, and it is unsafe and may suffer from XSS attacks.

Declare a callback function, whose function name (such as show) is used as a parameter value to be passed to the server that requests data across domains, and the function parameter is the target data to be obtained (data returned by the server).

Create a <script> tag, assign the cross-domain API data interface address to the src of the script, and pass the function name to the server in this address (you can pass parameters through question marks:?callback=show).

After the server receives the request, it needs to perform special processing: concatenate the passed function name and the data it needs to give you into a string, for example: the passed function name is show, and the data it prepares is show('I Do not love you').

Finally, the server returns the prepared data to the client through the HTTP protocol, and the client calls and executes the previously declared callback function (show) to operate on the returned data.

CORS: Cross-Origin Resource Sharing (CORS) is a mechanism; when a resource accesses another resource (this resource is placed in

Different domain names or different protocols or ports), the resource will initiate a cross-domain HTTP request, which needs to be supported by both the browser and the server;

The entire CORS communication is done automatically by the browser. When the browser finds that the AJAX request is cross-origin, it will automatically add some additional header information, and sometimes there will be an additional request, but the user will not feel it;

The key to realizing CORS is the server, as long as the server implements the CORS interface, it can communicate across origins

The server handles different requests in different ways; there are simple requests and non-simple requests.

19. What is the difference between cookie, localstorage, and sessionstrorage?
Interact with the server:

Cookie is the data (usually encrypted) stored on the user's local terminal by the website to identify the user's identity

Cookies are always carried in the same-origin HTTP request header (even if not required), and are passed back and forth between the browser and the server

sessionStorage and localStorage will not automatically send data to the server, only save it locally

Storage size:

The cookie data is limited by different browsers, and the size generally cannot exceed 4k

Although sessionStorage and localStorage also have storage size limitations, they are much larger than cookies and can reach 5M or greater

Expiration time:

localStorage stores persistent data, and the data will not be lost after the browser is closed unless the data is actively deleted

sessionStorage data is automatically deleted after the current browser window is closed

The cookie set by the cookie is valid until the expiration time, regardless of whether the browser is closed or not.

20. What are the pointers of this?
1. This in ordinary functions points to window

2. This in the timer points to window

3. The arrow function does not have this, its this point depends on the external environment,

4. This in the event points to the caller of the event

5. Both this in the constructor and this in the prototype object point to the instance object created by the constructor new

6. This in the class class points to the instance object created by the constructor constructor new

7. This in the self-invoking function points to window.

21. What is recursion, and what are the advantages or disadvantages of recursion?
Recursion: A function is recursive if it can call itself internally. Simple understanding: letter

The number calls itself internally, this function is a recursive function

Advantages: clear structure, strong readability

Disadvantages: low efficiency, and the call stack may overflow. In fact, each function call will allocate space in the memory stack, and the stack capacity of each process is limited. When there are too many levels of calls, the stack capacity will be exceeded. resulting in a stack overflow. -> performance

22. Tell me about the methods you usually use for performance optimization?
Reduce the number of http requests, package and compress online code, use lazy loading, use Sprite images, dynamically render components, and CDN loading packages .

23. Which tag is the vue instance mounted on?
The vue instance will be mounted in the body tag at the end, so we cannot get the body tag in vue. If you want to use the body tag, you need to get it in a native way.

24. What is a deep copy and what is a shallow copy?
Shallow copy: Creates a new object that has an exact copy of the original object's property values. If the attribute is a basic type, the value of the basic type is copied. If the attribute is a reference type, the memory address is copied, so if one of the objects changes this address, it will affect the other object.

A deep copy will copy all attributes and copy the dynamically allocated memory pointed to by the attributes. A deep copy occurs when an object is copied along with the objects it refers to. Deep copies are slower and more expensive than shallow copies. The two objects before and after copying do not affect each other.

25. What is the execution mechanism of js?
js is a single-threaded, asynchronous, non-blocking I/O model, event loop execution mechanism

All tasks can be divided into two types, one is synchronous tasks (synchronous), and the other is asynchronous tasks (asynchronous). A synchronous task refers to a task that is queued for execution on the main thread. Only when the previous task is completed can the next task be executed. Asynchronous tasks refer to tasks that do not enter the main thread but enter 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 for execution.

26. Please write at least three methods for deduplication of arrays? (native js)
using filter

 function unique(arr) {
   return arr.filter(function(item, index, arr) {
     //当前元素,在原始数组中的第一个索引==当前索引值,否则返回当前元素
     return arr.indexOf(item, 0) === index;
   });
 }
     var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
         console.log(unique(arr))

Use ES6 Set to remove duplicates (most commonly used in ES6)

 function unique (arr) {
   return Array.from(new Set(arr))
 }
 var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
 console.log(unique(arr))
  //[1, "true", true, 15, false, undefined, null, NaN, "NaN", 0, "a", {}, {}]

Use for to nest for, and then splice to deduplicate (the most commonly used in ES5)

 function unique(arr){            
         for(var i=0; i<arr.length; i++){
             for(var j=i+1; j<arr.length; j++){
                 if(arr[i]==arr[j]){         //第一个等同于第二个,splice方法删除第二个
                     arr.splice(j,1);
                     j--;
                 }
             }
         }
 return arr;
 }
 var arr = [1,1,'true','true',true,true,15,15,false,false, undefined,undefined, null,null, NaN, NaN,'NaN', 0, 0, 'a', 'a',{},{}];
     console.log(unique(arr))
     //[1, "true", 15, false, undefined, NaN, NaN, "NaN", "a", {…}, {…}]     //NaN和{}没有去重,两个null直接消失了


27. Please write at least two common array sorting methods (native js)
quick sorting

function quickSort(elements){
     if(elements.length <=1){
       return elements;  
     }
   var pivotIndex=Math.floor(elements.length / 2);
   var pivot=elements.splice(pivotIndex,1)[0];
   var left=[];
   var right=[];
   for(var i=0;i<elements.length;i++){
     if(elements[i] < pivot){
         left.push(elements[i]);
     }else{
        right.push(elements[i]);
     }
   } 
 return  quickSort(left).concat([pivot],quickSort(right));


The concat() method is used to concatenate two or more arrays; this method does not change the existing arrays, but only returns a copy of the concatenated arrays.
 ​Insertion
sort

function sort(elements){
    // 假设第0个元素是一个有序数列,第1个以后的是无序数列,
    // 所以从第1个元素开始将无序数列的元素插入到有序数列中去
    for (var i =1; i<=elements.length; i++) {
        // 升序
        if(elements[i] < elements[i-1]){
            // 取出无序数列中的第i个作为被插入元素
            var guard=elements[i];
            //记住有序数列的最后一个位置,并且将有序数列的位置扩大一个
            var j=i-1;
            elements[i]=elements[j];
            // 比大小;找到被插入元素所在位置
            while (j>=0 && guard <elements[j]) {
                elements[j+1]=elements[j];
                j--;
            }
            elements[j+1]=guard; //插入
        }
    }
}
var elements=[3,5,6,8,2,4,7,9,1,10];
document.write('没调用之前:'+elements);
document.write('<br>');
sort(elements);
document.write('被调用之后:'+elements);


Bubble Sort

function sort(elements){
    for(var i=0;i<elements.length-1;i++){
       for(var j=0;j<elements.length-1-i;j++){
          if(elements[j] > elements[j+1]){
               var  swap=elements[j];
               elements[j]=elements[j+1];
               elements[j+1]=swap;
          }
       }
    }
}
var elements=[3,5,6,8,2,4,7,9,1,10];
console.log('before'+elements);
sort(elements);
console.log('after'+elements);


28. Do you know lodash? What common APIs does it have?
Lodash is a consistent, modular, high-performance JavaScript utility library.

_.cloneDeep deep copy

_.reject removes an element based on a condition.

_.drop(array, [n=1] ) Function: Remove the first n elements in the array, and then return the rest.

29. What are the HTTP request methods?
get, post, put, delete, etc.

30. What tools are usually used for packaging? What is babel?
WebPack is a module packaging tool. You can use WebPack to manage your module dependencies and compile the static files required by the output modules. It can well manage and package HTML, Javascript, CSS and various static files (pictures, fonts, etc.) used in web development, making the development process more efficient. For different types of resources, webpack has corresponding module loaders. The webpack module packager will analyze the dependencies between modules, and finally generate optimized and merged static resources

Babel can help us convert some grammars that are not supported by current browsers, and it will convert these grammars into lower version grammars for browser recognition.
 

31. What are set and map?
set is a new data structure provided by es6, which is similar to an array, but the values ​​of its members are unique.

Map is a new data structure provided by es6. It is similar to an object and is also a collection of key-value pairs, but the range of keys is not limited to strings, and various types of values ​​can be used as keys. In other words, the Object structure provides a "string-value" correspondence, and the Map structure provides a "value-value" correspondence, which is a more complete implementation of the Hash structure. If you need a "key-value pair" data structure, Map is more suitable than Object.

32. What are the methods to clear the float?
Why clear the floating, because the floating box is out of the standard flow, if the height of the parent box is not set, the box below will be propped up.

1. Additional label method (after the last floating label, add a new label and set clear: both;) (not recommended)

2. Add the overflow attribute to the parent (add overflow:hidden to the parent element) (not recommended)

3. Use the after pseudo-element to clear the float (recommended)

    .clearfix:after{/*伪元素是行内元素 正常浏览器清除浮动方法*/
        content: "";
        display: block;
        height: 0;
        clear:both;
        visibility: hidden;
    }
    .clearfix{
        *zoom: 1;/*ie6清除浮动的方式 *号只有IE6-IE7执行,其他浏览器不执行*/
}

4. Use before and after double pseudo-elements to clear floats

 .clearfix:after,.clearfix:before{
        content: "";
        display: table;
    }
    .clearfix:after{
        clear: both;
    }
    .clearfix{
        *zoom: 1;
    }

33. What are the common layout methods? What are their strengths and weaknesses?
Commonly used methods for page layout include floating, positioning, flex, grid grid layout, and grid system layout

float:

Advantages: good compatibility.

Disadvantage: Floats break out of standard document flow, so floats need to be cleared. We can fix this problem.

absolute positioning

Advantages: fast.

Disadvantages: The child elements are also separated from the standard document flow, and the practicability is poor.

flex layout (appeared in CSS3)

Advantages: To solve the shortcomings of the above two methods, the flex layout is perfect. The mobile terminal basically uses flex layout.

Grid layout (grid)

The layout introduced in CSS3 is very useful. The amount of code is simplified a lot.

A middle adaptive layout of left and right 300px realized by grid layout

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        html * {
            padding: 0;
            margin: 0;
        }
        /* 重要:设置容器为网格布局,宽度为100% */
        .layout.grid .left-center-right {
            display: grid;
            width: 100%;
            grid-template-rows: 100px;
            grid-template-columns: 300px auto 300px;  /* 重要:设置网格为三列,并设置每列的宽度。即可。*/
        }
        .layout.grid .left {
            background: red;
        }
        .layout.grid .center {
            background: green;
        }
        .layout.grid .right {
            background: blue;
        }
    </style>
</head>
<body>
    <section class="layout grid">
        <article class="left-center-right">
            <div class="left">
                我是 left
            </div>
            <div class="center">
                <h1>网格布局解决方案</h1>
                我是 center
            </div>
            <div class="right">
                我是 right
            </div>
        </article>
    </section>
</body>
</html>

34. How is lazy loading of pictures realized?
That is, we first set the data-set attribute of the picture (of course, it can be any other, as long as it does not send http requests, the function is to access the value) as the value of its picture path, because it is not src, so it will not send http ask. Then we calculate the sum of the height of scrollTop on the page and the height of the browser. If the coordinate Y of the picture from the top of the page (relative to the entire page, not the browser window) is less than the sum of the former two, it means that the picture will be displayed (the right time, of course, it can also be other situations), at this time we can replace the data-set attribute with the src attribute.

35. What is the difference between computed and watch in vue?
The computed attribute is to simplify the computational complexity of the template string in the template and prevent the template from being too redundant. it has caching properties

Computed is used to monitor the variables defined by oneself. This variable is not declared in data, but directly defined in computed, and then two-way data binding can be performed on the page to display the results or be used for other processing;

watch is mainly used to monitor the changes of vue instances. Of course, the variables it monitors must be declared in data. It can monitor a variable or an object. It is generally used to monitor routing, special processing of the value of the input input box, etc. , it is more suitable for scenarios where one data affects multiple data, and it is not cacheable

watch: It monitors the attribute value. As long as the attribute value changes, it will trigger the execution of the callback function to perform a series of operations.

computed: It monitors the dependent value. If the dependent value remains unchanged, it will directly read the cache for multiplexing, and it will recalculate when it changes.

In addition, there is a very important difference: Computed properties cannot perform asynchronous tasks, and computed properties must perform synchronous tasks. That is to say, computed properties cannot request or perform asynchronous tasks from the server. If an asynchronous task is encountered, it is handed over to the listening property. Watch can also detect computed attributes.

36. How does vue implement value transfer from father to son, son to father, and brothers?
Passing values ​​from parent to child is mainly through the props attribute, props is read-only

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>父组件向子组件传值--props</title>
    <script src="./js/vue.min.js"></script>
</head>
<body>
    <div id="app">   
        <menu-item title="来自父组件的值"></menu-item>
  <!--   在子组件身上绑定自定义属性来接收父组件data中的数据 -->
        <menu-item :tit="title"></menu-item>
    </div>
    <script>
Vue.component('menu-item',{
    props:['tit'],  //props用来接收父组件传过来的值
    //在props中使用驼峰形式,模版中要改为使用短横线拼接  props里面的值只读,不能修改
    //props是单向数据流
    data(){
        return{
        }
    },
    template:'<div>{
   
   {tit}}</div>'
})
        var vm=new Vue({
           el:'#app',
           data:{
              title:'我是父组件中的数据'
           },
           methods:{
           }
        });
    </script>
</body>
</html>

The child passes the value $emit to the parent

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <!--   父组件 -->
    <div :style='{fontSize:fontSize+"px"}'>{
   
   {pmsg}}</div>
   <!--  子组件 -->
    <menu-item :parr="parr" @aas="blune"></menu-item>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /*

Passing values ​​from child components to parent components - basic usage

      props传递数据原则:单向数据流
    */
    Vue.component('menu-item', {
     props:['parr'],
     data(){
           return {
               msg1:'这是子组件传递过来的值'
           }
        },
      template: `
        <div>
          <ul>
            <li v-for="(item,index) in parr" :key="index">{
   
   {item}}</li>
          </ul>
          <button @click='dd'>扩大父组件中字体大小</button> 
        </div>
      `,
      methods:{
          dd(){
           this.$emit("aas",this.msg1)
          } 
      }
    });
 //$emit
    var vm = new Vue({
      el: '#app',
      data: {
        pmsg: '父组件中内容',
        parr: ['apple','orange','banana'],
        fontSize: 10
      },
      methods: {
        blune(message){
            this.fontSize+=5;
            console.log(message);   
        }
      }
    });
  </script>
</body>
</html>

 Sibling component pass value event bus

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./js/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <brother></brother>
        <sister></sister>
    </div>
    <script>
        var enveBus = new Vue();
        Vue.component('brother', {
            data() {
                return {
                    kk: ''
                }
            },
            methods: {
                dd() {
                    enveBus.$emit("bTs", '这是哥哥给妹妹的爱')
                }
            },
            template: `
        <div>
          <button @click='dd'>这是一个哥哥组件---{
   
   {kk}}</button>
        </div>
      `,
            mounted() {
                enveBus.$on('asd', (result) => {
                    this.kk = result;
                })
            }
        });
        Vue.component('sister', {
            data() {
                return {
                    sis: ''
                }
            },
            template: `
   <div>
     <button @click="cc">这是一个妹妹组件---{
   
   {sis}}</button> 
   </div>
 `,
            mounted() {
                enveBus.$on('bTs', (message) => {
                    this.sis = message
                })
            },
            methods: {
                cc() {
                    enveBus.$emit('asd', '这是妹妹对哥哥的爱');
                }
            }
        });
        var vm = new Vue({
            el: '#app',
            data: {
            },
            methods: {
            }
        });
    </script>
</body>
</html>

37. What vuex, talk about your understanding of it?
First of all, the emergence of vuex is to solve the problem of complex and confusing value transfer between components in the process of web component development

Put the data we need to share among multiple components into the store,

To get or format data you need to use getters,

To change the data in the store, use mutation, but it can only contain synchronous operations, and the way to call this.$store.commit('xxxx') in specific components

Action also changes the data in the store, but it is a submitted mutation, and can contain asynchronous operations. The calling method in the component is this.$store.dispatch('xxx'); the commit('call mutation') used in actions

38. What methods are there for judging data types? What are their strengths, weaknesses and differences?
Then the method of judging the data type can generally be used: four common methods: typeof, instanceof, constructor, toString

Advantages and disadvantages of different types typeof instanceof constructor Object.prototype.toString.call
Advantages Simple to use Can detect reference types Basically can detect all types (except null and undefined) Detect all types Disadvantages
can only detect basic types (null ) cannot detect basic types, and cannot be easily modified across iframe constructors, nor can it be crossed across iframes. Under IE6, undefined and null are both Object


39. Do you know symbols?
ES6 introduces a new primitive data type Symbol, which represents a unique value.

40. Please describe the class class in ES6?
The class in es6 can be regarded as the syntactic sugar of the constructor in es5, which simplifies the writing of the constructor, and the common attributes of the class are placed in the constructor

Create a class through the class keyword, and we still habitually define the first letter of the class name to be capitalized

There is a constructor function in the class, which can accept the passed parameters and return the instance object at the same time

The constructor function will automatically call this function as long as new generates an instance. If we don't write this function, the class will automatically generate this function

Multiple function methods do not need to be separated by commas

Generate instance new cannot be omitted

Grammatical specification, do not add parentheses after the class name of the created class, add parentheses after the class name of the generated instance, and do not need to add function to the constructor

In inheritance, if instantiating a subclass outputs a method, first check whether the subclass has this method, and if so, execute the subclass first

In inheritance, if there is no such method in the subclass, check whether the parent class has this method, and if so, execute the method of the parent class (proximity principle)

If the subclass wants to inherit the method of the parent class, and at the same time extend its own method inside itself, use super to call the constructor of the parent class, super must be called before the subclass this

Always pay attention to the pointing problem of this, the common properties and methods in the class must be used with this.

The this in the constructor points to the new instance object

Custom methods, generally also point to new instance objects

After binding the event, this points to the event source that triggered the event

There is no variable promotion for classes in ES6, so the class must be defined before objects can be instantiated through the class.


41. Talk about the box model?

In the standard box model, width and height refer to the width and height of the content area. Increasing padding, borders, and margins will not affect the size of the content area, but will increase the overall size of the element's box.

In the IE box model, width and height refer to the width and height of the content area + border + padding.

42. What is promise? What does it do?
Promise is a solution to asynchronous programming. Simply put, it is a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which messages of asynchronous operations can be obtained.

It can solve the problem of callback hell, which is the problem of asynchronous deep nesting

.catch()

Get exception information

.finally()

Whether successful or not (not a formal standard)

/*
     1. Promise基本使用
     我们使用new来构建一个Promise  Promise的构造函数接收一个参数,是函数,并且传入两个参数:           resolve,reject, 分别表示异步操作执行成功后的回调函数和异步操作执行失败后的回调函数
*/


var p = new Promise(function(resolve, reject){
//2. 这里用于实现异步任务  setTimeout
setTimeout(function(){
  var flag = false;
  if(flag) {
    //3. 正常情况
    resolve('hello');
  }else{
    //4. 异常情况
    reject('出错了');
  }
}, 100);
});
//  5 Promise实例生成以后,可以用then方法指定resolved状态和reject状态的回调函数 
//  在then方法中,你也可以直接return数据而不是Promise对象,在后面的then中就可以接收到数据了  
p.then(function(data){
console.log(data)
},function(info){
console.log(info)
});


43. What is the difference between vue-cli 2.0 and 3.0?

3.0 hides the configuration file of webpack. If you need to configure it, you need to create a vue.config.js file. 3.0 was released in October 2018.

44. What are the characteristics of the arrow function, please briefly describe it?
The arrow function does not have its own this, this points to the this of the external execution environment where the arrow function is defined

Even calling call/apply/bind cannot change the this of the arrow function

Arrow functions themselves have no names

The arrow function cannot be new, and an error will be reported

The arrow function has no arguments, and the access to this variable in the arrow function accesses the arguments of the external execution environment

Arrow functions have no prototype.

45. What are the common problems on the mobile terminal and how to solve them?
Click event 300MS delay problem solution: download the package of fastclick

The H5 page window is automatically adjusted to the device width, and users are prohibited from zooming the page

<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> 


Ignore the recognition of email addresses in the Android platform

<meta name="format-detection" content="email=no"> 

When the website is added to the home screen quick start method, the address bar can be hidden, only for ios safari

<!-- ios7.0版本以后,safari上已看不到效果 -->

<meta name="apple-mobile-web-app-capable" content="yes">

46. ​​What is the difference between post and get requests?
GET: Generally used for information acquisition, using URL to pass parameters, and there is also a limit to the number of sent information, generally 2000 characters

POST: Generally used to modify resources on the server, there is no limit to the information sent.

The GET method needs to use Request.QueryString to obtain the value of the variable, and the POST method obtains the value of the variable through the Request.Form, that is to say, Get passes the value through the address bar, and Post passes the value by submitting the form.

However, use a POST request in the following cases:

Unable to use cache file (update file or database on server)

Send a large amount of data to the server (POST has no data limit)

POST is more stable and reliable than GET when sending user input that contains unknown characters.

47. What is the same-origin policy?
The so-called same-origin policy is a security mechanism of the browser to restrict communication between websites of different origins. The same origin means that the domain name, protocol, and port are consistent.

48. What do the http status codes mean?
1xx indicates that the HTTP request has been accepted, continue to process the request 2xx indicates that the HTTP request has been processed (200) 3xx indicates that the requested URL is redirected to another directory (304 resources have not changed, and will be redirected to local resources) 4xx indicates the client An error occurred (403 access forbidden, 404 resource does not exist) 5xx indicates an error occurred on the server.

49. What is BFC?
BFC (block-level formatting context), a box that creates a new BFC is independently laid out, and the layout of elements inside the box does not affect elements outside the box. Two adjacent boxes in the same BFC have a margin overlapping problem in the vertical direction.

BFC creates an independent rendering area in the value browser. The layout of all elements in this area will not affect the layout of elements outside the area. This rendering area only works on block-level elements.

50. What is token? (encryption)
token can also be called a token, generally composed of uid+time+sign (signature)+[fixed parameters]

uid: the unique identity of the user
time: the timestamp of the current time
sign: signature, compressed into a fixed-length hexadecimal string using hash/encrypt to prevent malicious splicing by third parties
Fixed parameters (optional): some commonly used Fixed parameters are added to the token to avoid repeated database checks.
The token is generally stored in localStorage, cookie, or sessionStorage on the client side. Usually stored in the database on the server

token authentication process

The user logs in, and the server returns Token to the client after success.
After the client receives the data, it is stored on the client
. The client visits the server again, and puts the token into the headers or each request parameter.
The server uses a filter for verification. If the verification is successful, the request data will be returned, and if the verification fails, an error code will be returned.
token can resist csrf, but cookie+session cannot

Sessions are stateful and are generally stored in the server memory or hard disk. When the server is distributed or clustered, the session will face load balancing problems. In the case of load balancing multiple servers, it is not easy to confirm whether the current user is logged in, because multiple servers do not share sessions

The client logs in and transmits the information to the server. After receiving it, the server encrypts the user information (token) and sends it to the client. The client stores the token in containers such as localStroage. The client passes the token every time it visits, and the server decrypts the token to know who the user is. Through cpu encryption and decryption, the server does not need to store sessions to occupy storage space, which is a good solution to the problem of load balancing multiple servers. This method is called JWT (Json Web Token).

51. What are the data types of js?
js data types are divided into basic data types (string, number, boolean, null, undefined, symbol) and complex data types

Characteristics of basic data types: data stored directly on the stack

The characteristics of complex data types: what is stored is that the object is referenced in the stack, and the real data is stored in the heap memory.

52. What happens during the process of a page from entering the URL to when the page is loaded and displayed?
01. The browser searches for the IP address corresponding to the domain name (DNS query: browser cache -> system cache -> router cache -> ISP DNS cache -> root domain name server)

02. The browser sends an HTTP request to the Web server (TCP three-way handshake)

03. Server 301 redirection (from http://example.com to http://www.example.com)

04. The browser follows the redirection address and requests another URL with www

05. The server processes the request (reading resources through routing)

06. The server returns an HTTP response (set the Content-type to 'text/html' in the header)

07. The browser enters the DOM tree construction

08. The browser sends a request to obtain resources embedded in HTML (such as pictures, audio, video, CSS, JS, etc.)

09. The browser displays the completion page

10. The browser sends an asynchronous request

53. Security issues: CSRF and XSS attacks?
CSRF (Cross-site request forgery): Cross-site request forgery.

Method 1, Token verification: (most used)

The server sends a token to the client;

The form submitted by the client carries this token.

If the token is invalid, the server rejects the request.

Method 2: Hide the token:

Hide the token in the http header.

Method 2 is a bit similar to method 1, there is not much difference in essence, but there is a difference in the way of use.

Method 3, Referer verification:

Referer refers to the source of the page request. It means that the server only responds to the request of this site; if not, it intercepts

XSS (Cross Site Scripting)``: cross-domain scripting attack.

1. Encoding:

HTML Entity encodes the data entered by the user.

As shown in the figure above, convert characters into escape characters.

The role of Encode is to convert some characters such as $var`, so that the final output of the browser is the same.

For example, this code:

<script>alert(1)</script>

If no processing is performed, the browser will execute the js operation of alert to realize XSS injection. After the encoding process, the display result of L in the browser is <script>alert(1)</script>, which realizes the output of `$var as plain text and does not cause the execution of JavaScript.

2. Filter:

Remove user input and event related attributes. For example, onerror can automatically trigger attacks, and onclick, etc. (All in all, filter out some unsafe content)

Remove the Style node, Script node, and Iframe node input by the user. (Especially the Script node, which supports cross-domain, must be removed).

3. Calibration

Avoid decoding HTML Entities directly.

Correct unpaired DOM tags using DOM Parse transformations.

Remarks: We should understand the concept of DOM Parse. Its function is to parse text into DOM structure.

The more commonly used method is to convert it into text through the encoding in the first step, then convert it into a DOM object in the third step, and then filter it in the second step.

54. The difference between CSRF and XSS Difference
1:

CSRF: The user needs to log in to website A first to get the cookie

XSS: No login required.

Difference 2: (difference in principle)

CSRF: It uses the vulnerability of website A itself to request the API of website A.

XSS: It is to inject JS code into website A, and then execute the code in JS to tamper with the content of website A.

55. The difference between cookie and session
1. Cookie data is stored on the client's browser, and session data is stored on the server.

2. The cookie is not very safe, others can analyze the locally stored COOKIE and cheat the COOKIE

Considering security, session should be used.

3. The session will be saved on the server within a certain period of time. When the number of visits increases, it will take up the performance of your server

Considering reducing server performance, COOKIE should be used.

4. The data saved by a single cookie cannot exceed 4K, and many browsers limit a site to save up to 20 cookies.

5. So my personal suggestion:

Store important information such as login information as SESSION

If other information needs to be kept, it can be placed in COOKIE.

56.
Similarities and differences between call, apply, and bind: both can change the direction of this; difference: call and apply will call the function, and change the internal this point of the function. The parameters passed by call and apply are different, and the parameters passed by call are used Separated by commas, apply uses an array to pass bind will not call the function, you can change the internal this point of the function. Application scenario

call often does inheritance.

apply is often related to arrays. For example, using mathematical objects to achieve the maximum and minimum values ​​of an array

bind does not call the function, but still wants to change the this point. For example, change the this point inside the timer.
 

Guess you like

Origin blog.csdn.net/qq_46580087/article/details/124562372