This article summarizes and shares 48 front-end high-frequency interview questions (with answer analysis). It will help you sort out the basic knowledge of vue, javascript, etc., and enhance your front-end knowledge reserve. It is worth collecting, come and take a look!
1. What is the principle of vue two-way data binding?
mvvm scenario: In scenarios with a lot of data operations, when a large number of DOM elements need to be used, it will be more convenient to use the open method of mvvm, allowing developers to focus more on data changes. Liberate cumbersome DOM elements
MVVM model,
M data is obtained from the background product data
V view is the written page, every div, every input is a view
VM view model,
data generation Changes will change the display of the view through the view model, and changes in the view will also affect changes in the data through the view model [Related recommendations: vuejs video tutorial, web front-end development]
Core: Regarding VUE two-way data binding, its core is the Object.defineProperty() method.
2. What are the life cycles of vue?
beforeCreate (before creation), created (after creation), beforeMount (before loading) , mounted (after loading), beforeUpdate (before update), updated (after update), beforeDestroy (before destruction), destroyed (after destruction)
mounted The real dom mounting is completed updated as long as the data data is changed. Will automatically update the global timer and custom event that triggers destroy
If keep-alive is used, there will be two more: activated and deactivated. When the component is first loaded, the first 4 life cycles will be executed, respectively. For: beforeCreate, created, beforeMount, mounted
3. What is the difference between v-if and v-show?
Same points: both can control the display and hiding of dom elements
Differences: v-show only changes the display attribute, The dom element has not disappeared. There is no need to re-render the page when switching.
v-if directly delete the dom element from the page. Switching again requires re-rendering the page.
4.What is async await? What does it do?
async await is a new addition to ES7. async is used to declare a function, and await is used to wait for an asynchronous method to complete execution. The async function returns a promise object. You can use the .then method to add a callback function. During the execution of the function, once it encounters await, it will return first. After the asynchronous operation is completed, it will execute the following statement in the function body
5. What are the commonly used methods for arrays? Which methods will change the original array, and which ones will not
# 6. What is the prototype chain?
Each instance object has a proto attribute, which points to the prototype object of the constructor. The prototype object of the constructor is also an object and also has a proto attribute. This is a process of finding it layer by layer. A prototype chain is formed.
#7. What is a closure? What are the advantages and disadvantages of closures?
- Concept: Function nested function, internal variables can access external variables, this variable is called a free variable
- Problem solved: Save variables
- Problems caused: It will cause memory leaks
- Application of closures: anti-shake throttling
8. What are the new features of es6?
- New template string
- Arrow function
- for-of (used to traverse data—such as values in an array.)
- ES6 incorporates Promise objects into the specification and provides native Promise objects.
- Added let and const commands for declaring variables.
- There is also the introduction of the concept of module module
9. Why must the v-for loop bind key?
For each A DOM element plus a key as a unique identifier, the diff algorithm can correctly identify this node, making the page rendering faster!
10. Why should the data in the component be defined as a function instead of an object? ?
Every component is an instance of Vue. Components share data attributes. When the value of data is a value of the same reference type, changing one of them will affect the others
11. What are the common methods of vertically centering boxes? Please give 3 examples.
Use the child-to-father positioning method to achieve
<style>
.container{
width: 300px;
height: 300px;
position: relative;
}
.conter{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
Using the transform of Css3, you can easily achieve vertical centering of the element without knowing the height and width of the element.
<style>
.container{
position: relative;
}
.conter{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
flex
<style>
.container{
display: flex;
justify-content: center;
align-items: center;
}
.conter{
}
</style>
12. What are the js data types and what are the differences
- Basic types: string, number, boolean, null, undefined, symbol, bigInt
- Reference types: object, array
- Basic types are stored in the stack, small space, frequent operations
- Reference data types are stored in the heap , its address is in the stack, generally when we access it it is its address
13. What is symbol
is the new primitive data type Symbol introduced in es6 , representing a unique value
14. What is the same-origin policy
The so-called same-origin policy is a security mechanism of the browser to restrict websites from different origins from being able to Communication (same domain name, protocol, port number)
15.What is promise and what is its function
- promise is an object that can obtain asynchronous operation information from the changed object
- It can resolve callbacks The problem of hell is the asynchronous deep nesting problem
16. What is recursion and what are the advantages and disadvantages of recursion?
- Recursion: If the function can call itself internally, then the entire function is a recursive function. Simple understanding: the function calls itself internally, and this function is a recursive function,
- Advantages: clear structure, strong readability
- Disadvantages: low efficiency, the call station may overflow. In fact, each function call will allocate space in the memory stack, and the content of the stack of each process is limited. . When there are too many levels of calls, the capacity of the stack will be exceeded, resulting in stack overflow
17. What is the difference between let and const
- The let command does not have variable promotion. If used before let, an error will be reported.
- If there are let and const commands in the block area, a closed scope will be formed.
- Duplicate declarations are not allowed
- const defines a constant and cannot be modified, but if it defines an object, the data inside the object can be modified
18.vue performance optimization
- Functional component
- Route lazy loading
- v-for needs to bind the key. The key is the only symbol of the virtual dom, which can help vue dynamically render the page efficiently. When rendering the page The diff algorithm will be used to compare the old and new DOM. When comparing, only the same level will be compared, and no cross-level comparison will be performed. The node where the key changes will be destroyed, and the child nodes will be destroyed first.
- Computed cache data and watch keep-alive cache components
- Do not use v-if and v-for at the same time, v-show is display, and destruction is display-none.v-if is true create.false destroy.
- When designing vue responsive data, the design cannot be too deep. Full recursive calculations will be done.
- The granularity of the components cannot be designed too finely. Reasonable division. The deeper the level, the greater the performance consumption
- Anti-shake throttling
- UI component library is introduced on demand
19..mvvm and mvc
- m (data layer) v (view layer) vm (data view interaction layer) simplifies a large number of DOM operations, is only used for a single page, and displays the view layer through data instead of node operations.
- mvc also needs to obtain dom, so that the page rendering performance is low and the loading speed is slow
- Project optimization that can be said in the interview:
- Don’t design too deep when designing Vue responsive data .Will do full recursive calculations.
- The granularity of the components cannot be designed too finely. Reasonable division. The deeper the level, the greater the performance consumption
20. Routing mode: Hash and history
- Hash has a size limit based on the url parameter passed, and will not be included in the http request and has no impact on the backend at all. Changing the hash will not reload the page; history can be placed in the url Parameters can also store data in a specific object. The solution to the history mode browser white screen is to add a candidate resource covering all situations on the server. The server must have a corresponding mode on the server to use it. If the server does not For configuration, you can use the default hash first.
21.What are the commonly used tags within block and row attributes? What are the characteristics
- Block tags: div, h1~h6, ul, li, table, p, br, form.
- Features: Exclusive line, line wrap display, width and height can be set, blocks and lines can be nested
- Line labels: span, a, img, textarea, select, option, input.
- Features: It can only be displayed within the line, and the content supports the width and height. The width and height cannot be set (except for img, input, textarea, etc.)
##22.= The difference between = and ===
== is equality in a non-strict senseEqual if the values are equal-
= == is equality in the strict sense. It will compare the data type and value size on both sides.Equal only if the value and reference address are equal-
23. Restrictions of strict mode
Variables must be declared before use- The parameters of the function cannot have attributes with the same name, otherwise an error will be reported
- The with statement cannot be used
- Prohibit this from pointing to the global object
-
24.git
git init initializes the warehouse- git clone Clone
- git status Check the file status
- git add. Add the file to the staging area
- git commit -m Description information
-
25.tcp and udp protocols
tcp is more secure and the http protocol is based on tcp- udp is more efficient than tcp and is prone to data loss
-
26. The five states of vuex
mutations (modify the data in the state, but it can only perform synchronous operations, asynchronous must be written in In action) - state (put data)
- action (perform asynchronous operation)
- getter (computed attribute)
- moudel (allows a single store to be split Divide into multiple stores and store them in a single state at the same time)
-
Transmission process
The page submits events to the action asynchronously through mapAction. The action synchronously submits the corresponding parameters to the mutation through commit, and the mutation will modify the corresponding value in the state. Finally, the corresponding value is run out through the getter. In the calculated attribute of the page, the value in the state is dynamically obtained through mapGetter.
27. What is anti-shake and throttling, and how js handles anti-shake And throttling
- First anti-shake is to stop dropping the previous event when the next event is triggered
- Throttling is to trigger the current event Need to set the throttle (timer) after the previous event ends
28. What is redrawing and Reflow
Redraw: When the content and layout of the element have not changed, but only the appearance of the element changes (background-color), it will be redrawn- Reflow: When a part If the content or layout has changed, reflow will occur if the page is rebuilt
- Reflow will definitely cause redrawing, but redrawing does not necessarily cause reflow
-
29.Css Priority
!importent>inline> id> classes, pseudo-classes, attributes>tags, pseudo-element selectors> inheritance and wildcards
30.How Solving box collapse
- Setting the top margin of the parent box
- overflow: hidden
- The child box is off-label
- padding on the parent box
31. Clear the floating method
There are 5 methods in total
- The parent box sets the height
- overflow: hidden
- Pseudo element
- Double pseudo-element
- Add an empty box at the end of the parent box and set clear:both
32. What is the difference between Split() and join()?
- split The string is converted into an array, and the parameter is separated by a certain string.
- join The array is converted into a string. The parameter indicates how the converted string is connected.
33. Array deduplication
1. Use double for loops, and then use the array method splice method to deduplicate (commonly used in es5)
2. Set deduplication: Prepare an array, deconstruct the newset from the array, and prepare a function to store the variables of the array as the judgment value of the function. Return Array.from(new set(arr))
3. Array Method indexof
4. Array method sort Obj[a]-Obj[b]
34. What causes memory leaks
- Improper use of global variables (no declared variables)
- Improper use of closures
- Timers/delays are not cleaned up
- DOM element references that are not cleaned up (dom cleared Or the event is not cleared when deleting)
35. Which hook functions will be triggered when the page is loaded for the first time?
beforeCreate
created Data initialization is completed, the method is also called, but the DOM is not rendered
-
beforeMount
mounted DOM and data are hung before completion
36. What are the five core properties of Vuex?
- ##state => Basic data
##getters => Data derived from basic data (state), equivalent to state Computed attributes mutations => Method to submit changed data, synchronized! actions => Like a decorator, wrapping mutations so that they can be asynchronous. modules => Modular Vuex ##Brief description of the vuex data transfer process-
Page Submit events to action asynchronously through mapAction. The action synchronously submits the corresponding parameters to the mutation through commit, and the mutation will modify the corresponding value in the state. Finally, the corresponding value is run out through the getter. In the calculated attribute of the page, the value in the state is dynamically obtained through mapGetter.
37. The difference between get and post
Same points
The bottom layer of get request and post request is based on TCP/IP protocol. Using either of them, the two-way communication between client and server can be realized. Interaction
The most essential difference
Conventions and specifications:
Specification: Definition GET request is used to obtain resources, that is For query operations, POST requests are used to transmit entity objects and are used for addition, deletion, and modification operations- Convention: GET request splices parameters into the URL for parameter transfer. POST request writes parameters into the request body and transfers
-
- Non-essential difference
The cache is different, get will cache it
The parameter length limit is different, the parameters of the get request are through the URL passed, and the length of the URL is limited, usually 2K; the post request parameters are stored in the request body, there is no size limit - Rollback and refresh are different, get requests can roll back and refresh directly, no It will have an impact on users and programs; if the post request is directly rolled back and refreshed, the data will be submitted again
- Historical records are different, the parameters of the get request will be saved in the history record, but the parameters of the post request will not
- The bookmarks are different. The address requested by get can be saved as a bookmark, but the post will not
-
- 38. Cross-domain
Domain reason: The browser protects resources for security reasons, same-origin policy. (Protocol, domain name, port number)
Solution to cross-domain:- jsonP But you can only use the get principle-set the requested interface to the src attribute of the script tag and pass a function to the background to achieve cross-domain area. The background responds to a function call
- cors: the most commonly used.
- Reverse proxy: The local front end is sent to the local back end and will not cross domain. (Same origin) The local back end receives the request and forwards it to other servers (there will be no cross domain between servers). The proxy is Requires special flags in the path.
-
- 39. The difference between three types of storage
cookie Set expiration time to delete, even if the window or browser is closed
localStorage Large storage capacity, stores persistent data, data will not be lost after closing the browser unless manually deleted - sessionStorage temporary storage, closing the browser will automatically clear the stored content
-
- Storage size:
- The cookie data size cannot exceed 4k
- Although sessionStorage and localStorage also have storage size restrictions, a single cookie is much larger and can reach 5m or more
40.How dom implements communication between multiple tabs in the browser
- websocket.SharedWoeket;
- You can also call local storage such as localStorage and cookies Method; when localStorage is added, modified or deleted in another browser context, it will trigger an event. We listen to the event and control its value to communicate page information;
- Note quirks: Safari is in incognito When setting the localStorage value in mode, a quotaExceededError exception will be thrown
41. Please tell me the usage of each folder and file in the src directory in the vue.cli project?
- The assets folder is for static resources;
- components are square components;
- router is for defining routing-related configurations
- view is a view
- app.vue is an application main component
- main.js is the entry file
42. The difference between $route and $router
router is an instance of VueRouter, which is equivalent to a global router object, which contains many attributes and sub-objects, such as the history object. . . For frequently used jump links, you can use this.$router.push, which is the same as router-link jump.
route is equivalent to the routing object currently being jumped. . You can get name, path, params, query, etc. from it
43. Virtual dom implementation principle
- Use JavaScript objects to simulate the real DOM tree. Make abstraction
- diff algorithm: compare the difference between two virtual trees
- pach algorithm: apply the difference between two virtual DOM objects to the real DOM tree
44. The difference between ordinary functions and arrow functions
- The arrow function has no prototype, the prototype is undefined
- The arrow function this points to the global object, while the function points to the reference object
- The call, apply, and bind methods cannot change the direction of the arrow function
45. How to understand the vue single data flow
The data is always From the parent component to the child component, the child component does not have the right to modify the data passed by the parent component. It can only request the parent component to modify the original data
46.slot slot
- slot slot can be understood as the slot occupies the position in advance in the component template. When reusing components, use the relevant slot When a tag is added, the content in the tag will automatically replace the position of the corresponding slot tag in the component template, serving as an outlet for carrying distributed content
- The main function is to reuse and expand components, and do some customized component processing
47.vue common instructions
- v-model is mostly used for form elements to implement two-way data binding
- v -bind: abbreviated as:, dynamically binds the attributes of some elements, the type can be: string, object or array.
- v-on:click binds a function to the label, which can be abbreviated as @. For example, to bind a click function, the function must be written in methods
- v-for Format: v-for=" Field name in (of) array json" Loop array or json
- v-show display content
- v-else command: Used in conjunction with the v-if command, there is no corresponding value. When the value of v-if is false, v-else will be rendered.
- v-if instruction: The value is true/false, controlling whether the element needs to be rendered.
- v-else- if must be used with v-if
- v-else directive: used with v-if directive, there is no corresponding value. When the value of v-if is false, v-else will be rendered
- v-text Parsing text
- v-html Parsing html tag
- v-bind:class Three binding methods 1. Object type '{red:isred}' 2. Ternary type 'isred?"red":"blue"' 3. Array type '[{red:"isred"},{blue:" isblue"}]'
- v-once only renders once when entering the page and does not render again
- v-cloak prevents flickering
- v-pre puts the elements inside the tag in place Output
48. The role of keep-alive in vue
- < keep-alive> is a built-in component of Vue. The state can be retained in memory during component switching to prevent repeated rendering of the DOM.
- < keep-alive > When wrapping dynamic components, inactive component instances are cached instead of destroying them.
(Learning video sharing: vuejs introductory tutorial, Basic programming video)
The above is the detailed content of [Compiled and shared] 48 front-end high-frequency interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!