The latest front-end interview questions in 2023-interview collection summary experience (with answers) is being continuously updated~~

Table of contents

Facing actual combat:

1. Self-introduction

2. Introduce the projects that the front-end familiar technology has done

3. How to answer "why did you leave your previous company" during the interview?

Interview questions:

1. HTML articles

1. What tags are added in HTML5?

2. What is the specific difference between inline elements and block-level elements?

​3. List several common block elements, inline elements and inline elements?

​4. Briefly describe the difference between readyonly and disabled

5. Why do HTML5 web pages only need to be written?

6. What is the difference between HTML5 storage types?

7. Website TDK three major label SEO optimization 

2. CSS articles

​1. Briefly explain the difference and usage between CSS link and @import?

2. What is the difference between the transparency effects of rgba and opacity?

3. Display and hide elements?

​4. Who are several positioning layouts position and relative and absolute relative to?

5. Draw a straight line of 0.5px with CSS3?

6. Draw a triangle with CSS3?

7. CSS3 box model

8. Float

9. Flex layout

​10. CSS plane conversion

​11. "Son and Father" in CSS

​12. The box is centered in CSS3

​13. Positioning stacking order z-index in CSS3

​14. Selector weight in CSS3

​15. Transition in CSS3

​16. Structural pseudo-class selectors and pseudo-element selectors in CSS3

3. HTML&CSS Mixed Articles

​1. The difference between Localstorage, sessionStorage and cookie

2. How to realize the layout of double flying wings (holy grail)? 

​3. What is the difference and function of double colon and single colon in ::before and ::after? 

​4. What are the similarities and differences between the alt and title of img, and the principle of lazy loading of images?

5. What is BFC? 

4. JavaScript

1. JS data type

2. What is the difference between an arrow function and a normal function?

​3. What is the judgment method and difference between null and undefined in JS?

4. Prototype chain

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

6. What is the function of keep-alive?

7. Understanding of closure?

8. Implementation of nextTick

9. Mix in the mixin principle

​10. List methods related to array operations

​11. What is the difference between typeof and instanceof? 

​12. What is the difference between "===" and "==" in js?

​13. How to use native JavaScript to bind two onclick events to a button?

5. Vue articles

1. What is a front-end construction tool? For example (webpack of Vue2, Vite of Vue3)

2. Six ways of communication between Vue components

(1) Parent components pass values ​​to child components

(2) Child components pass values ​​to parent components (in the form of events)

3. Understanding and usage scenarios of Vuex

​4. The life cycle of vue has eight stages

5. Briefly describe the principles and differences between MVVM and MVC?

6. Vue common commands

7. Why is the data in vue a function? What role does it play? 

6. Solutions to browser compatibility issues:

1. What is browser compatibility?

2. Question 1: The default external patch and internal patch of labels in different browsers are different

3. When we lay out horizontally, we are used to setting float for block-level elements, and then when their spacing is set with margin, the margin value displayed under IE6 is larger than the set value

4. When the height of the label is set less than 10px, the height in IE6 and IE7 will exceed the height you set

5. The picture has spacing by default

6. Margin overlap problem: When margin margins are set for two adjacent elements, margin will take the maximum value (margin collapse)

7. Two block-level elements, the parent element is set to overflow: auto; the child element is set to position: relative; and the height is greater than the parent element, it will be hidden instead of overflowing in IE6 and IE7

8. There is a gap under the picture under IE6

9. Cursor:hand display hand type is not supported on qq browser and Google

10. The problem of margin value on both sides of IE


Facing actual combat:

1. Self-introduction

  • Introduce yourself (short introduction)
  • Technical Leader (Vue2, Vuex, Vue-Router, Vue3, Vite, ts, Pinia, React, etc.)
  • Project experience
  • Teamwork and communication skills (separation of front and back ends)

In short, it is to maximize strengths and avoid weaknesses: show your value, and start by briefly introducing your name and background. You can mention your technical expertise, project experience, teamwork and communication skills, and work experience.

2. Introduce the projects that the front-end familiar technology has done

  • Project Background: First, briefly describe the background and purpose of the project you are involved in. Explain what the project is, what problem it solves, and its business or technical importance.

  • Technology stack: List the main technology stack and tools you use in the project. This includes programming languages, frameworks, libraries, and other related technologies. Explain why you chose these technologies and their role in the project.

  • Features and Modules: Briefly describe the main features and modules of the project. Describe the specific parts of the project that you are responsible for and how you will collaborate with the team to develop these features and modules.

  • Technical Highlights: Emphasize some technical highlights in the project or challenges you encountered in the project. This could be a technical problem you solved, performance optimization, cross-browser compatibility, or responsive design.

  • Outcomes and Impacts: List the outcomes and impacts of the project. This could be growth in user numbers, improvement in user feedback, improved website performance, etc. If supported by specific data or statistical results, it can better demonstrate the value of the project.

  • Learn and Grow: Share what you've learned and grown through the project. Describe the challenges you encountered in the project and how you overcame them and learned new knowledge and skills.

  • Self-evaluation: Finally, conduct a self-evaluation of your contributions and experience in the project. Highlight the role you played in the project, as well as your passion and commitment to front-end development.

Make sure to present your point of view concisely and communicate well with the interviewer when presenting the project. Provide practical examples and specific details to support your introduction. Also, be prepared to answer project-related questions and demonstrate your in-depth knowledge of the project.

3. How to answer "why did you leave your previous company" during the interview?

    During the interview, you are often asked why you left the original company. When you are an interviewer, you will basically ask this question when interviewing others. If the interviewer answers how bad the previous company was, including the chaotic management of the original company, it is generally not appropriate, because it will make the new unit feel that this person does not know how to be grateful, does not know how to analyze the reasons from himself, and will only shirk if there are problems responsibility.

   There have also been interviewers who said that because of interpersonal relationships, it can only mean that this person is not good at communicating with others, and it is a taboo for hiring. And if you answer that the previous company was good, then you can’t clearly express the reason for leaving; since the original unit is good, then you still leave? It seems to be clearly deceiving.

Recommended visit: Front-end interview: If the interviewer asks why he left the previous company-爱码网

Interview questions:

1. HTML articles

1. What tags are added in HTML5?

(1) Layout tab: 

(2) Multimedia label: video (video)

audio (audio)

  

(3) Other tags: canvas (canvas), progress (progress bar), meter (meter)

(4) Supplement: HTML5 new attributes:

hidden (hidden element), required (required), minlength (minimum length), maxlength (maximum length), pattern (regular expression), placeholder (prompt text), autocomplete (automatic filling), autofocus (automatic focus)

The advantages of semantics are as follows:

  • The code structure is clear, easy to read, and conducive to development and maintenance
  • It is convenient for other devices to parse (such as screen readers) to render web pages according to semantics.
  • Good for Search Engine Optimization (SEO)

2. What is the specific difference between inline elements and block-level elements?

(1) Block-level elements occupy a row of page space exclusively, and will not share a row of page space with other elements

(2) Inline elements can share a row of page space with other non-block-level elements (inline, inline block)

3. List several common block elements, inline elements and inline elements?

(1) Block elements:

(2) Inline elements: a, span, em(i), strong(b), u

 (3) Inline block elements:

4. Briefly describe the difference between readyonly and disabled

(1) readyonly is to set the form element as read-only

(2) disabled is to set the form element to the disabled state

5. Why do HTML5 web pages only need to write <!DOCTYOE HTML>?

The doctype in HTML 4.01 requires a reference to a DTD because HTML 4.01 is based on SGML.

And HTML 5 is not based on SGML, so there is no need to reference the DTD,

But doctype is needed to regulate browser behavior.

Among them, SGML is Standard Generalized Markup Language. Simply put, it is an older standard than HTML and XML. Both of them are developed from SGML, but HTML5 is not.

6. What is the difference between HTML5 storage types?

        HTML5 can store data locally, which was previously used by cookies. HTML5 provides the following two local storage solutions: localStorage is used for persistent local storage, and the data will never expire and will not be lost even when the browser is closed. sessionStorage Only pages in the same session can be accessed and the data will be destroyed when the session ends. Therefore, sessionStorage is not a persistent local storage, but only a session-level storage.

7. Website TDK three major label SEO optimization 

2. CSS articles

1. Briefly explain the difference and usage between CSS link and @import?

link is an XHTML tag, in addition to loading CSS, you can also define other things such as RSS;

@import belongs to the category of CSS and can only load CSS.
When link refers to CSS, it will be loaded at the same time when the page is loaded;

@import requires the page to be loaded after the page is fully loaded.
link is an XHTML tag, no compatibility issues;

@import was proposed in CSS2.1, and browsers with lower versions do not support it.
link supports using Javascript to control DOM to change styles; @import does not.

2. What is the difference between the transparency effects of rgba and opacity?

opacity will inherit the opacity attribute of the parent element

The descendant elements of the element set by RGBA will not inherit the opacity property.

3. Show and hide elements?

(1) display:none hides the corresponding element, no space is allocated to it in the document layout, and the elements on each side of it will be closed, as if it never existed.
(2) visibility:hidden hides the corresponding element, but still retains the original space in the document layout.

4. Several positioning layouts position and relative and absolute are relative to whom are they positioned?

(1) relative: relative positioning, positioning relative to its own position in the normal document flow.


(2) absolute: Absolute positioning is generated, and positioning is performed relative to the parent element whose positioning is not static at the nearest level.


(3) fixed: Generate absolute positioning, positioning relative to the browser window or frame. (Old versions of IE do not support)


(4) static: the default value, no positioning, the element appears in the normal document flow. (Rarely used)
(5) sticky: Generate sticky positioned elements, and the position of the container is calculated according to the normal document flow. (Rarely used)

5. Draw a straight line of 0.5px with CSS3?

height: 1px;
transform: scale(0.5);

6. Draw a triangle with CSS3?

<style>
.up{
    width:0;
    height:0;
    border: 100px solid transparent;
    border-top: 100px solid red;/*红色*/
}
.down{
    width:0;
    height:0;
    border: 100px solid transparent;
    border-bottom: 100px solid blue;/*蓝色*/
}
.left{
    width:0;
    height:0;
    border: 100px solid transparent;
    border-left: 100px solid pink;/*黑色*/
}
.right{
    width:0;
    height:0;
    border: 100px solid transparent;
    border-right: 100px solid pink;/*黄色*/
}
</style>

<body>
    <div class="up"></div>
    <div class="down"></div>
    <div class="left"></div>
    <div class="right"></div>
</body>

Realize the effect:

 

7. CSS3 box model

The Box Model can be used to layout elements, including padding, borders, margins, and actual content

There are two types of box models:

The first is the W3C standard box model (standard box model)

The second IE standard box model (weird box model)

The difference between the performance of the standard box model and the weird box model:

1. Width in the standard box model refers to the width of the content area

height refers to the height of the content area

The size of the box under the standard box model = content + border + padding + margin

2. Width in the weird box model refers to the total width of the content, border, and padding (content + border + padding); height refers to the total height of the content, border, and padding

The size of the box under the weird box model = width (content + border + padding) + margin

In addition, we can also set the parsing mode of the box model through the attribute box-sizing

Two values ​​can be assigned to box-sizing:

1. box-sizing: content-box: the default value, border and padding are not included in the width range, which can be understood as the standard model (default) of W3c. Total width=width+padding+border+margin

2. box-sizing: border-box : border and padding are included in the width range, which can be understood as the weird box model of IE, total width=width+margin

1. Merge of vertical margins of adjacent block elements

2. Collapse of vertical margins of nested block elements

8. Float

(1) Off label

(2) Clear floating

(3) The method of clearing the float

3.1 Clear Float - Extra Label Method

3.2 Clear floating - add overflow to the parent

 

3.3 Clear floating - :after pseudo-element method

3.4 Clear Float - Double Pseudo-Element Clear Float

9. Flex layout

1. Spindle alignment

Use justify-content to adjust the alignment of elements on the main axis

2. Side axis alignment

Use align-items to adjust the alignment of elements on the side axis

3. Change shaft

Use flex-direction to change the arrangement direction of elements

4. Flexbox line wrap

Goal: Use flex-wrap to achieve multi- line arrangement of elastic boxes

10. CSS flat conversion

(1) Displacement: transform: translate (horizontal movement distance, vertical movement distance)

 (2) rotation

transform: rotate(angle);  note: the angle unit is deg

If the value is positive , it will rotate clockwise ; if the value is negative , it will rotate counterclockwise

 (2) Zoom

transform: scale(x-axis scaling factor, y-axis scaling factor);

transform: scale (zoom factor);

A scale value greater than 1 indicates zooming in, and a scale value less than 1 indicates zooming out

11. "Son and Father" in CSS

12. The box is centered in CSS3

(1) Realize by using positioning (children and fathers), margin -left, and margin-top

(2) Realize by using positioning (child and father), transfrom attribute

(3) Use flex layout to realize box centering

13. Positioning stacking order z-index in CSS3

14. Selector weight in CSS3

15. Transition in CSS3

  

16. Structural pseudo-class selectors and pseudo-element selectors in CSS3

(1) Destructuring pseudo-class selectors

 (2) Pseudo element selector

3. HTML&CSS Mixed Articles

1. The difference between Localstorage, sessionStorage and cookie

What they have in common: they are all saved on the browser side and have the same origin

The difference between the three:

1. The cookie data is always carried in the same-origin http request (even if it is not required), that is, the cookie is transmitted between the browser and the server

Pass back and forth between sessions, and sessionStorage and localStorage will not automatically send data to the server, but only save it locally. Cookie data also has the concept of path (path), which can restrict cookies to only belong to a certain path

2. The storage size limit is also different. The cookie data cannot exceed 4K. At the same time, because each http request will carry a cookie, the cookie is only suitable for storing small data, such as session identifiers. Although sessionStorage and localStorage also have storage size limitations, they are much larger than cookies and can reach 5M or greater.

3. The validity period of the data is different

sessionStorage: only valid until the current browser window is closed;

localStorage: is always valid, and is always saved when the window or browser is closed, so it is used as persistent data;

cookie: only valid until the set cookie expiration time, even if the window is closed or the browser is closed

4. The scope is different,

sessionStorage is not shared across different browser windows, even on the same page;

localstorage is shared among all same-origin windows;

Cookies are also shared among all same-origin windows

5. Web Storage supports an event notification mechanism, which can send notifications of data updates to listeners.

6. The api interface of web Storage is more convenient to use.

2. How to realize the double flying wing (holy grail) layout? 

 1. Use positioning to realize self-adaptation between fixed sides on both sides

        The parent box sets the left and right padding values

        Set the padding value of the parent box for the width of the left and right boxes, and then position them at the padding respectively.

        middle box adaptation

2. Use flex layout to realize self-adaptation between fixed sides on both sides

        Parent box set display: flex

        Set fixed width and height for left and right boxes

        Middle box set flex: 1 

3. What is the difference and function of double colon and single colon in ::before and ::after? 

the difference

Pseudo-classes are always represented by: in CSS, such as :hover, :active, etc.

Pseudo-elements already existed in CSS1, when the syntax was represented by: , such as :before and :after

Later revised in CSS3, pseudo-elements are represented by ::, such as ::before and ::after, to distinguish pseudo-elements and pseudo-classes

Since the lower version of IE is not compatible with double colons, developers continue to use the old idiom :after in order to be compatible with various browsers.

Pseudo-element

A single colon (:) is used for CSS3 pseudo-classes

Double colon (::) for CSS3 pseudo-elements

If you want the inserted content to appear before other content, use ::before, otherwise, use ::after;

In code order, the content generated by ::after is also later than the content generated by ::before

From the perspective of the stack, the content generated by ::after will be on top of the content generated by ::before

effect:

The main function of ::before and ::after is to add the specified content before and after the element content

Both pseudo-classes and pseudo-elements are used to add special effects to selectors

The essential difference between pseudo-classes and pseudo-elements is whether new elements are created abstractly

Pseudo-classes can be superimposed as long as they are not mutually exclusive

Pseudo-elements can only appear once in a selector, and only at the end

Pseudo-classes and pseudo-elements have the same priority as classes and tags respectively

4. What are the similarities and differences between the alt and title of img, and the principle of lazy loading of images ?

similarities and differences

alt is the alternative text displayed on the webpage when the image fails to load; title is the text displayed when the mouse is placed on it, title

Is the description and further explanation of the picture;

These are superficial differences, alt is a necessary attribute of img, and title is not for website SEO optimization, title and alt have the most important point: search engines judge the meaning of pictures mainly by alt attribute. Therefore, it is also a part of page optimization to describe in brief text in the alt attribute of the picture, and to include keywords at the same time. If conditions permit, you can further explain the pictures in the title attribute. Since too many pictures will seriously affect the loading speed of the webpage, and the traffic consumption under the mobile network is huge, so delayed loading is almost standard.

principle

The principle of image lazy loading is very simple, that is, we first set the data-set attribute of the image (of course, it can be any other, as long as it does not send http requests, the function is to access the value) as the value of its image path, because Not src, so no http request will be sent. Then we calculate the sum of the height of scrollTop of the page and the height of the browser. If the coordinate Y of the top of the page (relative to the entire page, not the browser window) of the picture example (relative to the entire page, not the browser window) is less than the sum of the former two, it means that the picture will be displayed (the right time, of course, it can also be other situations), at this time we can replace the data-set attribute with the src attribute.

5. What is BFC? 

definition

BFC (Block formatting context) is literally translated as "block formatting context". It is an independent rendering area,

Only the Block-level box participates, which specifies how the internal Block-level Box is laid out, and is compatible with this area

Irrelevant outside the domain

layout rules

1. The internal Boxes will be placed one after another in the vertical direction

2. The vertical distance of Box is determined by margin. The margin of two adjacent Boxes belonging to the same BFC

will overlap

3. The left side of the margin box of each element touches the left side of the containing block border box (for left to

right formatting, otherwise the opposite). This is true even in the presence of float

4. The BFC area will not overlap with the float box

5. BFC is an isolated and independent container on the page, and the child elements inside the container will not affect the elements outside. opposite

the same

6. When calculating the height of BFC, floating elements also participate in the calculation

Which elements generate a BFC:

1. Root element

2. The float attribute is not none

3. The position is absolute or fixed

4、display 为 inline-block, table-cell, table-caption, flex, inline-flex

5. overflow is not visible

4. JavaScript articles

1. JS data type

The basic types of JS data are:

String, Number, Boolean, Null, undefined basic data types, plus ES6's Symbol, BigInt.

JS has three  complex types ( reference data types ) : Object, Array and function

2. What is the difference between an arrow function and an ordinary function?

(1) Arrow functions are more concise than ordinary functions.
        If there are no parameters, just write an empty parenthesis. If there is only one parameter, you can omit the parameter parentheses. If there are multiple parameters, separate them with commas. If the return value of the function body Only one sentence, curly braces can be omitted.
(2) The arrow function does not have its own this
        The arrow function does not create its own this, so it does not have its own this, it only inherits this in the upper layer of its own scope. So the point of this in the arrow function has been determined when it is defined, and will not change afterwards.
(3) The this point inherited by the arrow function will never change
(4) Call(), apply(), bind() and other methods cannot change the point of this in the arrow function  
(5) The arrow function cannot be used as a constructor

        because the arrow A function does not have its own this, and this points to the outer execution environment, and cannot be changed, so it cannot be used as a constructor. 
(6) Arrow functions do not have their own arguments object. Accessing arguments in an arrow function actually gets the arguments value of its outer function. (7) The arrow function has no prototype  (8) Supplement: Where does the this of the arrow function point to?         Arrow functions are different from functions in traditional JavaScript. Arrow functions do not have their own this. What they call this is to capture the this value of their context as their own this value. Since they do not have their own this, So it will not be called by new, and this so-called this will not be changed. 


3. What is the judgment method and difference between null and undefined in JS?

1. Judgment of undefined (1) undefined means lack of value, that is, there should be a value here, but it has not been defined yet(2) The variable has been declared and has not been assigned a value, so it is undefined(3) The parameter that should be provided when calling the function has not yet Provided, this parameter is equal to undefined(4) The object has no assigned property, the value of this property is equal to undefined(5) The function has no return value, and the default returns undefined 2. Null judgment  (1) Null means that a value is defined, But this value is a null value(2) as a function parameter, indicating that the function parameter is not an object(3) as the end of the object prototype chain (Object.getPrototypeOf(Object.prototype))(4) It is reasonable to define a value as null , but defined as undefined unreasonable (var name = null) 3.typeof different types   










typeof null; // 'object'
typeof undefined; // 'undefined'

4.Number() is also different for converting numbers 

Number(null); // 0
Number(undefined); // NaN 

4. Prototype chain

Prerequisites:
(1)  prototype : All functions have a prototype attribute, which points to the prototype object of the function.
(2)  __proto__ , this is an attribute that every object (except null) will have, called __proto__, this attribute will point to the prototype of the object.
(3)  constructor : Each prototype has a constructor attribute, pointing to the associated constructor.

Prototype chain: When obtaining an object, if the object itself does not have this attribute, it will go to its prototype __proto__ to find it. If it cannot find it, it will go to the prototype of the prototype to find it... until it finds the most Up to the top level (Object.prototype), the Object.prototype object also has a __proto__ attribute whose value is null.
In addition, each prototype prototype will have a constructor attribute pointing to its associated constructor.

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

  • v-showInstructions are to display or hide elements by modifying displaytheir attributes;CSS

  • v-ifThe instruction is to directly destroy and rebuild DOM to achieve the effect of showing and hiding elements;

  • Use v-showwill save performance overhead; it is v-ifmore reasonable to use when you only need to show or hide once.

6. What is the function of keep-alive?

Official website explanation: When wrapping dynamic components, inactive component instances are cached, which is mainly used to preserve component state or avoid re-rendering .

Function: Implement component caching and keep the state of these components to avoid performance problems caused by repeated rendering. Frequent switching of cache components is required without repeated rendering

Scenario: tabs tab page background navigation, vue performance optimization

Principle:Vue.js Internally, DOMthe nodes are abstracted into individual VNodenodes, and keep-alivethe cache of components is also based on VNodenodes rather than direct storage DOMstructures. It caches (pruneCache与pruneCache)the components that meet the conditions in the object, and then takes the node out of the object and renders it when it needs to be re-rendered.cachevnodecache

7. Understanding of closure?

Concept: A function that has access to variables inside another function.

Essence: It refers to a function that has the right to access variables in the scope of another function. The most common way to create a closure is to create another function within a function and access the local variables of this function through another function. Closures can be used Break through the chain of scope, and pass the variables and methods inside the function to the outside.

        A closure is an environment, specifically referring to an external function -- a higher-order function.

        In layman's terms, it is an environment that can read variables inside other functions.

        Essentially, closures are the bridge that connects the inside of a function with the outside of a function.

Uses: 1. Read variables of internal functions;

   2. The values ​​of these variables will always be kept in memory and will not be automatically cleared after the outer function is called

Advantages: 1. Variables will always be in memory;

      2. Avoid pollution of global variables;

      3. The existence of private variables;

Features: 1. Function nested function;

      2. Internal functions can directly use local variables of external functions;

      3. Variables or parameters will not be reclaimed by garbage collection mechanism GC;

Supplementary garbage collection mechanism:

  In Js, if an object is no longer referenced, the object will be reclaimed by GC. If two objects refer to each other and are no longer referenced by a third party, then the two objects that refer to each other will also be recycled. Because function a is referenced by b, and b is referenced by c outside a, this is why function a will not be recycled after execution.

Disadvantages : Variables are stored in memory for a long time, which will increase memory usage, and improper use will cause memory leaks

Three characteristics of judging closures:

  1. Function nested function;

  2. The internal function must operate the local variables of the external function;

  3. The external function must return the internal function to the outside and save it in a global variable;

Judging the execution result of the closure:

  1. When the external function is called several times, there are several copies of protected local variables;

  2. The function from a closure is called several times, and the protected local variable changes several times;

8. Implementation of nextTick

  • nextTick是Vue提供的一个全局API,是在下次DOM更新循环结束之后执行延迟回调,在修改数据之后使用$nextTick,则可以在回调中获取更新后的DOM。
  • Vue在更新DOM时是异步执行的。只要侦听到数据变化,Vue将开启1个队列,并缓冲在同一事件循环中发生的所有数据变更。如果同一个watcher被多次触发,只会被推入到队列中-次。这种在缓冲时去除重复数据对于避免不必要的计算和DOM操作是非常重要的。nextTick方法会在队列中加入一个回调函数,确保该函数在前面的dom操作完成后才调用
  • 比如,我在干什么的时候就会使用nextTick,传一个回调函数进去,在里面执行dom操作即可。简单了解nextTick的实现,它会在callbacks里面加入我们传入的函数,然后用timerFunc异步方式调用它们,首选的异步方式会是Promise。这让我明白了为什么可以在nextTick中看到dom操作结果。
  • Implementation principle: Execute the delayed callback after the next DOM update cycle ends, and use nextTick to get the updated DOM immediately after modifying the data. nextTick mainly uses macro tasks and micro tasks. Try using Promise, MutationObserver, and setImmediate according to the execution environment. If none of the above works, use setTimeout to define an asynchronous method. Calling nextTick multiple times will store the method in the queue, and clear the current queue through this asynchronous method.

9. Mix in the mixin principle

When the mixin project becomes complicated, there will be repeated logic among multiple components.
Multiple components of mixin will have the same logic and be extracted. In fact, mixin is not a perfect solution, and there will be some problems
such as: Vue3 proposes The Composition API is designed to solve these problems [the pursuit of perfection will consume certain costs, such as development costs]
Scenario: The right column of the news list on the PC side is the same as the details page, and mixin can be used for mixing
Disadvantages: 1. Variable sources are different Clear, not conducive to reading
2. Multiple mixins may cause naming conflicts 3. There may be a many-to-many relationship between mixins and components, making the project more complex

10. List methods related to array operations

 

11. What is the difference between typeof and instanceof? 

(1) The return value of typeof is a string, which is used to describe the data type of the variable;

typeof is used to judge the data type, and the return values ​​include number, string, boolean, function, undefined, and object. However, you will find that when typeof judges null, array, object, and function instances (new + function), it returns object. This leads to not getting the real data type when judging these data types. Therefore, the disadvantages of typeof-although it can judge the basic data types (except null), but in the reference data types, except for the function type, others cannot be judged.

(2) The return value of instanceof is a Boolean value, which is used to determine whether a variable belongs to an instance of an object. instanceof can accurately judge complex reference data types, but cannot correctly judge basic data types.

12. What is the difference between "===" and "==" in js?

the difference

===: The three equal signs are called equivalent symbols. When the values ​​on both sides of the equal sign are of the same type, directly compare the two sides of the equal sign

If the values ​​are the same, true will be returned; if the value types on both sides of the equal sign are different, false will be returned directly. That is to say three equal signs

It is necessary to judge whether the value or the type is equal.

==: Two equal signs are called equivalent symbols. When the values ​​on both sides of the equal sign are of the same type, compare whether the values ​​are the same, but the types are different.

Automatic type conversion occurs when the type is converted to the same type before comparison. That is to say, as long as the two equal signs are equal in value

can.

13. How to use native JavaScript to bind two onclick events to a button?

Var btn=document.getElementById(‘btn’); //事件监听 绑定多个事件
var btn4 = document.getElementById("btn4");

btn4.addEventListener("click",hello1);
btn4.addEventListener("click",hello2);

function hello1(){
    alert("hello 1");
}

function hello2(){
    alert("hello 2");
}

Five, Vue articles

​1. What is a front-end construction tool? For example (webpack of Vue2, Vite of Vue3)

① First of all, we must understand: the browser only understands html, css, js,
which functions may be available in enterprise-level projects?
1. Typescript: If we encounter a ts file, we need to use tsc to convert the typescript code to js code
2. React/Vue: Install react-compiler / vue-complier to convert the jsx file or .vue file we wrote into a render function
3. less/postcss/component-style: we need to install a series of compilation tools such as less-loader, sass-loader, etc. 4. Syntax downgrade: babel ---> convert the new syntax of es to the syntax acceptable to older browsers
5 . Size optimization: uglifyjs ---> Compress our code into a smaller file with higher performance
② Cause and effect:
Because it is very troublesome to change a little bit!
Will App.tsx --->tsc ---> App.jsx --->React-complier --->js file
But there is one thing that can help you put tsc, react-compiler, less, babel, uglifyjs all Integrated together, we only need to care about the code we write. The code we write
changes --> someone helps us automatically go through tsc, react-compiler, less, babel, uglifyjs all one by one --> js
this thing It is called the front-end construction tool
③The work of the front-end construction tool:
Packaging: The process of handing over the code we wrote that the browser does not recognize to the construction tool for compilation and processing is called packaging. After the packaging is completed, it will give us a file that the browser can recognize.
What kind of dirty work does a construction tool undertake:
1. Modular development support: support for importing code directly from node_modules + multiple modular support
2. Handle code compatibility: downgraded from the original babel syntax, less, ts syntax Conversion (**not done by the build tool, the build tool integrates the processing tools corresponding to these grammars into automatic processing)
3. Improve project performance: compress files, **code splitting*
4. Optimize the development experience:
(1) The build tool will Help you automatically monitor file changes, when the file changes, automatically call the corresponding integration tool for repackaging, and then re-run the browser (the whole process is called hot update, hot replacement) (2) Development server: cross-domain
problem , use react-cli create-react-element-vue-cli to solve cross-domain problems,
④ build tool summary: 
        build tools allow us not to care about how our code runs in the browser every time, we only need the first time Provide a configuration file to the build tool (this configuration file is not necessary, if you don’t give it to him, it will help you to deal with it by default), with this integrated configuration file, we can update it next time Just call the corresponding command once. If we combine hot update, we don't need to care about anything. This is what the build tool does.
The construction tool allows us not to care about the production code, nor how the code runs in the browser. We only need to care about how our development is written and how to write it.

2. Six ways of communication between Vue components

(1) Parent components pass values ​​to child components

//App.vue父组件
<template>
  <div id="app">
    <users :users="users"></users>//前者自定义名称便于子组件调用,后者要传递数据名
  </div>
</template>
<script>
import Chilren from "./components/chilren "
export default {
  name: 'App',
  data(){
    return{
      users:["HelloKK"]
    }
  },
  components:{
    Chilren:Chilren 
  }
}
//chilren子组件
<template>
  <div class="hello">
    <ul>
      <li v-for="user in users">{
     
     {user}}</li>//遍历传递过来的值,然后呈现到页面
    </ul>
  </div>
</template>
<script>
export default {
  name: 'chilren',
  props:{
    users:{           //这个就是父组件中子标签自定义名字
      type:Array,
      required:true
    }
  }
}
</script>

(2) Child components pass values ​​to parent components (in the form of events)

// 子组件
<template>
  <header>
    <h1 @click="changeTitle">{
     
     {title}}</h1>//绑定一个点击事件
  </header>
</template>
<script>
export default {
  name: 'app-header',
  data() {
    return {
      title:"Vue.js Demo"
    }
  },
  methods:{
    changeTitle() {
      this.$emit("titleChanged","子向父组件传值");//自定义事件  传递值“子向父组件传值”
    }
  }
}
</script>
// 父组件
<template>
  <div id="app">
    <app-header v-on:titleChanged="updateTitle" ></app-header>//与子组件titleChanged自定义事件保持一致
   // updateTitle($event)接受传递过来的文字
    <h2>{
     
     {title}}</h2>
  </div>
</template>
<script>
import Header from "./components/Header"
export default {
  name: 'App',
  data(){
    return{
      title:"传递的是一个值"
    }
  },
  methods:{
    updateTitle(e){   //声明这个函数
      this.title = e;
    }
  },
  components:{
   "app-header":Header,
  }
}
</script>

​3. Understanding and usage scenarios of Vuex

Vuex is a state management pattern developed specifically for Vue applications. At the heart of every Vuex application is the store.

Vuex's state storage is responsive; when a Vue component reads the state from the store, if the state in the store changes, the corresponding component will be efficiently updated accordingly 2. The only way to change the state in the store It is to explicitly submit (commit) mutation, so that we can easily track each state change. Vuex mainly includes the following core modules:

1. State: defines the state data of the application

2.Getter: Define "getter" in the store (which can be considered as the calculated property of the store),

Just like computed properties, the return value of a getter is cached according to its dependencies, and will only be recomputed when its dependent values ​​change

3. Mutation: is the only way to change the state in the store, and must be a synchronous function

4. Action: used to submit mutations instead of directly changing the state, and can contain any asynchronous operations

5. Module: Allows a single Store to be split into multiple stores and stored in a single state tree at the same time

4. Vue's life cycle eight stages

1.beforeCreate

Create a Vue instance, at this time there are only some life cycle functions and default events on the instance

At this time, the methods and data on the data computed watch methods cannot be accessed

2.created

Data data can be operated, and some requests can be made. It is not easy to make too many requests, so as to avoid the white screen time being too long.

3.beforeMount

Determine the mounting method of el

Determine whether there is a template setting

Render the template and save it in memory, but it has not been mounted on the page

4.mounted

Mount the template in memory to the page

At this point you can manipulate the DOM nodes on the page

At this point, the component enters the running phase from the creation phase

5.beforeUpdate

The data displayed on the page is old. At this time, the data in data is the latest, and the page data and data data have not been synchronized yet. 6.updated

Render the latest DOM tree according to the latest data in data, and then mount the latest DOM to the page

At this time, the data is consistent with the page data and is the latest

7.beforeDestroy

At this point, the component enters the destruction phase from the running phase

The data, methods and filters on the component are all available, and the destruction has not yet been executed

8.Destroyed 

The component has been completely destroyed, and all data, methods, instructions, filters, etc. in the component are no longer available

5. Briefly describe the principles and differences between MVVM and MVC?

MVVM view model two-way binding, is the abbreviation of Model-View-ViewModel

1. Advantages of MVVM:

  1. low coupling. The View (View) can be changed and modified independently of the Model. A Model can be bound to different Views. When the View changes, the Model can remain unchanged, and when the Model changes, the View can also remain unchanged;
  2. reusability. You can put some view logic in a Model and let many Views reuse this view logic.
  3. Independent development. Developers can focus on business logic and data development (ViewModel), and designers can focus on page design.
  4. testable.

2. What is MVC?

        MVC is one of the most widely used software architectures. Generally, MVC is divided into: Model (model), View (view), and Controller (controller). This is mainly based on the purpose of layering, so that the responsibilities of each other are separated. View generally uses Controller to communicate with Model. Controller is the coordinator of Model and View, and View and Model are not directly connected. Basically a one-way connection. M and V refer to the same meaning as M and V in MVVM. C means Controller refers to the page business logic. MVC is one-way communication. That is, the View and the Model must be connected through the Controller.

Model (Model) represents the application core (such as database).

View (view) display effect (HTML page).

Controller (controller) handles input (business logic).

The MVC pattern also provides complete control over HTML, CSS, and JavaScript.

The Model is the part of the application that handles the logic of the application data. (Usually model objects are responsible for accessing data in the database)

View (view) is the part of the application that handles the display of data. (Usually views are created from model data)

Controller (controller) is the part of the application that handles user interaction. (Usually the controller is responsible for reading data from the view, controlling user input, and sending data to the model)

advantage:

1. Low coupling
2. High reusability
3. Low life cycle cost
4. Fast deployment
5. High maintainability
6. Favorable software engineering management

3. The difference between MVC and MVVM:

        The difference between MVC and MVVM is not that VM completely replaces C. The purpose of ViewModel is to extract the business logic displayed in the Controller, not to replace the Controller. Other view operations should be implemented in the Controller. That is to say, MVVM realizes the reuse of business logic components.

The Controller in MVC has evolved into the ViewModel in MVVM.
MVVM uses data to display the view layer instead of node operations.
MVVM mainly solves the problem of a large number of DOM operations in MVC, which reduces page rendering performance, slows down loading speed, and affects user experience.

6. Vue common commands

v-model is mostly used for form elements to realize two-way data binding
v-bind: abbreviated as colon: , to dynamically bind the properties of some elements, and the type can be: string, object or array.
v-on:click binds a function to a label, which can be abbreviated as @ , for example, binding a click function must be written in methods
v-for format: v-for="field name in(of) array json" loop array or json, remember to add the key
v-show to display the content

v-if instruction: the value is true/false, to control whether the element needs to be rendered
v-else instruction: used with the v-if instruction, there is no corresponding value. When the value of v-if is false, v-else will be rendered
v-else-if must be used together with v-if
v-text parses text
v-html parses html tags (commonly used to solve background rich text content)
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
v-cloak prevents flickering
v-pre outputs the elements inside the tag in situ

7. Why is data in vue a function? What role does it play? 

        In Vue components, the data option must be a function, not an object directly. This is because multiple instances of Vue components can exist at the same time. If you directly use the data option in the form of an object, all instances will share the same data object, which will cause data interference.

  Therefore, setting the data option to a function allows each instance to have its own independent data object. When a component is created multiple times, each instance will call this function and return a new data object, thus ensuring data isolation.

  In addition, the data option has an important feature as a function, that is, it can receive a parameter, which is the component instance itself. This feature is very useful in some scenarios, for example, when defining a component, it is necessary to use some properties or methods of the component instance to calculate the initial data.

  Therefore, in order to avoid data sharing and ensure data isolation, and to facilitate the use of properties and methods of component instances, the data option in Vue components must be a function.

Here is an example of a simple Vue component where data is defined as a function:

<template>
  <div>
    <p>{
    
    { message }}</p>
    <button @click="increment">{
    
    { count }}</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!',
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}
</script>

In this example, the data function returns an object containing two properties, message and count. Every time a component instance is created, Vue will call this function to return a new data object, ensuring that each component instance has its own data object.

6. Solutions to browser compatibility issues:

1. What is browser compatibility?

The so-called browser compatibility problem refers to the situation that the page display effect is not uniform because different browsers have different parsing for the same piece of code. In most cases, no matter what browser users use to view our website or log in to our system, it should be a uniform display effect.

2. Question 1: The default external patch and internal patch of labels in different browsers are different

Problem: In different browsers, if only margin and padding are set for labels without style control, their respective differences will be large.

Solution: use the wildcard * in css, set the value of margin and padding to 0, or use Normalize to clear the default style.

3. When we lay out horizontally, we are used to setting float for block-level elements, and then when their spacing is set with margin, the margin value displayed under IE6 is larger than the set value

Problem: The next block will be pushed to the next line in IE6

Solution: Add display: inline; in the label style of setting float to convert it into an inline element.

4. When the height of the label is set less than 10px, the height in IE6 and IE7 will exceed the height you set

Solution: Set overflow: hidden for labels that exceed the height, or set the value of line-light to be smaller than the height value you set. (It will appear in the label with a small rounded background. Browsers before IE8 will set a minimum default line height for the label. Even if your label is empty, the height of this label will still reach the default line height. .)

5. The picture has spacing by default

Problem: When several img tags are put together, some browsers will have a default spacing

Solution: use float attribute for <img /> layout. (The img tag is an inline tag, but as long as it does not exceed the width of the container, the img tag will be arranged in a row, but there will be gaps between img tags in some browsers.)

6. Margin overlap problem: When margin margins are set for two adjacent elements, margin will take the maximum value (margin collapse)

Solution: Try to only set the margin value for one box.

There is also a combination of vertical margins of nested block elements. The solution is: define the upper margin for the parent element; define the upper margin for the parent element; add overflow:hidden; float:left/right;position:absolute/ fixed.

7. Two block-level elements, the parent element is set to overflow: auto; the child element is set to position : relative; and the height is greater than the parent element, it will be hidden instead of overflowing in IE6 and IE7  

Solution: set the position of the parent element: relative;

8. There is a gap under the picture under IE6

Solution: set img to display: block; or attribute vertical-align: middle;

9. Cursor:hand display hand type is not supported on qq browser and Google

Solution: Use cursor: pointer uniformly

10. The problem of margin value on both sides of IE

Solution: Convert the element to an inline attribute display: inline

Guess you like

Origin blog.csdn.net/m0_69257679/article/details/129794885