Baidu front-end side

foreword

This time, I will mainly record China Information (2023.3.7), Baidu front-end side (2023.3.22 at 11:00 noon), Unicom Digital Technology (3.24 at 1:30 p.m.)

Article directory

conclusion of issue

The difference between vue computed and watch? (Shenzhou information)

1. Calculated attribute computed

Features:

  • Support caching, only when the dependent data changes, the calculation will be recalculated;
  • Asynchronous is not supported, and it is invalid when there are asynchronous operations in computed, and cannot monitor data changes;
  • Computed property values ​​are cached by default, and computed properties are cached based on their responsive dependencies. That is, the value calculated based on the data declared in data or props passed by the parent component;
  • If an attribute is calculated from other attributes, this attribute depends on other attributes to be one-to-one or one-to-one, generally computed is used;
  • If the computed attribute value is a function, then the get method will be used by default, and the return value of the function is the attribute value of the attribute; in computed, the attribute has a get and a set method, and when the data changes, the set method is called;
2. Listening attribute watch

Features:

  • Caching is not supported, and data changes will directly trigger corresponding operations;
  • watch supports asynchronous operations;
  • The monitored function receives two parameters, the first parameter is the latest value; the second parameter is the value before input;
  • When an attribute changes, the corresponding operation needs to be performed, one-to-many;
  • The monitoring data must be the data declared in data or the data in props passed by the parent component. Trigger other operations when the data changes. The function has two parameters:
    immediate: component loading immediately triggers the execution of the callback function;
    deep: deep monitoring; in order to discover the change of the internal value of the object, it is used for complex types of data, for example: objects in the array Changes in content, note: This is not required to monitor changes in the array. Note: deep cannot monitor the changes of the array and the addition of objects. Refer to the vue array mutation, which will be monitored only when triggered in a responsive manner;

Note: This method is most useful when asynchronous or expensive operations need to be performed when data changes, which is the biggest difference from computed.

For details, please see the difference between computed and watch in Vue and the detailed explanation of application scenarios

The difference and principle of vue-router routing mode?

hash mode:

  1. The character "#" will appear in the url path
  2. The hash value is not included in the Http request, it is handled by the front-end routing, so when the hash value is changed, the page will not be refreshed, and no request will be sent to the server, so this is also a must for single-page applications.
  3. The change of the hash value will trigger the hashchange event
  4. When we perform a refresh operation, or directly enter the browser address, the hash route will be loaded to the page corresponding to the address bar, and the history route will generally report a 404 error (refresh is a network request, and an error will be reported when there is no back-end preparation).

history mode:

  1. history uses the history stack of the browser. There were back, forward, and go methods before, and then the pushState() and replaceState() methods were added in HTML5. They provide the function of modifying the history, but they are being modified , although the current URL is changed, the browser will not immediately send a request to the backend.
  2. This mode of history requires background configuration support. For example: when we are on the home page of the project, everything is normal and can be accessed, but when we refresh the page or directly access the path, it will return 404, that is because in the history mode, we only dynamically operate window.history through js To change the path in the browser address bar, there is no http request, but when I directly enter this address in the browser, I must initiate an http request to the server, but this target does not exist on the server, so will return 404

Principle:
The principle of HashRouter:
Obtain the hash value in the new URL through the window.onhashchange method, and then do further processing

The principle of HistoryRouter:
using history.pushState to do page jump will not trigger page refresh, use window.onpopstate to monitor the forward and backward of the browser, and then do other processing

Vue-router common interview questions

promises in js?

Promise of Xingye Digital Gold

Pending (in progress, initial state, neither successful nor failed.), Resolved (completed, also known as Fulfilled), Rejected (failed) There are only two ways to change the three states: the asynchronous operation has never been
completed pending => completed resolved asynchronous operation never completed pending => failed rejected once the status is changed, it cannot be changed again, which is also the origin of its name promise-promise, a promise object can only be changed once

What is Promise, the three states of Promise

The point of this in js?

  1. The this in the global object points to window
  2. This in the global scope or ordinary function points to the global window
  3. In the case of not an arrow function, this water far points to the object that called it last
  4. The new keyword changes the direction of this
  5. apply, call, bind can change the direction of this, not an arrow function
  6. The this in the arrow function, its pointing has been determined when it is defined.
    The arrow function does not have this, see if there is a function in the outer layer, if there is this in the outer function, if not, it is window
  7. The this in the anonymous function always points to the window. The execution environment of the anonymous function is global, so this points to the window

Prototype and prototype chain in js?

Prototype: Each function has a prototype attribute, called a prototype. Because the value of this attribute is toxic, it is also called a prototype object
Function: store some attributes and methods; implement the inheritance prototype chain in JS
: each object has a _proto_, which points to its prototype prototype object; its prototype The prototype object has another _proto_, pointing to its prototype prototype object, and so on until it finally finds the prototype of the top-level object Object. This query path is the prototype chain.

How to dynamically load JS scripts? (My Baidu side)

There are 4 ways to dynamically load JS scripts

Vue's image lazy loading?

Lazy loading is lazy loading (also known as on-demand loading).

The specific performance is: when we visit the page, first replace the path of the img picture with the path of a placeholder image, so that only one request is required, and when the picture enters the visible area, the path of the picture is replaced with the real one Path, so as to display the picture and achieve the effect of lazy loading. (That is: lazy loading is to use the same placeholder image to occupy the place, and then obtain the real path of the picture on demand, so as to achieve lazy loading)

The technical principle is: first hide the src attribute of img, and store its real address in the custom attribute of the img tag (eg: data-src), when the picture enters the visible area, change the real path from data- src and replace it back to display the picture.

Advantages: fast page loading speed, reduce the pressure on the server side, save traffic

Lazy loading of routes

Routing Lazy Loading: When building apps in packages, JavaScript bundles can become very large, affecting page load. If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the route is accessed, it will be more efficient.
eg:

const UserDetails = () => import('./views/UserDetails')

The principle of lazy loading (on-demand loading) is divided into two steps:

  • Package the submodules that need to be lazy loaded into independent files (children chunk)
  • Use functions to implement lazy execution of submodule loading code
    detailed routing lazy loading

One-way data flow in vue?

  • In vue, the principle of one-way data flow needs to be followed.
    Under the premise of passing from parent to child, the data occurrence of the parent component will notify the child component to automatically update.
    Inside the child component, the props passed by the parent component cannot be directly modified => props are read-only

The actual performance of one-way data flow in Vue is: when the data in the Model changes, the value in the View will be modified one-way, and when the value in the View changes, the Model will not perceive it. The practical application is v-bind one-way data.
Compared with one-way data flow, two-way data binding means that more View changes will be notified to the Model layer. That is, the specific implementation of MVVM. No matter the value in Model or View changes, it will be notified to the other party through ViewModel to achieve synchronization. The practical application is v-model two-way data binding.

The advantage of one-way binding is that it can bring one-way data flow. The advantage of this is that all state changes can be recorded and tracked, and state changes are notified through manual calls. The source is easy to trace, and there is no "black box operation". At the same time, there is only one entry and exit for component data, which makes the program more intuitive and easier to understand, and is conducive to the maintainability of the application. The disadvantage is that the amount of code will increase accordingly, and the data transfer process will become longer, resulting in many similar boilerplate codes. At the same time, due to the strict requirements for the independent management of the application state (single global store), when dealing with scenarios with more local states (such as "rich form" applications with more user input and interaction), it will appear wordy and cumbersome.

Basically, the advantages and disadvantages of two-way binding are the mirror images of one-way binding. The advantage is that it simplifies a large number of business-independent codes in the scenario where there are many bills of delivery. The disadvantage is that due to "black-box operations", we cannot track the change of the bureau or state (although in most cases we don't care: most of the potential behaviors also increase the difficulty of debugging when errors occur. At the same time, because the source and entry of component data changes There may be more than one, and novice players can easily mess up the direction of data flow. If there is a lack of "control" means, it is easy to cause an application avalanche due to a wrong operation.

What problem does Vuex solve?

1. When we use Vue to develop projects, we often pass parameters through routing. Too many parameters will cause 400 Bad Request. Vuex can solve this problem.
2. Solve the problem that the simplicity of one-way data flow is easily destroyed when multiple components share state.
3. Solve the problem that multiple views depend on the same state.
4. Solve the problem that when there is too much data in medium and large projects, only need Change the processing data in vuex without going to each page to change

The principle of Vuex?

The core of every Vuex application is the store, which includes:
(1) state (data): used to store data sources, which is the public state;
(2) getters (data processing): sometimes data sources need to be processed, Return the required data;
(3) actions (event): the operation to be performed, which can be performed synchronously or asynchronously
(4) mutations (execution): after the operation is completed, actions update the state data source through commit (synchronous operation)
(5) modules: use a single state tree, so that all the states of the application are concentrated into one large object, so the partial state of each module is subpackaged so that each module has its own state, mutation, action, getters, and even nested sub module;

The workflow of vuex is:
(1) Submit an action through dispatch,
(2) After actions receive this event, some asynchronous|synchronous operations can be performed in actions, and distributed to different mutations according to different situations, (3
) ) actions to trigger mutations through commit,
(4) mutations to update state data, after the state is updated, it will notify vue to render

The basic principle of webpack packaging?

The principle of webpack packaging is to statically analyze the dependencies between files, and generate static resources from these modules according to the specified rules. When webpack processes the program, it will recursively build a dependency graph, which contains each required by the application. Modules, package all these modules into one or more bundles.

The entire packaging process of webpack:

  1. Read the configuration parameters of webpack;
  2. Start webpack, create a Compiler object and start parsing the project;
  3. Start parsing from the entry file (entry), find the imported dependent modules, recursively traverse the analysis, and form a dependency tree;
  4. Use the corresponding Loader to compile the dependent module files of different file types, and finally convert them into Javascript files;

Multi-process of browser and single thread of js?

Browser (multi-process)
The browser is multi-process. Taking Chrome as an example, every time a tab page is opened, a process will be generated. If Chrome opens many tab pages and does not close them, the computer will become more and more stuck. It's CPU's sake.

What processes are included in the browser:
Chorme browser needs at least 1 browser process, 1 GPU process, 1 network process, and 1 rendering process from closing to starting, and then opening a new page, a total of 4 processes.
If you open a new tab page later: the browser process, GPU process, and network process are shared and will not be restarted. Then, by default, a rendering process will be configured for each tab page, but there are exceptions, such as from page A Open a new page B in it, and if A and B belong to the same site, A and B will share a rendering process, and in other cases, a new rendering process will be created for B. Therefore, the latest Chrome browser includes
: 1 browser main process, 1 GPU process, 1 network process, multiple rendering processes, and multiple plug-in processes

The single thread of JS is related to its purpose. As a browser scripting language, the main purpose of JavaScript is to interact with users and manipulate the DOM. This determines that it can only be single-threaded, otherwise it will bring very complicated synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to a certain DOM node, and the other thread deletes this node. At this time, which thread should the browser take as the standard, so this is a contradiction, and it is JS. The function determines that it is a single-threaded language.

For details, see JS (single-thread) and browser (multi-process)

Scope and scope chain in JS

Scope: It is the range in which a variable or function can act.

  1. Global scope: Any variable that is not declared in a function or in curly braces is in the global scope, and variables declared in the global scope can be accessed anywhere in the program.
  2. Function scope: Function scope is also called local scope. If a variable is declared inside a function, it is under a function scope. These variables can only be accessed inside the function, not outside the function.
  3. Block-level scope: ES6 introduces the let and const keywords. Unlike the var keyword, variables declared using let and const in curly braces exist in block-level scope. These variables cannot be accessed outside of the curly braces.

Scope chain: When searching for a variable, it will first search from the variable object of the current scope. If it is not found, it will search from the variable object of the parent scope (upper environment), and always find the variable of the global scope. Object, that is, the global object. Such a linked list composed of variable objects with multiple scopes is called a scope chain. It consists of a series of variable objects of the current environment and the upper environment, which guarantees the orderly access of the current execution environment to variables and functions that meet the access rights.
Understand Javascript scope and scope chain

How many ways to implement horizontal and vertical centering of elements? (code topic)

Short-answer publish-subscribe model? (code question)

JS variable type? (Another classmate's Baidu side-by-side face-to-face classics)

Value type: simple data type/basic data type, when storing, the variable stores the value itself, so it is called a value type

string, number, boolean, undefined, null, Symbol
reference type: complex data type, only the address (reference) is stored in the variable during storage, so it is called reference data type

Objects created by the new keyword (system objects, custom objects), such as Object, Array, Date, etc.
to determine the data type

Introduce let and const

Can a constant declared with const be modified?

Arrow functions and attributes?

1. Different shapes: Arrow functions are defined by arrows, which are not found in ordinary functions.
2. Arrow functions are all anonymous functions: ordinary functions can have anonymous functions or named functions
3. Arrow functions cannot be used in constructors: ordinary functions can be used in constructors to create object instances.
4. The direction of ths in the arrow function is different: in ordinary functions, ths always points to the object that calls it, if it is used as a constructor, it points to the created object instance.
5. The arrow function does not have an arguments object: every ordinary function call has an arguments object, which is used to store the actual passed parameters. But
arrow functions don't have this object.
6. Other differences: Arrow functions do not have prototype prototype objects. Arrow functions do not have super. Arrow function does not have new.target

The difference between undefined and null?

The difference between undefined and null data types

How to hide elements in css?

(1) display:none disappears + rearranges + redraws + binding events do not trigger + no transition;

(2) visibility: hidden exists + no rearrangement + redrawing + binding events are not triggered + there is a transition;

(3) opacity: 0 exists + no rearrangement + not necessarily redrawing + triggers self-binding + transition;

(4) position:absolute removes the line of sight;

(5) z-index: Negative values ​​are covered by other elements;

(6) transform:scale(0,0) Scale the element to 0 Exist + binding event does not trigger.

JS event loop mechanism?

Event loop mechanism

Cross-domain? Solution to cross domain?

Cross-domain issues
are developed with Vue, and a project is started locally. The local browsing address is localhost:8080, which is a common address, but the interface written on the back end, including its address, is definitely not under this localhost:8080 , then there is actually a cross-domain situation at this time. Generally, the means of dealing with cross-domain in practice is to use the webpack_dev-server provided by the webpack to provide us with the target attribute. When we use this target attribute again, it will be It can be transferred to our target server, which is a means of dealing with cross-domain. The reason why webpack can solve cross-domain is that the local writing project is actually written on localhost, and webpack will set up a local server locally, that is, It is said that this server and our front-end localhost:8080 conform to the same-origin policy, and the request is sent to the proxy server of the middle layer of webpack. The server provided by the middle layer of webpack and the back-end server actually do not have cross-domain problems. Let it ask the back-end server, and after getting the data, it will be passed to our front-end by the middle layer.

How to configure cross domain in webpack?

devServer: {
    
    
    proxy: {
    
    
      '/api': {
    
    
        target: 'http://localhost:8989', // target: 表示代理到的目标地址
        secure: false, // 如果是https接口,需要配置这个参数
        changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
        ws: true,
        pathRewrite: {
    
    
          '^/api': '' // 自定义
        }
      },
    }
  } 

What does the http304 status code mean?

The network status response code is a 3-digit code used to indicate the HTTP response status of the web server. If the request status code starts with 1, it is a temporary response, 2 generally means success, 3 means redirection, 4 means client error, and 5 means server error. Common response status codes include: 200 (success), 301 (permanent redirection), 302 (temporary redirection), 304 (unmodified), 400 (bad request), 401 (unauthorized), 403 (forbidden), 404 (Not Found), 500 (Internal Server Error), 503 (Service Unavailable)

The whole process of browser caching:
the browser loads the resource for the first time, the server returns 200, the browser downloads the resource file from the server, and caches the resource file and response header for comparison during the next loading; when loading the resource next time
, Since the mandatory cache has a higher priority, first compare the time difference between the current time and the last time 200 was returned. If it does not exceed the max-age set by cache-control, it has not expired and hits the strong cache, directly reading resources from the local. If the browser does not support HTTP1.1, use the expires header to determine whether it has expired;
if the resource has expired, it indicates that the mandatory cache has not been hit, then start negotiating the cache, and send a message with If-None-Match and If-Modified- Since request;
after receiving the request, the server first judges whether the requested file has been modified according to the Etag value. If the Etag value is consistent, there is no modification, and the negotiation cache is hit, and 304 is returned; if it is inconsistent, there is a change, and the new resource is returned directly Bring a new Etag value to the file and return 200;
if the request received by the server does not have an Etag value, compare If-Modified-Since with the last modification time of the requested file, and if they match, hit the negotiation cache and return 304; inconsistent Then return the new last-modified and file and return 200;

What happens after the user enters a url?

1. Enter the URL in the address bar of the browser and press Enter
2. The browser checks whether there is a cache for the current URL, and compares whether the cache has expired
3. DNS resolves the IP corresponding to the URL
4. Establishes a TC connection according to P (three-way handshake)
5 , HTTP initiates the request
6, the server processes the request, the browser receives the HTTP response
7, renders the page, builds the DOM tree
8, closes the TCP connection (waves four times)

Simulate a queue with two stacks? (code topic)

What are the new features of ES6? (Unicom Digital)

Summary of ten new features of front-end ES6

What are the three states of promise?

What routes are used in the project?

Global route guard: As long as the route changes, the guard can monitor it.

  • beforeEach : Global pre-guard,
  • beforeResolve: Global resolution guard, to ensure that the resolution guard is called correctly before the navigation is confirmed, and after the guard and asynchronous routing components in all components are resolved.
  • afterEach: A global after guard, useful for analytics, changing page titles, declaring pages for accessibility, and many other things.

Route exclusive guard: only responsible for guarding one route, beforeEnter;

Component routing guard: only responsible for the guard of a single component.

  • beforeRouteEnter (called before the corresponding route that renders the component is validated);
  • beforeRouteLeave (called when navigating away from the corresponding route that rendered this component);
  • beforeRouteUpdate (Called when the current route changes, but the component is reused).
    Application scenario: In the online shopping mall project, every step of the routing jump needs to determine whether the user is logged in. Only when the user logs in can he jump to other pages. If the user does not jump, he can only go to the login page. At this time It is necessary to use the global routing guard. If the user wants to view the successful payment page, he must first go to the payment page to make the payment, instead of jumping directly from the home page to the successful payment page, then an exclusive routing guard is required.

What happens when you enter a url?

js event loop mechanism?

Guess you like

Origin blog.csdn.net/qq_40992225/article/details/129937413