Front end common interview questions!!! Ultra detailed

Time:2020-3-26

It’s said that adults’ self-esteem is paid. I haven’t had it for more than two months. Hahaha
The epidemic affected a lot of small partners who had been broken and left their jobs. Here are some common interview questions. You can share them with me, programmer Xiaobai. If you have any questions, please feel free to give me some advice~~

1. What can front-end optimization do?
2. What is the difference between HTTP and HTTPS?
3. The understanding, advantages and disadvantages of Ajax?
4. What is MVVM?
5. What is the difference between V-IF and v-show?
6. Summarize life cycle hook function
7. Five core concepts of vuex
8. Vue route hook function
9. What will cause cross domain and how to solve it?
10.hash and history?
11. Content distribution of Vue
12. What is the difference between deep copy and shallow copy?
13. V-text, v-html (key), v-pre differences and usage
14. Principle of Vue bidirectional binding
15. Analysis of the function of for loop structure traversal array and key
16. Hook function parameters
17. How to customize instruction instructions?
18. Pass values from parent-child components and non parent-child components
19. What’s the difference between calculated calculation attribute and method method?
20. Is there a difference between gradual enhancement and graceful degradation?
21. What’s the difference between cookies, sessionstorage and localstorage?
22. Clear float
23. What is a closure, how to use it, and why?
24. What is the difference between JavaScript host object and native object?
What’s the difference between call and apply?
26. What’s the difference between = = and = = =?
27. What’s the difference between HTTP and HTTPS?
28. Throttling and anti shaking
29. What do you know about the new syntax of ES6?
30. What’s the difference between get and post?

1、 What can front-end optimization do?

1. Reduce HTTP requests:
Merge JS and CSS files (packaged with webpack or other packaging tools)
Sprite map is used for small pictures (for the pictures and UI, just give them to the UI for making)
Use Base64 for simple pictures

2. CDN for content distribution network
CDN is mainly used for static files, such as CSS, JS and flash.
CDN, automatically find the nearest physical machine server to download web components

3. JS and CSS
Use jsmint and gzip to simplify files, CSS simplification technology points: optimize﹒ 606, extract CSS, JS public methods, use 0 instead of 0px

4. Resource volume reduction
Gzip compression
JS confusion
CSS compression
Picture compression

5. Image loading processing
Picture lazy loading
Display of progress bar when loading the first screen

Lazy loading details: first, set a relatively simple picture to the SRC of the picture, then set the real address of the picture to a custom attribute, make a placeholder, and then set a listening event for the picture. Once the picture reaches the viewport range, get the real address from the custom attribute of the picture, and then assign it to SRC for loading.
Display of progress bar when loading the first screen: if you are not satisfied with the optimized data volume of the first screen, and you cannot further shorten the length of the first screen package, you can use the progress bar to remind users to wait.

6. Mobile optimization
Long list scrolling optimization
Function anti shake and function throttling
Use touchstart and touchend instead of Click
Viewport settings for HTML

Long list scrolling: IOS scrolls locally as much as possible, Android scrolls globally as much as possible. At the same time, WebKit overflow scrolling: touch needs to be added to the body to optimize the scrolling of mobile segments

Anti shake: stop frequent sliding or repeated clicking. The action will not be executed until n milliseconds have passed. If the action is called again within n milliseconds, the execution time will be recalculated.

Throttling: set an execution cycle in advance. When the time to call an action is greater than or equal to the execution cycle, the action will be executed, and then enter the next new cycle.

Touch start and touch end replace Click: click will have a 300ms delay in the mobile terminal, and the order of event execution is touch start – > touch move – > touch end – > Click
HTML viewport settings: can prevent the page from scaling, to optimize performance.

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

1. HTTPS protocol needs to apply for Certificate in Ca, generally there are few free certificates, so it needs a certain fee.
2. HTTP is hypertext transmission protocol, information is plaintext transmission, and HTTPS is SSL encrypted transmission protocol with security.
3. HTTP and HTTPS use totally different connection methods and different ports. The former is 80 and the latter is 443.
4. The connection of HTTP is very simple and stateless; HTTPS protocol is a network protocol constructed by SSL + HTTP protocol that can carry out encrypted transmission and identity authentication, which is safer than HTTP protocol.

3、 What are the advantages and disadvantages of Ajax?

AJAX is a method that can request background data without refreshing the page. It sends asynchronous request to the server through XMLHttpRequest object, obtains data from the server, and then operates DOM through JS to update the page content.
Implementation process:
1. Create an XMLHttpRequest object
2. Set callback function in response to HTTP request
3. Create an HTTP request, specify the response request method, URL, parameters, etc
4. Send HTTP request
5. Get the data returned by the server
6. Use js to operate DOM to update the content of the page
Disadvantages:
1. Not friendly to search engine
2. It costs a lot to implement the backward and forward functions under Ajax
3. Restrictions on cross domain issues

4、 What is MVVM?

M. What do V and VM stand for?

m model

Data layers in Vue are all in data

V view view

View in Vue is our HTML page

VM (view model) controller connects data with view layer

VM is Vue instance is VM

Conclusion:

1. MVVM divides the whole project into three parts

2. Vue instance VM is the bridge between data model data and view template view

3. When the data changes, VM will inform the view to change

4. When the view changes, if V-model is used, it will notify the data change

5. Summary: the principle of MVVM code writing
(1) Only data, not DOM structure of view
(2) Data and view correspond one by one
(3) Don’t manipulate DOM, but manipulate data
(4) Because the data is responsive
(5) As long as the data changes, the view will naturally change

MVVM is to abstract the state and behavior of the view. Let’s separate the view UI and business logic. It can take out the data of the model and help to deal with the business logic involved in the view due to the need to display the content
MVVM mode is the same as the previous MVC mode. Its main purpose is to separate (view) and (model). It has several advantages:

  1. Low coupling. View can be changed and modified independently of model. A ViewModel can be bound to different views. When the view changes, the model can remain unchanged. When the model changes, the view can also remain unchanged.
  2. Reusability. You can put some view logic in a view model and make many views reuse this view logic.
  3. Independent development. Developers can focus on business logic and data development (ViewModel), designers can focus on page design, using expression blend can easily design interface and generate XAML code.
  4. Testable. The interface is always more difficult to test, but now the test can be written for ViewModel.
5、 What’s the difference between V-IF and v-show?

V-IF is a “real” conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch.

V-IF is also inert: if the condition is false at the time of initial rendering, nothing is done – the conditional block will not start rendering until the condition first becomes true.

V-show, by contrast, is much simpler – no matter what the initial conditions are, elements are always rendered and simply switched based on CSS.

In general, V-IF has higher switching overhead, while v-show has higher initial rendering overhead. Therefore, if you need to switch very frequently, it is better to use v-show; if the conditions are unlikely to change at run time, it is better to use V-IF.

6、 Summarize life cycle hook functions

1. Beforecreate: after instance initialization, the * * data observer * * and event / watcher events are called before configuration. Note that before, data, watcher and methods are all missing.

At this time, there is nothing in the Vue instance, but the $route object exists. Redirection and other operations can be performed according to the routing information.

2. Created: called after the instance has been created. In this step, the instance has completed the following configuration: Data observer, property and method operation, and watch / event event callback. However, the mount phase has not yet begun and the $El attribute is not currently visible.

At this time, this. $data can be accessed, and watcher, events, and methods also appear. If data and methods are dynamically changed according to the background interface, it can be used.

3. Beforemount: called before mount, and the related render function is called for the first time. But render is executing, and DOM cannot operate at this time. I printed the Vue instance object at this time. Compared with the created life cycle, there is only one more $El attribute. However, its value is undefined,

The data needed for page rendering should be assigned before that.

4. Mounted: called after mounting. In this step, create VM. $el and replace el, and mount it to the instance.

At this point, the element has been rendered, and the DOM dependent code is here ~ for example, listening to DOM events.

After the 5.beforeUpdate:$vm.data update, the virtual DOM is called before it is re rendered and patched.

You can further modify $VM. Data in this hook, which does not trigger additional re rendering.

6. Updated: the virtual DOM is called after re rendering and patching.
When the hook is called, the data of the component DOM has been updated, so you can now perform DOM dependent operations. But do not modify the data at this time, or the two lifecycles of BeforeUpdate and updated will continue to be triggered and enter the dead cycle!

7.beforeDestroy: before the instance is destroyed, it is called. At this step, the instance is still fully available.

The instance will be destroyed. Do something before it is destroyed~

After the 8.destroyed:Vue instance is destroyed, it is called. At this time, everything indicated by the Vue instance has been unbound, all event listeners have been removed, and all sub instances have been destroyed.

There are not many things that can be done at this time. You can only add some hints such as toast.

Note: hook functions such as beforemount, mounted, BeforeUpdate, updated, beforedestroy and destroyed are not called during server-side rendering.

7、 Five core concepts of vuex

Vuex is a state management architecture specially designed for vue.js application, which manages and maintains the changeable state of each Vue component (you can understand some data in the Vue component).

Vue has five core concepts: state, getters, transitions, actions, modules. Next, I will sort out these five core concepts.

State = > basic data

Getters = > data derived from base data

Iterations = > submit the method of changing data, synchronization!

Actions = > like a decorator, package transitions so that they can be asynchronous.

Modules = > modular vuex

State

State is the basic data in vuex!

State provides a unique public data source, and all shared data should be stored in the state of the store

Vuex uses a single state tree, that is, one object contains all the state data. As a constructor option, state defines all the basic state parameters we need.
Get the vuex property in the Vue component
We can get the state of vuex through Vue’s computed, as follows:
Front end common interview questions!!! Ultra detailed
Whenever the store.state.count changes, the calculated properties are re evaluated and the associated DOM is updated.

Mapstate helper

When a component needs to obtain multiple states, it will be redundant to declare these states as calculation properties. To solve this problem, we can use the mapstate helper function to help us generate the calculated properties and let you press the key a few times less.
Front end common interview questions!!! Ultra detailed
When the name of the mapped calculated attribute is the same as the name of the state’s child node, we can also pass a string array to mapstate.
Front end common interview questions!!! Ultra detailed
Object expansion operator

The mapstate function returns an object. How can we mix it with local computed properties? In general, we need to use a utility function to merge multiple objects into one, so that we can pass the final object to the computed attribute. But since we have the object expansion operator, we can greatly simplify the writing method:
Front end common interview questions!!! Ultra detailed
Object operator

… the spread operator allows an expression to expand somewhere. The expansion operator can be used where there are multiple parameters (for function calls) or elements (for array literals) or variables (for deconstructing assignments).

Expansion operators cannot be used in objects, because currently expansion operators can only be used in traversable objects. The implementation of iterables relies on the [symbol. Iterator] function. At present, only array, set and string have the [symbol. Iterator] method built-in, but object has not the method built-in, so the expansion operator cannot be used. However, the object expansion operator feature has been added to the ES7 draft.
Example:
Front end common interview questions!!! Ultra detailed
Object expansion operators in draft ES7

Expansion operators for objects are not yet supported in ES6, but will be in ES7. The object expansion operator allows us to operate objects more quickly, as shown in the following example:
Front end common interview questions!!! Ultra detailed
Component remains local

Using vuex doesn’t mean you need to put all the states into vuex. Although putting all the states into vuex makes the state changes more explicit and easy to debug, it also makes the code tedious and non intuitive.

If some states strictly belong to a single component, it is better to treat them as local states. You should weigh and determine according to your application development needs.

Two ways for components to access data in state
The first way:
Front end common interview questions!!! Ultra detailed
The second way:
Front end common interview questions!!! Ultra detailed

getters

That is, the state derived from the state of the store.

Getters receive state as its first parameter and other getters as its second parameter. If not required, the second parameter can be omitted as follows:
Front end common interview questions!!! Ultra detailed
Just like state, we can get the getters of vuex through Vue’s computed.
Front end common interview questions!!! Ultra detailed
The mapgetters helper function simply maps getters in the store to local calculated properties, similar to state
Front end common interview questions!!! Ultra detailed
If you want to take a getter property by another name, use the object form:
Front end common interview questions!!! Ultra detailed

mutations

Committing a mutation is the only way to change the state in the store in vuex.

The mutation must be synchronous, and action is required if it is to be asynchronous.

Each station has a string event type and a callback function (handler). This callback function is where we actually make the state change, and it will accept state as the first parameter and submit the load as the second parameter. (commit load should be an object in most cases), commit load can also be omitted.
Front end common interview questions!!! Ultra detailed
You cannot call a mutation handler directly. This option is more like event registration: “this function is called when a mutation of type increment is triggered.” To wake up a mutation handler, you need to call the store.commit method with the corresponding type:
Front end common interview questions!!! Ultra detailed
How to submit Object Styles

We can also use this method to submit objects with the type attribute.
Front end common interview questions!!! Ultra detailed

Mutations are subject to Vue’s response rules

It’s best to initialize all the required properties in your store in advance.

When you need to add new properties to an object, you should

Use vue.set (obj, ‘newprop’, 123), or

Replace old objects with new ones. For example, using the object expansion operator, we can write state. Obj = {… State. Obj, newprop: 123}

Mapmutations helper function

Similar to other helper functions, you can use this. $store. Commit (‘xxx ‘) to submit a mutation in the component, or use mapmutations helper function to map methods in the component to store. Commit call (need to inject store in the root node).
Front end common interview questions!!! Ultra detailed

actions

Action is similar to mutation, with the following differences:

Action submits a mutation, not a direct change of state.

An action can contain any asynchronous action.

Let’s end actions with the following example:
Front end common interview questions!!! Ultra detailed
Note: the action function accepts a context object with the same methods and properties as the store instance, so you can call context.commit to submit a mutation, or get the state and getters through context.state and context.getters.

*Distribute actions

The action is triggered by the store.dispatch method:
Front end common interview questions!!! Ultra detailed

*Other places like residences
Actions supports the same load mode and object mode for distribution:
Front end common interview questions!!! Ultra detailed

*Mapactions helper

You can use this. $store. Dispatch (‘xxx ‘) to distribute the action in the component, or use mapactions auxiliary function to map the methods of the component to the store. Dispatch call (you need to inject the store in the root node first):

import { mapActions } from ‘vuex’
export default {
//..

methods: {

...mapActions(\[
'incrementn' // map this. Incrementn() to this. $store. Dispatch ('incrementn ')
\]),
...mapActions({
    Add: 'incrementn' // map this. Add() to this. $store. Dispatch ('incrementn ')
})

}
}

Modules

Using a single state tree causes all the states of the application to be centralized into a large object. However, when the application becomes large, the store object becomes bloated.

To solve these problems, vuex allows us to split the store into modules. Each module has its own state, mutation, action, getters, and even nested submodules – similar segmentation from top to bottom:
Front end common interview questions!!! Ultra detailed
Local state of the module

For the mutation and getter inside the module, the first parameter received is the local state of the module. For the getter inside the module, the root node state will be the third parameter:
Front end common interview questions!!! Ultra detailed
Similarly, for the action within the module, context.state is the local state, and the state of the root node is context.rootstate:
Front end common interview questions!!! Ultra detailed

In summary, statemutionactiongetter
State: all shared data should be stored in the state of the store
Mutation: used to modify data in the store
Action: because asynchronous code cannot be written in transitions, action is required. It is used to process asynchronous tasks
Getter: it is used to process new data in the store. Note that it does not change the data in the state, but only serves as a wrapper, which is equivalent to calculating attributes

Vuex is a technology which needs to be used when dealing with complex parent-child communication.
Some constants can be defined in state. Getters write the method to trigger state change. Getters are usually used less.
There are also two places to store methods: actions and moments. One is asynchronous and the other is synchronous. We usually use moments to store some methods. In the page, you can usethis.$store.commit()Method to trigger transitions, which changes the value in state.

8、 Hook function of Vue routing

The navigation hook provided by Vue router is mainly used to intercept the navigation and let it complete jump or cancel.

There are three types of route hooks: global, single route exclusive, or component level

Global hook: it mainly includes beforeeach and aftereach. This kind of hook is mainly used to determine permissions and operations to be performed when pages are lost. Generally written in main.js

The beforeeach function has three parameters:
-To: routing object to be entered by router
-From: route the current navigation is about to leave
-Next: function, a hook in the pipeline. If the execution is finished, the navigation status is confirmed; otherwise, it is false, and the navigation is terminated.

You can use router.beforeeach to register a global before hook
router.beforeEach((to, from, next) => { // … })
After hook has no next method and cannot change the navigation
router.afterEach(route => { // …})

In the project:
1. Global hook
Front end common interview questions!!! Ultra detailed
2. Hooks in a single route
It is mainly used to write the logic to be executed when a specified route jumps
Front end common interview questions!!! Ultra detailed
3. Hooks in components (not much is used)
It mainly includes beforerouteenter, beforerouteupdate and beforeroutleave. These hooks are written in the component and can also pass three parameters (to, from, next). Their functions are similar to the previous ones
Front end common interview questions!!! Ultra detailed

9、 What causes cross domain and how to solve it?

Four character mantra: homology strategy
Front end common interview questions!!! Ultra detailed
The cross domain problem is caused by the same origin policy implemented by the browser for security. The same origin policy restricts documents and scripts from different sources. The same origin means that the domain name, protocol and port of two URLs should be identical

Solve cross domain
1.JSONP

Jsonp is a common method of cross source communication between server and client. The biggest feature is simple application, good compatibility (compatible with the lower version of IE). The disadvantage is that it only supports get requests and does not support post requests.

Core idea: the web page requests JSON data from the server by adding a < script > element. After the server receives the request, it puts the data in the parameter position of a callback function with a specified name and sends it back.

1) Native implementation:
Front end common interview questions!!! Ultra detailed
2) Vue.js implementation:
Front end common interview questions!!! Ultra detailed

2.CORS cross domain(most used at present)
Common cross domain request: only the server can set access control allow origin, and the front end does not need to be set
If cross domain request with Cookie: both front and back end need to be set

[front end setting]
Judge whether there is cookie according to xhr.withcredentials field

1) Native Ajax implementation
Front end common interview questions!!! Ultra detailed
2)vue-resource
Front end common interview questions!!! Ultra detailed
3)axios
Front end common interview questions!!! Ultra detailed

[server settings]
The server supports CORS mainly by setting access control allow origin. If the browser detects the settings, it can allow Ajax cross domain access.

3.Set document.domain to solve the problem of unable to read cookies of non homologous web pages
Because the browser checks whether the two pages are of the same origin through the document.domain attribute, so as long as the same document.domain is set, the two pages can share cookies (this scheme only applies to cross domain scenarios with the same primary domain and different sub domains)
Front end common interview questions!!! Ultra detailed

4.Cross document communication API: window. Postmessage()
Call the PostMessage method to implement the parent window http://test1.com to send messages to the child window http://test2.com (the child window can also send messages to the parent window through this method)

It can be used to solve the following problems:

Data transfer of the page and the new window it opens
Message passing between multiple windows
Page and nested iframe messaging
Cross domain data transfer of the above three scenarios
Front end common interview questions!!! Ultra detailed
Call the message event to listen for messages sent by the opposite party
Front end common interview questions!!! Ultra detailed

10、 What is the difference between hash and history?

Spa needs the ability to update the page without refreshing the page, which requires the introduction of front-end routing. In fact, the front-end routing uses the hash or history attribute of the browser.

Hash: (more compatible)

Although hash (the later part of the URL) appears in the URL, it will not be included in the HTTP request and has no impact on the back end at all, so changing hash will not reload the page.

When the hash changes, the hashchange event will be triggered. Listen for the event and update the page.

            window.onhashchange = function() {

Document. Getelementbyid (“demo”). InnerHTML = x; / / update page content

                ……

            };

history :

History takes advantage of the new pushstate () and replacestate () methods in the HTML5 history interface. These two methods are applied to the browser record stack,

Based on the existing back, forward and go, they provide the function of modifying the history (pushstate directly pushes the incoming URL into the history stack, and replacestate replaces the incoming URL with the current history stack).

Only when they perform the modification, the browser will not immediately send the request to the backend, although the current URL is changed.

The pushstate(), replacestate() methods receive three parameters: stateobj, title, URL

History. Pushstate ({color: “red”}, “red”, “red”); / / set the state

Window.onpoppstate = function (event) {/ / listening state

                     if(event.state && event.state.color === “red”) {

Document. Body. Style. Color = “red”; / / update page content

                      }

                }

//Change state * when using the history API to change the URL of the browser, additional steps are needed to trigger the popstate event, such as calling methods such as history. Back() and history. Forward()

                history.back();

                history.forward();

History vs. hash

History advantages:

The URL set by pushstate can be any URL under the same source, while hash can only modify the later part, so it can only set the URL of the current URL and the same document.

The new URL set by pushstate can be the same as the current URL, which will also add the record to the stack; the new value set by hash cannot be the same as the original one, and the same value will not trigger the action to add the record to the stack.

Pushstate can add any data type to the record through the stateobject parameter; hash can only add short strings.

Pushstate can set additional Title Properties for later use.

History disadvantage:

When history refreshes the page, if there is no corresponding response or resource in the server, 404 will appear. Therefore, if the URL does not match any static resources, you should return the same index.html page, which is the page your app depends on.

In the hash mode, only the previous content is included in the HTTP request. For the back end, even if there is no comprehensive coverage of the route, it will not report 404.

11、 Content distribution of Vue

Putting the content of the parent component in the specified location of the child component is called content distribution or slot
The most important feature of components is reusability, and good use of slots can greatly improve the reusability of components

1. Single slot:
Front end common interview questions!!! Ultra detailed
Front end common interview questions!!! Ultra detailed

2. Multiple slots are also called named slots: a named slot is to insert the content of a name into the corresponding name of a sub component
Different styles of content can be realized, and elements can be bound through the name attribute in the slot

The difference between a named slot and an anonymous slot:
Named slot has a name
Anonymous slot has no name

Named slot usage
Slot with name
Binding elements using the “name” attribute in < slot >
Specified by the slot attribute. The value of this slot must correspond to the name value of the following slot component. If it does not match, it will be placed in the anonymous slot

It should be noted that the same name values are replaced with each other. Since the name is not specified by slot, the slot label without the name attribute in the subcomponent will be replaced
Front end common interview questions!!! Ultra detailed

3. Scope slot
The action slot allows you to pass a template to the slot instead of passing a rendered element. It is called a scope slot because although the template is rendered in the parent scope, it can access some of the child data.

Scope slot usage scenario
Scope slot is used when a sub component does a circular display list or a part is passed in from the outside
Processing from parent component to child component
It can not only reuse the slots of sub components, but also make the content of slots inconsistent
Front end common interview questions!!! Ultra detailed

12、 Deep copy and light copy

Shallow copy and deep copy are only for complex objects such as object and array,
Difference: shallow copy only copies the first level attributes of the object, and deep copy can recursively copy the attributes of the object

In short, deep copy is mainly to copy the attribute value of another object, and the attribute value of another object will not be affected, because at this time, it has opened its own memory area in the heap, which is free from external interference.
Shallow copy mainly copies the reference value of an object. When you change the value of an object, the value of another object will also change.

13、 V-text, v-html (key), v-pre differences and usage

The output of v-text is plain text, which will not be HTML parsed by browser

V-html will output it when the HTML tag is parsed

V-pre displays the original information to skip the compilation process

Some static content can be rendered faster without compiling and pre instruction

14、 Principle of Vue bidirectional binding

The key points are the get method and set method under object. Defineproperty (obj, ‘MSG’, {})
Front end common interview questions!!! Ultra detailed

15、 The function of key when for loop structure traverses array

1) Key to make a unique identification for each node

2) Key is mainly used to update virtual DOM efficiently and improve performance

Note: V-IF and V-for are not recommended to be used together. When used, V-for has a higher priority than V-IF.

16、 Hook function parameters

When it’s time, we don’t need to operate it, and it will trigger by ourselves
With a life cycle
Front end common interview questions!!! Ultra detailed

17、 Custom instruction
  1. The built-in instructions of Vue may not be enough for development. At this time, we can consider our own custom instructions
  2. Syntax < div V – name of instruction = value “> < / div >

Front end common interview questions!!! Ultra detailed
For example, custom properties
Front end common interview questions!!! Ultra detailed

18、 Pass values of parent-child components and non parent-child components

Pass value from parent component to child component — basic usage
Front end common interview questions!!! Ultra detailed
Example:
Front end common interview questions!!! Ultra detailed

Pass value from child component to parent component — basic usage
Front end common interview questions!!! Ultra detailed
The function value obtained from the parent component by the child component is as follows:
Front end common interview questions!!! Ultra detailed
The function value obtained from the parent component by the child component is obtained by method 2:
Front end common interview questions!!! Ultra detailed
Pass value from child component to parent component: (in $ emit (‘function name in parent component ‘, value to be passed), use the passed value in function fn in methods in parent component
Front end common interview questions!!! Ultra detailed

Value transfer between non parent and child components
How to communicate between brothers

Data transfer between brothers requires the help of event center to transfer data through event center
Provide event center var hub = new vue()

Passing the data party, triggering the hub. $emit (method name, passed data) through an event
Receive the data party and trigger the hub. $on() method name in the mounted() {} hook

(to change who, write mounted in who, so that through this, you can change the data in who)

The destroy event cannot pass data after it is destroyed by the hub. $off() method name
Front end common interview questions!!! Ultra detailed
If the trigger event passes a value, there should be (parameter) corresponding to it in the listening event parameter

Destroy event function, which needs to be defined in brother’s father methods

19、 The difference between computed calculation attribute and method method

The calculation attribute in computed can be written in method. The difference is that method calls need to add () while computed doesn’t

Return must be added to computed
The method in computed is not triggered by events, but when the property (must be the property in data) changes, the current function will be triggered

The biggest difference is that there is a cache in computed, and the same value will directly take the cached value to improve performance, but the method has no cache, and the same value will be retrieved again

20、 The difference between gradual enhancement and elegant degradation

Progressive enhancement
Build the page for the low version browser to ensure the most basic functions, and then improve the effect, interaction and other additional functions for the advanced browser to achieve a better user experience.

graceful degradation
Build the full functionality at the beginning, and then make it compatible with lower versions of browsers.

Difference:

1. Elegant degradation starts from the complex status quo and tries to reduce the supply of user experience

2. Progressive enhancement starts from a very basic and functional version, and is constantly expanded to meet the needs of the future environment

3. Degradation (functional degradation) means looking back, while incremental enhancement means looking forward while keeping its foundation in a safe place

21、 What’s the difference between cookies, sessionstorage and localstorage?

Sessionstorage and localstorage are provided by HTML5 web storage API, which can easily save data between web requests. With local data, you can avoid unnecessary data transfer back and forth between browser and server. Sessionstorage, localstorage and cookies are all data stored on the browser side. The concept of sessionstorage is very special, and a concept of “browser window” is introduced. Sessionstorage is the data that always exists in the same window (or tab) of the same origin. That is to say, as long as the browser window is not closed, even if the page is refreshed or another page of the same origin is entered, the data still exists. When the window is closed, sessionstorage is destroyed. At the same time, different “independent” windows, even the same page, sessionstorage objects are also different cookies will be sent to the server. The other two won’t.

Cookies: there is a limit on the maximum number of cookies generated under each specific domain name. IE and opera will clean the cookies that are used least in the near future. Firefox will randomly clean the cookies

Sessionstorage: it is used to locally store the data in a session. These data can only be accessed by pages in the same session. When the session ends, the data will also be destroyed. It is session level storage.

Localstorage: used for persistent local storage. Data will never expire unless it is actively deleted.

22、 Clear float

1. Use an empty label to clear the float. This method is to add an empty label after all floating labels to define CSS clear: both. The disadvantage is to add meaningless labels.
2. Use overflow. Add the CSS attribute overflow: Auto; zoom: 1; zoom: 1 to the parent tag that contains floating elements for IE6 compatibility.
3. Use the after pseudo object to clear the float. This method is only applicable to non IE browsers. Pay attention to the following points in use. 1、 In this method, the height: 0 must be set for the pseudo object that needs to clear the floating element, otherwise the element will be several pixels higher than the actual one; secondly, the content attribute is required, but its value can be empty, and the value of the content attribute is set to “,” empty is also allowed.
4. Floating external elements

23、 What is a closure, how to use it, and why?

A package is a function that can read internal variables of other functions. In JavaScript language, only the sub function inside the function can read the local variable, so the closure can be simply understood as “a function defined inside a function”.

So, in essence, closure is a bridge that connects the inside and outside of a function. Closures can be used in many places. It can be used to read variables inside a function and keep the values of these variables in memory.

Note on using closures:

  • Because closures can save variables in functions in memory, which consumes a lot of memory, closures cannot be abused, otherwise it will cause performance problems of web pages and memory leakage in ie. The solution is to delete all unused local variables before exiting the function.
  • The closure changes the value of the variable inside the parent function, outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variable as its private value, you must be careful not to change the value of the internal variable of the parent function.

(for details about closures, please see [JavaScript scope and closure details] (https://www.cnblogs.com/syfwh…)

24、 What’s the difference between a JavaScript host object and a native object?

Native object
Ecma-262 defines native objects as “objects provided by ECMAScript implementation independent of the host environment”.
What does “local object” contain: object, function, array, string, Boolean, number, date, regexp, error, evalerror, rangeerror, referenceerror, syntaxerror, typeerror, urieror.
It can be seen from this that, in a simple way, a local object is a class (reference type) defined by ecma-262.

Built-in object
Ecma-262 defines the built-in object as “all objects provided by ECMAScript implementation and independent of the host environment, which appear when ECMAScript program starts executing”. This means that developers don’t have to instantiate built-in objects, it’s already instantiated.
It is also “independent of the host environment”. By definition, it seems difficult to distinguish “built-in object” from “local object”. Ecma-262 only defines two built-in objects, namely, global and math (they are also local objects. According to the definition, each built-in object is a local object). So it can be understood. A built-in object is one of the local objects.

Host object
What is “host object”? Mainly in the concept of “host”, the “host” in ECMAScript is certainly the running environment of our web page, namely “operating system” and “browser”.
All non local objects are host objects, which are provided by the host environment implemented by ECMAScript.All BOMs and DOMS are host objects.Because it shows different content for different “hosting” environments. Actually speaking,The officially undefined objects of ECMAScript belong to the host object, because most of the undefined objects are created by the ECMAScript program itself.

25、 What’s the difference between call and apply?

Call method:
Syntax: Call (thisobj, object)
Definition: calls a method of one object to replace the current object with another.
Note: call method can be used to call a method instead of another object. Call method can change the object context of a function from the initial context to a new object specified by thisobj. If the thisobj parameter is not provided, the global object is used as thisobj.
Apply method
Syntax: apply (thisobj, [argarray])
Definition: apply a method of one object and replace the current object with another.
Description: if argarray is not a valid array or is not an arguments object, a typeerror will be caused. If neither argarray nor thisobj parameters are provided, the global object will be used as thisobj and no parameters can be passed.

For both apply and call, they work the same, but they have the following parametersDifference
The meaning of the first parameter is the same, but for the second parameter: apply, an array of parameters is passed in, that is, multiple parameters are combined into an array, and call is passed in as the parameter of call (starting from the second parameter). For example, the application corresponding to func.call (func1, VAR1, var2, var3) is func.apply (func1, [VAR1, var2, var3]). The advantage of using apply at the same time is that the arguments object of the current function can be directly passed in as the second parameter of apply.

26、 What’s the difference between = = and = = =?

==Equality equals, = = identity equals. = =, when the value types on both sides are different, type conversion should be performed first and then comparison. ====, do not do type conversion, different types must be different.

27、 What’s the difference between HTTP and HTTPS?

The data transmitted by HTTP protocol is unencrypted, that is, clear text. Therefore, it is very insecure to transmit privacy information by HTTP protocol. In order to ensure that these privacy data can be encrypted for transmission, Netscape company designed SSL (secure sockets layer) protocol to encrypt the data transmitted by HTTP protocol, thus HTTPS was born. In short, HTTPS protocol is a network protocol constructed by SSL + HTTP protocol that can carry out encrypted transmission and identity authentication, which is more secure than HTTP protocol.

The differences between HTTPS and HTTP are as follows:

1. HTTPS protocol needs to apply for certificate from Ca, generally there are few free certificates, so it needs a certain fee.

2. HTTP is hypertext transmission protocol, information is plaintext transmission, and HTTPS is SSL encrypted transmission protocol with security.

3. HTTP and HTTPS use totally different connection methods and different ports. The former is 80 and the latter is 443.

4. The connection of HTTP is very simple and stateless; HTTPS protocol is a network protocol constructed by SSL + HTTP protocol that can carry out encrypted transmission and identity authentication, which is safer than HTTP protocol.

28、 Throttling anti shake

Anti shake: the callback is executed N seconds after the event is triggered. If it is triggered again in this N seconds, the timing will be re timed. A typical case is to input the search: the search request is made N seconds after the input is finished, and the content entered in N seconds will be re timed.
Front end common interview questions!!! Ultra detailed
Throttling: it is specified that in a unit time, only one function can be triggered. If multiple functions are triggered in this unit time, only one function will take effect. A typical case is that the mouse is constantly clicked to trigger. It is specified that multiple clicks in N seconds only take effect once.
Front end common interview questions!!! Ultra detailed

29、 What do you know about the new syntax of ES6?

Arrow function:
var foo = function(){return 1;};
/ / equivalent to
let foo = () => 1;
*This in the arrow function refers not to window, but to the object itself.

let、const
ES6 recommends using let to define variables in functions
Const is used to declare a constant, but it is not immutable
Let and const are only valid in the nearest block (in curly braces)

let
Only variables declared by let keyword have block level scope, and variables declared by VAR do not have block level scope.
1) No variable promotion
2) Temporary dead zone

Variables declared by let will be bound to this block level scope and will not be affected by the outside world

var  tmp  \=  123;

if (true) {

   console.log(tmp)

 let  tmp=456;

}

At this time, the printed TMP is undefined because the curly bracket is locked and the let has no variable promotion, so it is undefined

const
Declare a constant. A constant is a variable whose value (memory address) cannot be changed
1) When a constant is declared, it must be assigned immediately after it is declared
2) Since it’s a constant, you can’t reassign it. If it’s a basic data type, you can’t change the value. If it’s a complex data type, you can’t change the address value

Let’s talk about the difference between var let const:
  • The variable declared with VAR has the scope within the function where the statement is located, and there is variable promotion
  • The variable declared by let has the scope within the code block where the statement is located, and there is no variable promotion
  • Const is used to declare a constant. The value must be given during declaration. The value of the constant cannot be modified in the code that appears later

Front end common interview questions!!! Ultra detailed

Destructuring assignment
Deconstruction assignment is an efficient and concise assignment method in ES6
Front end common interview questions!!! Ultra detailed

Template string
ES6 provides the use of backquotes’ to create strings, which can contain ${ }
Front end common interview questions!!! Ultra detailed

for…of && for…in
For… Of traversal (array)
Front end common interview questions!!! Ultra detailed
For… Properties in traversal objects
Front end common interview questions!!! Ultra detailed

Promise

  • ES6 has native support for project. A project is an object waiting to be executed asynchronously. When it is executed, its status will become resolved or rejected
  • Promises is a mode of dealing with asynchronous operations, which has been implemented in many three-party libraries before, such as the deferred object of jQuery. When you initiate an asynchronous request and bind event handlers such as. When(),. Done(), etc., you are actually applying promise mode

Front end common interview questions!!! Ultra detailed

Expand operator
Enables you to expand a literal object into multiple elements
Front end common interview questions!!! Ultra detailed

async/await
The async function returns a promise object, so when the outermost layer cannot get its return value with await, we should use the original method:then()Chain to handle the promise object, like this

Await can be used to wait for the return value of an async function

If it doesn’t wait for a promise object, the result of an await expression is what it waits for.

If it waits for a promise object, await is busy. It will block the following code, wait for the promise object to resolve, and then get the value of resolve as the result of the await expression.

Seeing the word “blocking” above, I feel flustered Rest assured, that’s why await has to be used in async functions. Async function calls do not cause blocking, and all the internal blocking is encapsulated in a promise object and executed asynchronously.

Set and map

set

It is similar to an array, but the values of the members are unique and there are no duplicate values.
Set itself is a constructor to generate set data structure
const s = new Set();

const arr = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1];
const set = new Set();
arr.forEach(item => set.add(item));
console.log(set);  // 1, 2, 3, 4, 5
//Fast array de duplication
console.log([...new Set(arr)]);  //[1, 2, 3, 4, 5]

map
Object is a collection of key value pairs, similar to JSON objects, but key can be not only a string but also an object

var map = new Map();
Var obj = {Name: 'small edge', age: 14};
Map. Set (obj, 'xiaoyuanmao');
Map. Get (obj); // xiaoyuanmao
map.has(obj); // true
map.delete(obj) ;// true
map.has(obj); // false
30、 What’s the difference between get and post?

In fact, get and post are essentially the same. They are all request methods in HTTP protocol: the underlying implementation is based on TCP / IP protocol. The so-called difference is that the browser manufacturers make different restrictions according to the agreement.

(1) When using get request, the parameters are displayed in the URL, but when using post request, they are not displayed;
(2) Post transfers a large amount of data, which can reach 2m, while get can only transfer about 1024 bytes due to the restriction of URL length
(3) For get requests, you need to pay attention to caching. For post requests, you don’t need to worry about this problem;
(4) The content type value of post request must be set to application / x-form-www-urlencoded;
(5) When sending a request, because the parameters of the get request are all in the URL, the parameters sent by the send function are null, while the parameters of the post request need to be given when using the send method;
(6) The data requested by get mode will be cached by the browser, so other people can read the data from the history of the browser, such as account and password. In some cases, get will bring serious security problems. Post can avoid these problems relatively.

Finally, I recommend an article about the interview. I think it’s well written A kind of https://blog.csdn.net/u012551…