Common high-frequency interview questions at the front end

1. What are MVVM and MVC models?

MVC: MVC (model-view-controller) is a hierarchical architecture idea of a project. It separates complex business logic into small modules with single functions. Each module seems to be independent of each other, but in fact, each module has an interdependent relationship. Its advantages are: to ensure the intelligent simplicity of the module, convenient program development, maintenance, low coupling degree.

MVVM: MVVM: MVVM is model-view-ViewModel (model-view-controller), which is a two-way data binding mode. The ViewModel is used to establish the connection between the Model data layer and View View layer. Data changes will affect the View, and View changes will affect the data

2, vUE bidirectional data binding principle?

Vue. js adopts data hijacking combined with publiser-subscriber mode. It hijacks the setter and getter of each attribute through Object.defineProperty() to publish messages to subscribers when data changes and trigger corresponding listening callback.

Specific steps:

Step 1: You need to recursively traverse the Observe data object, including the property of the child property object, with setters and getters so that assigning a value to that object triggers the setter, and you can listen for data changes

Step 2: Compile parses the template instruction, replaces the variables in the template with data, and initializes the render page view, binds the corresponding node of each instruction to update function, adds the subscriber that listens to the data, receives notification once the data changes, and updates the view

Step 3: The Watcher subscriber acts as a communication bridge between the Observer and Compile. It mainly does the following:

1. Add yourself to the attribute subscriber (DEP) during self instantiation

2. It must have an update() method

3. If you call your own update() method and trigger the callback bound with Compile, you are out of the game.

Step 4: MVVM, as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor its model data changes, and uses Compile to parse and Compile template instructions. Finally, Watcher is used to build a communication bridge between Observer and Compile to achieve data change -> view update; View Interactive Changes (INPUT) -> Bidirectional binding effect of data model changes.

3. What is the life cycle of vUE?

The process from creation to destruction of a VUE instance is the lifecycle.

That is, create from the start, initialize the data, compile the template, hang in the DOM -> render, update -> render, prepare to destroy, destroy in, etc

The declaration cycle of VUE is usually divided into four stages and eight hook functions

The other three lifecycle functions are not commonly used

Keep-alive is primarily used to preserve component state or avoid re-rendering.

Activated is called only when the keep-alive component is active.

Deactivated is invoked only when the keep-alive component is disabled.

ErrorCapured is called when an error from a descendant component is caught. The hook receives three parameters: the error object, the component instance where the error occurred, and a string containing information about the source of the error. This hook can return false to prevent further propagation of the error.

1. Before and after creation

Data and Method are not initialized when the beforeCreate life cycle function is executed

Data and Method are already initialized when the Created lifecycle function executes

Before/after rendering

The beforeMount lifecycle function executes when the template string is compiled but not actually rendered into the page

When the Mounted lifecycle function is executed, the page is rendered and visible

Iii. Before/after data update

BeforeUpdate life cycle functions are executed, the latest data is available but not yet rendered into the view.

When the updated life cycle function is executed, the updated data has been rendered to the view.

Before/after destruction

BeforeDestroy lifecycle functions execute, the instance enters the phase of preparation for destruction, at which point data, methods, instructions, and so on are still available

The destroyed lifecycle is completed and data, methods, and instructions are not available

4. What’s the difference between V-IF and V-show?

V-if is “true” conditional rendering, because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch, essentially performing the creation or destruction of DOM elements.

V-show is much simpler — no matter what the initial conditions are, the element is always rendered and simply switches based on CSS. It operates on the display: None/Block property.

In general, V-if has a higher switching overhead, while V-show has a higher initial rendering overhead. Therefore, v-show is good if you need to switch very frequently; It is better to use V-if if conditions rarely change at run time.

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

Async await is a new syntax in ES7. What it does is async declares that a function is asynchronous and await that an asynchronous method is finished. It’s a good substitute for “then” in promises

The async function returns a Promise object, and callbacks can be added using the then method. When a function executes, it returns as soon as it encounters await, waits for the asynchronous operation to complete, and then executes the following statement in the function body.

6. What are the common array methods?

The concat() method is used to merge two or more arrays. This method does not change an existing array, but returns a new array.

The **find()** method returns the value of the first element in the array that satisfies the provided test function. Otherwise return undefined.

The **findIndex()** method returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned.

The **includes()** method is used to determine if an array contains a specified value, returning true if it does and false otherwise.

The **indexOf()** method returns the first index where a given element can be found in the array, or -1 if none exists. (Usually used to determine if the element is in the array)

The **join()** method joins all the elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item is returned without a delimiter.

The **pop()** method removes the last element from the array and returns the value of that element. This method changes the length of the array.

The **push()** method adds one or more elements to the end of an array and returns the array’s new length.

The **shift()** method removes the first element from the array and returns the value of that element. This method changes the length of the array.

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array (this method modifies the original array **)**.

The splice() method modifies an array by deleting or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.

An array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.

The **reverse()** method reverses the position of the elements in the array and returns the array. This method changes the original array.

The **sort()** method sorts the elements of an array using an in-place algorithm and returns the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences

7. How many ways can arrays loop? What are the roles of the two?

The **every()** method tests whether all elements in an array pass the test of a given function. It returns a Boolean value.

The **filter()** method creates a new array containing all the elements of the test implemented by the provided function.

The **forEach()** method performs the provided function once on each element of the array.

The **some()** method tests whether at least one element can pass the provided function method. This method returns a Boolean value.

What are the common string methods?

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

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

The includes() method is used to determine whether one string is included in another string, returning true or false depending on the case.

The indexOf() method returns the indexOf the specified value that first occurs in the String calling it, searching from fromIndex. If the value is not found, -1 is returned.

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

The padStart() method populates the current string with another string (repeated, if necessary) so that the resulting string reaches the given length. Padding applied from the beginning of the current string (left). (Often used to complement 0 with time)

The replace() method returns a new string that replaces some or all of the matching patterns with 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 that is called on every match.

The original string will not change.

The slice() method extracts a portion of a string and returns a new string, leaving the original string unchanged.

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

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

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).

What is a prototype chain?

Each instance object has a __proto__ attribute on it, pointing to the prototype object of the constructor, the prototype of the constructor

The object is also an object and also has a proto property, so the process of going up from level to level forms a prototype chain.

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. It’s simply a function

The domain can access local variables inside another function.

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

What it does: Extends the scope of variables and allows local variables inside the function to be accessed outside of the function, which is easy to leak because local variables in a closure are never reclaimed

11, What are the common inheritance?

First, prototype chain inheritance

Features: 1, the instance can inherit attributes: instance constructor attributes, the parent class constructor attributes, the parent class prototype attributes. The new instance does not inherit the attributes of the parent instance!

Disadvantages: 1. New instances cannot pass arguments to the parent constructor.

2. Single inheritance.

3. All new instances share the attributes of the parent instance. (Attributes on the stereotype are shared; if one instance modifies the stereotype attribute, the other instance modifies the stereotype attribute as well!)

Second, borrow constructor inheritance

Important: use.call() and.apply() to introduce the superclass constructor into the subclass function (do the self-execution (copy) of the superclass function in the subclass function)

Features: 1, inherit only the attributes of the parent class constructor, not the attributes of the parent class prototype.

2, solve the shortcomings of prototype chain inheritance 1, 2, 3.

3. Can inherit multiple constructor properties (call multiple).

4. In a child instance, you can pass arguments to the parent instance.

Disadvantages: 1, can only inherit the parent constructor attributes.

2. Constructor reuse is not possible. (Call it again every time you use it)

Each new instance has a bloated copy of the superclass constructor.

3. Combinatorial inheritance (combinatorial prototype chain inheritance and borrowed constructor inheritance)

Key points: combine the advantages of the two modes, parameter transfer and reuse

Features: 1, can inherit the attributes of the parent class prototype, can pass parameters, reusable.

2. The constructor properties introduced by each new instance are private.

Disadvantages: the parent constructor is called twice (memory consumption), and the subclass constructor replaces the prototype parent constructor.

Iv. Inheritance of the original type

Important: Wrapping an object with a function and then returning a call to that function makes that function an instance or object that can be added with any properties it wants. Object.create () works this way.

Features: Similar to copying an object, wrapped in a function.

Disadvantages: 1. All instances inherit properties from the stereotype.

2. Reuse cannot be realized. (New instance attributes are added later)

Fifth, class implementation inheritance

Inheritance is implemented through extends and super

Parasitic inheritance

Key points: is to give the original type inheritance outside a shell.

Advantages: No custom type is created, since the shell returns the object (this one), the function becomes the new object created by itself.

Cons: No prototypes, no reuse.

12, the background management system in the authority management is how to achieve?

Login: After the user fills in the account and password, the server verifies whether it is correct. After the verification is successful, the server will return a token. After receiving the token (I will store the token in the cookie to ensure that the login status of the user can be remembered after refreshing the page), The front-end will then pull a user_info interface based on the token to obtain user details (such as user permissions, user names and other information).

Permission verification: Obtains the user’s permission through the token, dynamically calculates the route to the user’s permission based on the user’s permission, and dynamically mounts the route 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 the local cookie, so that we can remember the user’s login status when we open the page or refresh the page next time, so that we do not need to go to the login page to log in again.

Ps: In order to ensure security, all the Expires/ max-age in the background of our company are sessions, which are lost when the browser is closed. Re-opening the browser requires re-login verification. The backend will also refresh the token at a fixed point every week, so that all background users can re-log in once to ensure that background users will not be arbitrarily used due to computer loss or other reasons.

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

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

To start with my main idea of permission control, there will be a routing table at the front, which represents the permissions that each route can access. After the user logs in, the user obtains the role of the user through the token, calculates the route to the user based on the user’s role, and then dynamically mounts the route through router.addRoutes. But these controls are only page level, to put it bluntly, the front end no matter how to do permission control is not absolutely safe, the back end permission verification is not escape.

Our company is now the front end to control the page-level permissions. Users with different permissions display different sidebars and limit the pages they can enter (a little button level permissions control is also done). The back end will verify each operation involving requests and verify whether it has the permissions for this operation. Every backend request, no matter 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 the permission to perform the operation according to the token. If there is no permission, a corresponding status code is thrown, and the front end detects the status code and performs corresponding operations.

Manage routing tables using VUEX, rendering sidebar components based on routes accessible in VUEX.

Concrete implementation:

The VUe-Router is mounted when the Vue instance is created, but the Vue-Router mounts some public pages for login or non-permission purposes.

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

Call router.addroutes (store.getters. AddRouters) to add a route accessible to the user.

Manage routing tables using VUEX, rendering sidebar components based on routes accessible in VUEX.

14. What are the new es6 features?

ES6 is a new version released in 2015. Compared with ES5, this version has made a lot of syntax optimization, such as: new let, const

Let and const have block-level scope and do not have the problem of variable promotion. New arrow function, simplify the definition of function writing, and can skillfully use the arrow function this, (note that the arrow function itself does not have this, its this depends on the external environment), new promise to solve the problem of callback region, new modularization, import, export to achieve import, export. New structural assignment. ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called Destructuring. Added the concept of class classes, which are similar to objects.

15. Why must v-for loop bind key?

Tags on the page are corresponding to the specific virtual DOM object (virtual DOM is js object), loop, if there is no unique key, the page to delete a label, because do not know which one is deleted! So to re-render all the virtual DOM, if you know that the key is X tag is deleted, just need to render the DOM of X tag removed!

16. Why should data in a component be defined as a function rather than an object?

Each component is an instance of Vue. Components share the data property, and when the values of data are of the same reference type, changing one of them affects the others

17. What are the common methods of vertical centralization of boxes? Please give three examples.

It is realized by using the method of locating the parent phase

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

Using Css3’s Transform, it is easy to realize the vertical centering of elements in the case of unknown height and width.

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

flex

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

#center{}Copy the code

What is usually used to achieve cross-domain?

Json:

JSONP has the advantage of simple compatibility and can be used to solve the problem of cross-domain data access in mainstream browsers. The disadvantage is that only support for get methods is limited and insecure and may be subject to XSS attacks.

Declare a callback function whose name (such as show) is passed as a parameter value to the server requesting data across domains, and whose parameter is to fetch the target data (the data returned by the server).

Create a

Once the server receives the request, it needs to do something special: concatenate the name of the function passed in with the data it needs to give you into a string, for example: the name of the function passed in is show, and the data it prepares is show(‘ I don’t love you ‘).

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

CORS: Cross-domain resource sharing (CORS) is a mechanism; When a resource accesses another resource (the resource is placed in

Different domain name or different protocol or port), the resource will make a cross-domain HTTP request that both the browser and the server support;

  1. The entire CORS communication is done automatically by the browser. When the browser discovers that AJAX requests cross sources, it automatically adds additional headers, and sometimes an additional request, but the user doesn’t notice;
  2. The key to implementing CORS is the server, which can communicate across sources as long as it implements the CORS interface
  3. The server handles different requests differently; There are simple and non-simple requests

What is the difference between cookie, LocalStorage and sessionstrorage?

  • Interacting with the server:

    • Cookies are data stored (usually encrypted) on a user’s local terminal by a website to identify the user
    • Cookies are always carried (even if they are not needed) in the same origin HTTP request header and passed back and forth between the browser and the server
    • SessionStorage and localStorage do not automatically send data to the server and only store data locally
  • Storage size:

  • Cookie data is limited by different browsers and cannot exceed 4K in size

  • SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more

  • Term time:

    • LocalStorage stores persistent data. Data is not lost after the browser is closed unless the data is deleted
    • SessionStorage data is automatically deleted after the current browser window is closed
    • Cookie The cookie expiration time is valid regardless of whether the browser is closed

20. What does this point to?

1. In normal functions this refers to window

2. This in the timer points to the window

3. The arrow function does not have this. Its this pointer depends on the external environment.

4. The this in the event refers to the caller of the event

5. The constructor this and the prototype object this refer to the instance of the constructor new

6. This in class refers to an instance object derived from the constructor constructor new

7. This in the self-calling function refers to the window

21, What is recursion, 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, and that function is a recursive function

Advantages: Clear structure, readable

Disadvantages: Low efficiency, call stack overflow, in fact, each function call will allocate space in the memory stack, and the stack capacity of each process is limited, when the call level is too many, will exceed the stack capacity, resulting in stack overflow. – > performance

22. What are the methods you use to optimize your performance?

Reduce the number of HTTP requests, package compressed online code, use lazy loading, use Sprite images, dynamic rendering components, CDN loading packages.

23. Which tag is the vUE instance mounted on?

The vUE instance will be mounted inside the body tag, so we can’t get the body tag in vUE. If we want to use the body tag, we need to get it in the native way

24. What is deep copy and what is shallow copy?

Shallow copy: Creates a new object with an exact copy of the original object’s property values. If the property is a primitive type, it copies the value of the primitive type, and if the property is a reference type, it copies the memory address, so if one object changes the address, it affects the other object.

Deep copy copies all attributes and dynamically allocated memory to which the attributes point. Deep copy occurs when an object is copied along with the object it references. Deep copy is slower and more expensive than shallow copy. The two objects do not affect each other.

25, what is the implementation mechanism of JS?

Js is a single-threaded, asynchronous, non-blocking I/O model, event loop execution mechanism

All tasks can be categorized into two types, synchronous and asynchronous. A synchronous task refers to a task that is queued to be executed on the main thread. The next task can be executed only after the first task is completed. Asynchronous tasks are tasks that do not enter the main thread but enter the task queue. The task queue notifies the main thread that an asynchronous task is ready to execute.

26, Please write at least three methods of array deduplication? (Native JS)

/ / use the filter
function unique(arr) {
  return arr.filter(function(item, index, arr) {
    // Current element, the first index in the original array == current index value, otherwise return current element
    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))
Copy the code
// Use ES6 Set to remove weights.
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", {}, {}]
Copy the code
// Use "for" to nest "for", and then splice to duplicate it (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]){         // The first is the same as the second, and the splice method deletes the second
                    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 and {} not to heavy, two null directly disappeared
Copy the code

27. Write at least two common ways to sort arrays (native JS).

// Quicksort
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 joins two or more arrays; This method does not alter the existing array, but simply returns a copy of the concatenated array.
};
var elements=[3.5.6.8.2.4.7.9.1.10];
document.write(quickSort(elements)); 

Copy the code
// Insert sort
function sort(elements){
    // If the 0th element is an ordered sequence and the first element is an unordered sequence,
    // Insert elements from the unordered array into the ordered array from the first element
    for (var i =1; i<=elements.length; i++) {
        / / ascending
        if(elements[i] < elements[i-1]) {// Insert the ith element in the unordered sequence
            var guard=elements[i];
            // Remember the last position of the ordered sequence, and expand the ordered sequence by one
            var j=i-1;
            elements[i]=elements[j];
            // Ratio size; Locate the inserted element
            while (j>=0 && guard <elements[j]) {
                elements[j+1]=elements[j];
                j--;
            }
            elements[j+1]=guard; / / insert}}}var elements=[3.5.6.8.2.4.7.9.1.10];
document.write('Before calling:'+elements);
document.write('<br>');
sort(elements);
document.write('When called:'+elements);
Copy the code
// 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);
Copy the code

28. Know Lodash? What are the common apis?

Lodash is a consistent, modular, high-performance JavaScript utility library.

_. CloneDeep Deep copy

_. Reject To remove an element based on conditions.

_. Drop (array, [n=1]) Drops the first n elements of an array and returns the rest.

29. What are the HTTP request methods?

Get, POST, PUT, delete, etc

30. Are those tools used for packaging at ordinary times? What’s a 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 (images, fonts, etc.) used in Web development, making the development process more efficient. Webpack has module loaders for different types of resources. The WebPack module packer analyzes the dependencies between modules and generates optimized and merged static resources

Babel allows you to convert syntax that is not currently supported by the browser, and it converts it to a lower version of the syntax for the browser to recognize.

What is a set/map?

A set is a new data structure provided by ES6. It is similar to an array, but the values of its members are unique.

A map is a new data structure provided by ES6. It is similar to an object and also a collection of key-value pairs. However, the range of keys is not limited to strings. In other words, the Object structure provides string-value mapping, and the Map structure provides value-value mapping, which is a more complete Hash structure implementation. If you need key-value data structures, Map is better than Object.

32, what are the methods to clear the float?

The reason for clearing the float is that the floating box falls out of the standard flow, and if the parent box does not set the height, the box below will push up.

1. Extra tag method (add a new tag after the last float tag and set clear: both;) (Not recommended)

2. Parent add overflow attribute (parent add overflow:hidden) (not recommended)

3. Clear float with after pseudo-element (recommended)


    .clearfix:after{/* False elements are normal browser clear float methods for inline elements */ content:"";
        display: block;
        height: 0;
        clear:both;
        visibility: hidden;
    }
    .clearfix{
        *zoom: 1;/* In Internet Explorer 6, only Internet Explorer 6-Internet Explorer 7 executes the */ methodCopy the code

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;
    }

Copy the code

33, What are the common layout methods? What are their strengths and weaknesses?

Common methods of page layout are float, location, Flex, Grid grid layout, and raster system layout

Floating:

  • Advantages: Good compatibility.
  • Disadvantages: Floats can deviate from the standard document flow, so floats need to be cleared. Let’s just work this out.

Absolute positioning

  • Advantages: Fast.
  • Disadvantages: Causes child elements to deviate from the standard document flow, poor usability.

Flex layout (as seen in CSS3)

  • Pros: The flex layout is perfect to address the shortcomings of the above two methods. Mobile basically uses Flex layout.

Grid layout

  • CSS3 introduced layout, very easy to use. The amount of code is much simpler.

An adaptive layout around 300px in the middle using a grid layout

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        html * {
            padding: 0;
            margin: 0;
        }
        /* Important: Set the container to grid layout with a width of 100% */
        .layout.grid .left-center-right {
            display: grid;
            width: 100%;
            grid-template-rows: 100px;
            grid-template-columns: 300px auto 300px;  /* Important: Set the grid to three columns and set the width of each column. Can. * /
        }
        .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">I was left</div>
            <div class="center">
                <h1>Grid layout solution</h1>I am a center</div>
            <div class="right">I am right</div>
        </article>
    </section>
</body>
</html>
Copy the code

Grid system layout

Advantages: It can be used for multi-terminal devices

How to realize lazy loading of pictures?

We set the data-set attribute of the image to the path of the image. Since it is not SRC, no HTTP request will be sent. We then calculate the sum of the height of the page scrollTop and the height of the browser, and if the image coordinates Y from the top of the page (relative to the entire page, not the browser window) are less than the sum, then the image is ready to display (when appropriate, but otherwise). At this point, we can replace the data-set attribute with the SRC attribute.

35. What is the difference between computed and Watch in VUE?

Computed attributes are used to simplify the computational complexity of template strings in the template and prevent the template from being too redundant. It has caching features

Computed is used to monitor self-defined variables, which are not declared in data, but defined directly in computed, and then used for bidirectional data binding on the page to display results or for other processing;

Watch is mainly used to monitor the change of the vue instance, which monitor the variable must be declared in the data can, of course, it can monitor a variable, it can also be an object that is generally used to monitor the routing, the value of the input input box special handling, etc., it is suitable for the scenario is a data affect multiple data, it does not have cache

  • Watch: Monitors the value of the property, and whenever the value of the property changes, it triggers the execution of a callback function to perform a series of operations.
  • Computed: Monitors dependency values. If the dependency values remain the same, it directly reads the cache for reuse, and recalculates only when they change.

In addition, there is a slightly important difference: computed properties cannot perform asynchronous tasks; computed properties must be executed synchronously. This means that computed properties cannot request or perform asynchronous tasks to the server. If an asynchronous task is encountered, it is handed to the listening property. Watch can also detect computed attributes.

36, VUE is how to achieve the parent to the child, child to father, brother between the value?

The parent transmits a value to the child through the props property, which is read-only

<! DOCTYPEhtml>
<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>Parent component passes value to child component --props</title>
    <script src="./js/vue.min.js"></script>
</head>
<body>
    <div id="app">   
        <menu-item title="Value from parent component"></menu-item>
  <! -- Bind custom attributes to child components to receive data from parent components -->
        <menu-item :tit="title"></menu-item>
    </div>
    <script>
Vue.component('menu-item', {props: ['tit'].//props is used to accept values from the parent component
    // The value inside the props is read-only and cannot be changed
    //props is a one-way data flow
    data(){
        return{}},template:'<div>{{tit}}</div>'
})
        var vm=new Vue({
           el:'#app'.data: {title:'I'm the data in the parent component'
           },
           methods: {}});</script>
</body>
</html>
Copy the code

The child passes the value $emit to the parent

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <! -- Parent component -->
    <div :style='{fontSize:fontSize+"px"}'>{{pmsg}}</div>
   <! -- Subcomponent -->
    <menu-item :parr="parr" @aas="blune"></menu-item>
  </div>
  <script type="text/javascript" src="js/vue.js"></script>
  <script type="text/javascript">
    /* Child components pass values to parent components - Basic usage rules for props pass data: unidirectional data flow */
    Vue.component('menu-item', {
     props: ['parr'].data(){
           return {
               msg1:'This is the value passed by the child component.'}},template: ` < div > < ul > < li v - for = "(item, index) in parr: key =" index "> {{item}} < / li > < / ul > < button @ click = 'dd' > expand parent component in font size < / button >  `.methods: {dd(){
           this.$emit("aas".this.msg1)
          } 
      }
    });
 //$emit
    var vm = new Vue({
      el: '#app'.data: {
        pmsg: 'Contents of parent component'.parr: ['apple'.'orange'.'banana'].fontSize: 10
      },
      methods: {
        blune(message){
            this.fontSize+=5;
            console.log(message); }}});</script>
</body>
</html>
Copy the code

The sibling component passes the value event bus

<! DOCTYPEhtml>
<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".'It's a brother's love for his sister.')}},template: ` < div > < button @ click = 'dd' > this is a brother components - {{kk}} < / button > < / div > `.mounted() {
                enveBus.$on('asd'.(result) = > {
                    this.kk = result; }}})); Vue.component('sister', {
            data() {
                return {
                    sis: ' '}},template: ` < div > < button @ click = "cc" > this is a sister components - {{sis}} < / button > < / div > `.mounted() {
                enveBus.$on('bTs'.(message) = > {
                    this.sis = message
                })
            },
            methods: {
                cc() {
                    enveBus.$emit('asd'.'It's a sister's love for her brother.'); }}});var vm = new Vue({
            el: '#app'.data: {},methods: {}});</script>
</body>
</html>
Copy the code

What vuex, tell me your understanding of it?

  1. First of all, VUEX emerged to solve the complex and chaotic problem of value transfer between components in the process of Web component-based development
  2. Putting the data we need to share across multiple components into a store,
  3. To get or format data, use getters,
  4. Changes the data in the store to use mutation, but only includes synchronized operations that are called in specific componentsthis.$store.commit('xxxx')
  5. Actions also change the data in the store, but are mutation submissions, and can include asynchronous operations that are invoked in the componentthis.$store.dispatch('xxx'); Commit (‘ call mutation’) used in actions

What are the methods of data type judgment? What are their strengths, weaknesses and differences?

Typeof, Instanceof, constructor, and toString can be used to determine the data type

Strengths and weaknesses of different types typeof instanceof constructor Object.prototype.toString.call
advantages Using a simple Can detect the reference type Detect almost all types (except null and undefined) All types are detected
disadvantages Only basic types can be detected (null) Basic types cannot be detected and cannot cross iframe Constructor is easily modified and cannot cross iframe In Internet Explorer 6, both undefined and NULL are objects

Do you know symbol?

ES6 introduces a new primitive data type, Symbol, which represents unique values

40, Describe the class in ES6.

Class in ES6 can be thought of as a syntactic sugar for constructors in ES5. It simplifies constructor writing and places the common properties of a class inside constructor

  1. The class keyword is used to create classes whose names are capitalized

  2. Class contains a constructor function that accepts arguments passed in and returns an instance object

  3. The constructor function is automatically called whenever a new instance is generated, and the class generates this function if we don’t write it

  4. Multiple function methods do not need to be separated by commas

  5. Generate instance new cannot be omitted

  6. Syntax specification, create class name without parentheses, generate instance class name with parentheses, constructors do not need function

    1. In inheritance, if you instantiate a subclass to output a method, see if the subclass has the method, and execute the subclass’s method first

    2. In inheritance, if there is no method in the subclass, look for the method in the parent class, if there is, execute the method in the parent class (nearest principle).

    3. If a subclass wants to inherit the methods of its parent class while extending its own methods internally, it calls the constructor of the parent class with super, which must be called before the subclass this

  7. Always be aware of the orientation of this. Use this for all common attributes and methods in the class.

    1. This in constructor refers to the instance object generated from new

    2. Custom methods also refer to instances of new objects

    3. After the event is bound, this points to the event source that triggered the event

    4. Classes do not have variable promotion in ES6, so you must define a class before you can instantiate an object from it

41. What about box models?

In the standard box model, width and height refer to the width and height of the content area. Increasing margins, borders, and margins does not affect the size of the content area, but does increase the overall size of the element 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 some event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which you can get messages for asynchronous operations.

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

.catch()
  • Obtaining exception Information
.finally()
  • Success or failure (not formal criteria)
We use new to build a Promise. The constructor for a Promise takes one argument, which is the function, and passes in two arguments: Resolve and reject indicate the callback function */ after an asynchronous operation succeeds and */ after an asynchronous operation fails


 var p = new Promise(function(resolve, reject){
   //2. This is used to implement the asynchronous task setTimeout
   setTimeout(function(){
     var flag = false;
     if(flag) {
       //3. Normal condition
       resolve('hello');
     }else{
       //4. Abnormal condition
       reject('Wrong'); }},100);
 });
 // 5 After the Promise instance is generated, the then method can be used to specify the Resolved and REJECT callback functions
 // In the THEN method, you can return the data directly instead of the Promise object, and receive the data in the later THEN
 p.then(function(data){
   console.log(data)
 },function(info){
   console.log(info)
 });
Copy the code

What are the differences between VUE-CLI 2.0 and 3.0?

The configuration file of Webpack is hidden in 3.0. If you need to configure it, you need to create a vue.config.js file. 3.0 came out in October 2018

What are the characteristics of the arrow function? Please describe it briefly?

The arrow function does not have its own this, which refers to the external execution environment in which the arrow function is defined

Even a call to call/apply/bind will not change the this of the arrow function

The arrow function itself has no name

Arrow function cannot be new, it will report an error

The arrow function does not have arguments; calling this variable inside the arrow function accesses arguments from the external execution environment

Arrow functions have no prototype

What are the common problems on the mobile terminal and how are they solved?

Click events 300MS delay problem solution: Download the Fastclick package

The H5 page window automatically adjusts to the width of the device and prevents users from zooming in and out of the page

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

Ignore the recognition of email addresses in Android

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

When a website is added to the home screen in quick launch mode, the address bar can be hidden, only for ios safari

<! -- after ios7.0, safari is no longer available -->

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

46, What are the differences between POST and GET requests?

GET: Generally used to obtain information. The URL is used to transfer parameters. The number of messages sent is limited to 2000 characters

POST: Generally used to modify resources on the server. There is no restriction on the information to be sent.

GET uses Request.QueryString to GET the value of a variable, while POST uses Request.Form to GET the value of a variable. GET uses the address bar to GET the value, and POST uses the Form to submit the value.

However, use a POST request in the following cases:

Unable to use cached files (updating files or databases on the server)

Sending large amounts 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 same origin policy is a security mechanism used by browsers to prevent websites from communicating with each other from different sources. The same domain name, protocol, and port are the same.

48. What do HTTP status codes stand for?

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. 4xx indicates that an error occurs on the client (403 Access is prohibited, 404 resources do not exist). 5xx indicates that an error occurs on the server

49. What is BFC?

BFC (block-level formatting context), a box that creates a new BFC is laid out independently and the layout of the elements inside the box does not affect the elements outside the box. Margin overlap occurs between two adjacent boxes in the same BFC in the vertical direction.

BFC is a value browser that creates a separate render region. The layout of all elements in this region does not affect the layout of elements outside the region. This render region only applies to block-level elements

What is the token? (encryption)

  1. A token can also be called a token, and generally consists of uid+time+sign(signature)+[fixed parameter]

    Uid: indicates the unique user id. Time: indicates the timestamp of the current time. Sign: indicates the signatureCopy the code
  2. The token is stored in localStorage, cookie, or sessionStorage on the client. Typically stored in a database on a server

  3. Token authentication process

    After the user logs in successfully, the server returns the Token to the client. After receiving the data, the client saves it in the client. When the client accesses the server again, the token is added to the headers or the server uses the filter to verify each request. If the verification succeeds, the request data is returned; if the verification fails, an error code is returnedCopy the code
  4. Token can resist CSRF, cookie+session cannot

  5. Session status is stored in the server memory or hard disk. When servers are distributed or clustered, session load balancing is a problem. Load balancing In the case of multiple servers, it is difficult to check whether the current user is logged in because the multiple servers do not share sessions

  6. The client logs in and sends the information to the server. After receiving the information, the server encrypts the user information (token) to the client. The client stores the token in a container such as localStroage. The client passes the token on each access, and the server decrypts the token to know who the user is. Through CPU encryption and decryption, the server does not need to store session 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)

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

Basic data type features: Data stored directly on the stack

The characteristics of complex data types: store the object in the stack reference, the real data is stored in the heap memory

52,What happens when a page is loaded and displayed from the time the URL is entered?

01. Search for the IP address corresponding to the domain name (DNS query: Browser cache > System cache > Router cache >ISP DNS cache > root DNS server)

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

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

04. The browser tracks the redirect address and requests another url with WWW

05. Server processing requests (reading resources via route)

06. The server returns an HTTP response (with content-type set to ‘text/ HTML ‘in the header)

07. Browser into the DOM tree construction

08. Browsers send requests for resources embedded in HTML (such as images, audio, video, CSS, JS, etc.)

09. The browser displays the complete page

10. The browser sends an asynchronous request

Security issues: CSRF and XSS attacks?

Cross-site Request Forgery (CSRF) : Cross-site request forgery.

Method 1: Token verification :(most used)

  1. The server sends one to the clienttoken;
  2. The client submits the form with thistoken.
  3. If thetokenInvalid, the server rejects the request.

Method 2: Hide the token:

Hide the token in the HTTP head header.

Method two is a bit like method one, not much different in nature, only in the way it is used.

Method three, Referer verification:

Referer refers to the source of page requests. Only accept requests from this site, the server will respond; If not, intercept

XSS (Cross Site Scripting) : Cross-domain Scripting attacks.

1. The code:

HTML Entity encoding for the data entered by the user.

Convert characters to escape characters as shown in the figure above.

Encode’s function is to transform some characters such as $var ‘, so that the browser in the final output is the same.

Take this code for example:

<script>alert(1)</script>
Copy the code

If nothing is done, the browser executes the ALERT JS operation to implement XSS injection. After encoding processing, L in the browser display result is , implementation of ‘ ‘$var as plain text output, and does not cause JavaScript’ execution.

2. Filtration:

  • Removes event-related attributes entered by the user. Such asonerrorIt automatically triggers an attack, andonclickAnd so on. (Basically, filter out some of the unsafe content)
  • Removes user inputStyleNodes,ScriptNodes,IframeNode. (in particular,ScriptNode, which supports cross-domain, must be removed).

3, correction,

  • Avoid direct confrontationHTML EntityTo decode.
  • useDOM ParseConvert, correct unpairedDOMThe label.

Note: We should learn about DOM Parse, which parses text into A DOM structure.

A more common approach is to convert text through encoding in the first step, then DOM objects in the third step, and then filtering in the second step.

54. Differences between CSRF and XSS

A difference:

  • CSRF: You need to log in to the website firstATo obtaincookie
  • XSS: No login is required.

Difference two :(difference in principle)

  • CSRF: Use the websiteAThe vulnerability itself, to request the siteAtheapi.
  • XSS: Is to the websiteAinjectionJSCode, and then executeJSTo tamper with the websiteAThe content of the.

55. The difference between cookies and sessions

  • 1. Cookie data is stored in the client’s browser, and session data is stored on the server.
  • 2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies
    • Sessions should be used for security reasons.
  • 3. Sessions are stored on the server for a certain period of time. When the number of visits increases, it takes a lot of performance out of your server
    • Cookies should be used to alleviate server performance.
  • 4. The data saved by a single cookie cannot exceed 4K. Many browsers limit the maximum number of cookies saved by a site to 20.
  • 5. Personal suggestions:
    • Store important information such as login information as SESSION
    • Other information can be stored in cookies if needed

56, Call, apply, bind

Common: both can change the direction of this; Call and Apply pass different arguments. Call passes arguments separated by commas. Apply passes bind with arrays. Application scenarios

  1. Call often does inheritance.
  2. Apply is often associated with arrays. For example, using mathematical objects to realize the maximum and minimum values of arrays
  3. Bind does not call the function, but also wants to change the this pointer. For example, change the this pointer inside the timer