Vue

What is the life cycle of a Vue, at what point do you usually initiate a request and why?

Generally divided into 8 phases: create before/after, load before/after, update before/after, destroy before/after. 1. Before creation: beforeCreate: The mount element EL and data object of the vue instance are both undefined and have not been initialized. Data and methods on Data, Methodes, computed, and Watch cannot be accessed at this stage. 2. Created: Created: Data is a vue data object, but el is not. You can do some initial data fetching, but you can't interact with the DOM at this stage, so you can asynchronously manipulate the DOM via this.$nextTick () if you want. BeforeMount: The EL and data of the vue instance are already initialized, but the previously virtual DOM node is still mounted. The virtual DOM has been created at this stage and is about to start rendering. Data can also be changed at this point without triggering the updated. Mounted: Indicates that the vue instance is mounted. In the current stage, the real DOM hangs at the end, the data is bidirectional bound, and dom nodes can be accessed and manipulated. BeforeUpdate: called when reactive data is updated. It occurs before the virtual DOM is patched and is suitable for accessing the existing DOM before the update, such as manually removing event listeners that have been added 6. Updated: Virtual DOM is called after re-rendering and patching. The new DOM has been updated to avoid manipulating data in this hook function and prevent endless loops. BeforeDestroy: beforeDestroy: Called before the instance is destroyed. This gets the instance. Often used to destroy timer, unbind event 8. After destruction: deStoryed: called after the instance is destroyed. All event listeners are removed and subinstances are destroyed. Activated before activation: Activated: Activated when the keep-alive component is activated 10. After activation: deactivated: After the keep-alive component is disabled, it triggers before creation, after page loading, and before and after page loading for the first timeCopy the code

Keep – the use of the alive

First, a brief description of the function of keep-alive. Kee-alive can cache inactive components. Components are destroyed by default when they switch back and forth, and re-initialized when they switch back. If there is a need to switch back to the original state without destroying the component, keep-alive can be used to achieve thisCopy the code

How are lifecycle hooks implemented?

Vue lifecycle hooks are callback functions that are called during component instance creation. The core is a publish-subscribe model, in which hooks are subscribed and published at the corresponding stagesCopy the code

Vue’s parent and child lifecycle hook execution order

The parent component is mounted only after the child components are mounted. Parent beforeCreate -> Parent created -> Parent beforeMount -> child beforeCreate -> child created -> Child beforeMount -> Child Mounted -> Parent Mounted Refresh: Parent beforeUpdate -> Child beforeUpdate -> Child updated -> Parent updated Destroy: Parent beforeDestory -> Child beforeDestory -> Child destroyed -> Parent deStoryed Waits for the child to complete before executing its own completed hook.Copy the code

How can VUE components communicate with each other?

There are three types, one is the parent component value, one is the sibling component value, $emit/$on 3. $parent/$children 3. Vuex data management 4. Value transfer between localStorage and sessionStorage components 6. $attrs/$Listeners communicate with other components 7. Provide /inject Communicate with other componentsCopy the code

vueX

Vuex is a state management mode specially developed for VUE. 1. State 2. Getters 3. 5. Modules: Sub-modules of the store, so that each module has its own state, mutation, action and getters, so that the structure is very clear and easy to manage.Copy the code

Query and Params in vue-router participate in the connection parameter

This.$route.push ({path:'/ XXX ',query:{id:id}}) params: this.$route.query. This.$router. Push ({name:' XXX ',params:{id:id}}) add parameter: this.$route.params.id params. Because Params can only import routes by name query is a get request that can be seen in the address bar when the page jumps. Params is the equivalent of a POST request. The parameters are not displayed in the address bar as $router and $routeCopy the code

Vue-router has several hook functions. What is the execution flow?

Hook function types have global guard, route guard, component guard 1. Navigation triggered 2. Departing component calls beforeRouteLeave guard 3. Calls global beforeEach guard 4. Call beforeRouterUpadate guard 5. BeforeEnter guard in routing configuration 6. Parse asynchronous routing components 7. Call the beforeRouteEnter guard in the activated component 8. Call global beforeResolve guard 9. Navigation confirmed 10. Dom update 12. Use the created instance to call the beforeRouteEnter callback that guards nextCopy the code

What is the difference between vue-Router and VUE?

Vue-router has two routing modes. Hash and history 1. Hash mode: Hash + hashChange Hash is used in urls but not included in HTTP requests to guide browser actions and is useless for server security. Hash does not reload the page, but executes javascript code by listening for changes in the hash to implement a changed hash of the page -- the # symbol 2. History pattern in the URL of the address bar: HistoryApi +popState will request the server as soon as the URL is refreshed, and every route change will be reloaded. In general, hash and history will work, unless you're more concerned about the appearance level, but the # symbol mixed in the URL does look a little bit ugly. If you don't want ugly hashes, you can use the history mode of the route, which takes full advantage of the history.pushState API to jump urls without reloading the page. -- Official website of vue-routerCopy the code

What are the advantages and disadvantages of spa single page?

Spa (single-page Application) only loads the corresponding HTML, JavaScript and CSS when the Web page is initialized. Once the page is loaded, SPA will not reload or jump the page because of the user's operation. Instead, a routing mechanism is used to transform HTML content to avoid page reloading. Advantages: 1. Good and fast user experience. Content changes do not require reloading the entire page, avoiding unnecessary jumps and repeated rendering 2. Spa is less stressful than the server 3. The front-end is responsible for interactive logic, while the back-end is responsible for data processing. Disadvantages: 1. Slow loading of the first screen (the first time) : In order to realize spa page, js and CSS should be uniformly loaded when the page is loaded, and some pages should be loaded as required; 2. Bad for SEO: SEO has a natural disadvantage because all content is displayed dynamically on a single pageCopy the code

What happens to new Vue ()?

New Vue() creates the Vue instance and internally initializes the root instance.Copy the code

What is vue.use?

Vue. use is used to work with plug-ins, where we can extend global components, directives, prototype methods, and so on.Copy the code

Can you explain the understanding of responsive data?

1. Array and object types are hijacked when values change. DefineReactive method is used internally to collect data dependency by using Object.defineProperty () to monitor get of data attribute, and then distribute data update through set. 2. Arrays are implemented by overriding array methods. Extend its seven change methods by listening to them for dependency collection and distribution of updates; (push/pop/shift/unshift/splice/reverse/sort) vue3 use proxy to implement the response dataCopy the code

How does Vue detect array changes?

Instead of intercepting each entry of an array for performance reasons, we chose to override the array method instead. When the array call these seven method (push/pop/shift/unshift/splice/reverse/sort), executive ob. Dep. Notify () distributed update notification WatcherCopy the code

How is the vue. $set method implemented?

Dep attributes are added to both the object and the array. When adding non-existent attributes to the object, watcher, which the object depends on, is triggered to update the object. When modifying the array index, we call splice method of the array itself to update the array.Copy the code

How does Vue template compilation work?

Template is converted into an AST syntax tree. Templates in the.vue file are processed by vue-loader, not compiled at runtime. New Function +with is the implementation principle of the code template engine. Vue-template-compiler is used to process the template attribute in vue-loaderCopy the code

$nextTick() and $forceUpdate() with $set

This.$nextTick(): An operation to be performed after data changes, and should be placed in the callback function of this.$nextTick() whenever it needs to use a DOM structure that changes as data changes. This.$forceUpdate(): Forces the Vue instance to re-render the virtual DOM (rander), not reloading the component. With the vue lifecycle, calling $forceUpdate triggers only the beforeUpdate and updated hook functions. No other hook functions are triggered. It only affects the instance itself and the child component that inserts the slot content, not all the child components this.$set: If new attributes are added to the vue instance (data) after it is created, it does not trigger view updates. Attributes added with this.$set trigger view updatesCopy the code

Difference between V-if and V-show

V-if is really conditional rendering, it doesn't start rendering until the condition is true for the first time and V-show will render whatever the initial condition is, just for display to show hide, okayCopy the code

Differences between Watch, computed, and Methods:

Computed: Computes attributes and relies on other attribute values. In addition, computed values are cached and recalculated only when the dependent attribute values change. Watch: monitor the change of the monitored data. Whenever the monitored data changes, callback will be executed for subsequent operations; Methods: is a method, methods have no caching mechanism, every time the rendering is triggered again, the call method will execute the function again; Watch has no cache. If the monitored data changes, corresponding operations will be directly triggered, but it supports asynchrony. With computed, the dependency data is recalculated only when it changes. So use Watch only when performing asynchronous or expensive operations, otherwise use computed. Computed is used when an attribute is affected by more than one attribute. When one data affects multiple data sets, watch is needed.Copy the code

V – the principle of the model

The V-model is essentially a syntax sugar, which can be viewed as the syntax sugar of the value+input method. This can be customized through the Prop and Event properties of the Model property. Underlying vUE is a combination of data hijacking and published-subscribe, using object.defineProperty() to hijack the setter and getter of a property. When data changes, a message is published to the subscriber, triggering a listening callback for the responseCopy the code

Detailed explanation of watch properties

Handle :watch is the specific method to be implemented in deep: deep monitoring. When it is necessary to monitor the changes of an object, the ordinary watch method cannot monitor the changes of the internal properties of the object. In this case, the deep property is needed to monitor the object deeply. When deep: true immediate: watch is specified in the option argument, the listener function is not executed when the value is first bound, only when the value changes. We need the immediate attribute if we need to execute the function when we first bind the value. Immediate: true // Example: watch: {cityName: {handler(newName, oldName) {//... }, deep: true, immediate: true } },Copy the code

The vue slot

A slot is a placeholder provided by a child component to a parent component, denoted by <slot></slot>. The parent component can fill this placeholder with any template code, such as HTML, components, etc., replacing the child component's <slot></slot> tag 1. Default slot: If the parent component does not pass a value to the child component, the child component displays its default content in the slot. 2. Named slot: The slot location in the child component is named, and the parent component uses the v-slot: name to display the corresponding slot in the child component 3. Scope slot: A scope slot is actually a slot with data, namely a slot with parameters. Simply speaking, it is a parameter provided by a child component to a parent component. This parameter is only used in the slot.Copy the code

Vue Common commands

v-if / v-else / v-else-if / v-model / v-bind / v-on / v-show / v-html / v-text
Copy the code

Vue performance optimization

1. Minimize data in data 2. More often use V-if instead of V-show 5. Spa pages use keep-alive cache component 6. Import third-party modules on demand 7. Lazy loading of pictures 8. Loading third-party modules using CDN 9. The compression codeCopy the code

Vue -router vs. location.href

1. Vue-router uses pushState to update the route, and the page is not reloaded. Location. href triggers the browser to reload the page once. 2. Vue-router Uses the DIff algorithm to load on demand and reduce DOM operations. Location. Href is a jump between different pages; This.$nextTick(()=>{get url}); Location. href is loaded synchronouslyCopy the code

The vue mixin

Mixins can define common variables or methods, but the data in mixins are not shared, that is, mixin instances in each component are different and exist independently without mutual influence. Mixins mixed with functions of the same name will be recursively merged into arrays. Both functions will be executed, but the mixin function of the same name will be executed first. Mixins mixed with objects of the same name will be replaced, the component of the same name will be executed first, that is, the component of the same name object mixins mixed with the object of the same name will be overwritten;Copy the code

Vue prevents events from bubbling and JS prevents events from bubbling

Prevent: prevents default events. Js:.stopPropagation(): prevents event bubbling. PreventDefault (): prevents default eventsCopy the code

Virtual DOM in VUE

What is the virtual DOM? A JS object describes a DOM node. Since vue is a data-driven view, the view updates as the data changes, and manipulating the real DOM is very performance consuming because browsers have designed the DOM to be very complex, the virtual DOM can be used for: To operate DOM as little as possible, it is necessary to calculate where the view needs to be updated by comparing the state before and after the change of data, to operate the DOM performance with the computational performance of JS, and to simulate a DOM node with JS, which is called the virtual DOM node. When the data changes, we compare the virtual DOM nodes before and after the change, calculate the places to be updated by dom-Diff algorithm, and then update the view VNode class to be updated: Vue has a VNode class that instantiates different types of virtual DOM nodes: Before rendering the view, the written template template is compiled into vNodes and cached. When the page needs to be rendered again after the data changes, the vNodes generated after the data changes are compared with the vnodes cached before to find out the differences, and then the different VNodes The corresponding real DOM nodes are the nodes that need to be re-rendered. Real DOM nodes are created according to the different VNodes and then inserted into the view to complete a view updateCopy the code

What are the changes to VUe3.0

1. Use proxy to realize responsive data 2. API changes, vue2 component library does not communicate with VUe3 component library 3. Import {createApp} from 'vue',const app = createApp () 4. Filters have been removed, suggesting methods to replace or evaluate attributesCopy the code

Vue3. X Responsive data principle

1. Proxy checks whether the current reflect. get return value is Object, and if so, it is acting by reactive. 2. How to prevent multiple get/set triggers when checking arrays? You can determine whether key is the property of the current proxied object target or whether the old value is equal to the new value. Trigger can be executed only when one of the two conditions is metCopy the code

Proxy versus Object.defineProperty

1. Proxy can directly listen for objects instead of properties 2. Proxy can directly listen for array changes 3. Object.defineproperty does not include apply, ovnKeys, deleteProperty, has, etc. Object.defineproprery can only be directly modified by traversing Object attributes. 5. Proxy as a new standard will be subject to browser manufacturers' focus on continuous performance optimization, which is also the performance bonus of the new standard. However, the Proxy has compatibility problems with browsers.Copy the code

Small program

A brief description of the micro channel small program related file types

1. WXML (WeiXin Markup Language) is a set of tag Language designed by the framework. Combined with basic components and event system, the structure of the page can be constructed. 2. WXSS (WeiXin Style Sheets) is a set of Style language used to describe the component Style of WXML. 3. The page title and tabBar app.json must have this file, without this file, the project will not run, because the wechat framework uses this file as the entry to the configuration file, the global configuration of the entire applet. Including page registration, network Settings, and applet window background color, configure the navigation bar style, configure the default title app.js must have this file, no will also error! But this file is just created and we don't need to write anything and then we can listen in this file and handle the life cycle of the applet function, declare the global variable app.wxss optionalCopy the code

How is bidirectional binding of applets different from vUE

{this.setData({a:1});} {this.setData({a:1});}Copy the code

How to pass data between applet pages

GlobalData: {userInfo: {// globalData: {userInfo: Null}}), use getApp() to get the stored information 2. With wx.navigateTo and wx.redirectTo, you can put some of your data in the URL. Wx. navigateTo and wx.redirectTo are not allowed to jump to pages contained in tabs. Use local cache StorageCopy the code

The life cycle function of a small program

1. OnLoad () is triggered when the page loads and is called only once. 2. OnShow () triggered when the page is displayed, usually used to send data requests 3. OnReady () triggered when the page is first rendered, OnHide () is triggered when the page is hidden. OnUnload () is triggered when the page is unloaded. OnPullDownRefresh () is triggered when the page is pulled downCopy the code

Applets routing differences

1. Wx.navigateto (): Leave the current page and go to a page in the app. 2. Wx.redirectto () : Closes the current page to jump to a page in the app. Wx.switchtab () : switches to the Tabbar page and closes all non-tabbar pages. 4. Wx.navigateback () : closes the current page and returns to the previous page or multi-level page. You can get the current page stack with getCurrentPages () and decide which layer to return to 5.wx.relaunch () : Close all pages and open a page within the appCopy the code

The difference between wechat small program and H5

1. Different operating environments (small programs run in wechat, H5 runs in browser) 2. Different development costs (H5 needs compatibility) 3. H5 needs continuous optimization to improve user experience 4. Small programs are more limited, the page size can not exceed 2M. Advantages of page applet that cannot open more than 10 levels: Applet is a lightweight app, but limited to wechat, with short development cycle, few functions and less spaceCopy the code

Request encapsulation of applets

Encapsulate wx.request with Promise so that it can pass url, path, params, methodCopy the code

Network request encapsulation of applets

How to determine the uniqueness of the user associated with the small program wechat public number

If the developer has multiple mobile applications, website applications, and public accounts (including small programs), the uniqueness of the user can be distinguished by unionID, because as long as it is the same wechat open platform account under the mobile application, website applications and public accounts (including small programs), the user's UnionID is unique. In other words, the same user, different applications under the same wechat open platform, unionID is the sameCopy the code

How many pages can a small program open

No more than 10 pages can be opened in wechat mini program. After reaching 10 pages, no new pages can be opened.Copy the code

Subcontracting loading of small programs

Subcontracting loading of applets Subcontracting loading of uniAPP applets

How does a small program implement a pull-down refresh

EnablePullDownRefresh Specifies the onPullDownRefresh hook function in the Page. When the pulldownRefresh condition is reached, the hook function is executed. Call wx.stopPullDownRefresh to stop the pull-down refreshCopy the code

What is the difference between bindtap and catchtap?

Similarities: First of all, they are used as click event functions, which are triggered when clicked. The main difference is that bindtap does not prevent bubbling while Catchtap doesCopy the code

Web synthesis problem

Enter the URL from the browser address bar to display the page

1.DNS domain name resolution. 2. Establish a TCP connection. 3. Send an HTTP request. 4. The server processes the request. 5. Return the response result. 6. Close the TCP connection. 7. Browser parses HTML; 8. Browser layout rendering;Copy the code

Get vs. Post

1. Different locations: Get is sent in the URL, post is sent in the request body 2. Different speeds: The data transmission speed of GET is faster than that of POST. 3. Different sizes: The data transmission speed of GET is limited, but that of POST is not limited. Security difference: Post is sent in the request body, which is more secureCopy the code

The TCP three-way handshake can be summed up in one sentence

Verify that the receiving and sending capabilities of both parties are normal.Copy the code

What macro and micro tasks are available in the browser

Macro tasks: Script, setTimeout, setInterval, I/O, UI interaction events, setImmediate(Node.js environment) Microtasks :Promise, MutaionObserver, process.nexttick (node.js environment)Copy the code

The MVC and MVVM

MVC: short for model-view-controller. Model-view-controller. M and V refer to the same meaning as M and V in MVVM. C, for Controller, is the page business logic. The purpose of using MVC is to separate M and V code. MVC is one-way communication. So the View and the Model, they have to be connected by the Controller. The difference between MVC and MVVM is not that VM completely replaces C, it just adds a layer of VM on the basis of MVC, but weakens the concept of C. ViewModel exists to extract the business logic shown in Controller, not to replace Controller. Other view operations and so on should still be implemented in the Controller. In other words, MVVM realizes the reuse of business logic components, making development more efficient, structure clearer, and increasing the reuse of code. MVVM: short for model-view-viewModel. Model-view-view Model A Model refers to the data passed by the back end. A View is the page you see. The ViewModel is the core of the MVVM pattern. It is the bridge between the View and the Model. It has two directions: One is to convert the Model into a View, which is to convert the data passed by the back end into the page you see. This is done by data binding. The second is to transform the View into a Model, that is, to see the page into back-end data. This is done by DOM event listening. Both directions are implemented, which we call bi-directional data binding.Copy the code

Why is there a cross-domain, cross-domain solution

What is cross-domain? : cross domain from a domain name to request another domain resources, strictly speaking, as long as the domain name, protocol, port is any different, just as a cross domain Why a cross-domain: in order to network safety, the browser set up a homologous strategy, only the domain name, port, all the same, is called homologous. When the page executes a script, it checks to see if the accessed resources are of the same origin, and if not, an error is reported. However, in the actual development, there are often cross-domain loading resource requirements, can not avoid cross-domain request, so there is cross-domain. JSONP: The front end uses JSONP to solve cross-domain problems, but only supports GET requests. 2. The CORS: CORS requires browser and backyard support at the same time, the browser will automatically carry out CORS communication, the key to achieve CORS communication is the back end, as long as the back end implements CORS, it will achieve cross-domain, server set access-Control-Allow-Origin can enable CORS, This attribute indicates which domain names can access resources. If the wildcard is set, all websites can access resources. 3Copy the code

HTTP status code and its meaning

1XX: information status code 2XX: success status code 200 OK A normal message is returned 201 Created The request is successful and a new resource is Created. 202 Accepted the request is Accepted but not yet processed. The page for the 301 Moved Permanently Permanently Moved to a new location. 302 Found Temporary redirect. 303 See Other Temporary redirects and always uses GET to request new URIs. The requested page has Not been Modified since the last request. 4XX: Client error 400 Bad Request The server cannot understand the format of the Request. The client should not attempt to use the same content to initiate a Request again. 401 Unauthorized The request is not authorized. 403 Forbidden Forbidden access. 404 Not Found The resource how to match the URI was Not Found. 5XX: Server Error 500 Internal Server Error Indicates a common Server Error. 503 Service Unavailable The server cannot process the request temporarily (possibly due to overload or maintenance).Copy the code

Reflux and redraw

A page from loading to completion, the first is to build a DOM tree, and then according to the geometric properties of the DOM node to form the render tree (render tree), when the rendering tree is completed, the page begins to layout according to the DOM tree, the render tree also according to the set style corresponding to render these nodes. Backflow: Add and delete DOM nodes, modify the width and height of an element, change the page layout, change the STRUCTURE of the DOM tree, then you must rebuild the DOM tree, and DOM tree is closely connected to the rendering tree, after the DOM tree is built, the rendering tree will also render the page again, this process is called backflow. Redraw: Changing the color of an element does not affect the layout of the page. The DOM tree does not change, but when the color changes, rendering the tree requires rerendering the page. This is redraw. The behavior that causes changes in the STRUCTURE of the DOM tree and the layout of the page is called backflow, and backflow is always accompanied by redrawing. A change in style does not cause a change in the DOM tree. A change in page layout is called redrawing, and redrawing does not necessarily follow backflow.Copy the code

Page optimization: Repaint and Reflow

What is backflow, what is redraw, what is the difference?

What is the difference between setTimeout and requestAnimationFrame?

SetTimeout and requestAnimationFrame two animation API performance layers: When the page is hidden or minimized, the timer setTimeout is still performing animation tasks in the background. When a page is inactive, the screen refresh task for that page is paused by the system and the requestAnimationFrame is stopped. RequestAnimationFrame performs better. The biggest advantage of using requestAnimationFrame to execute animations is to ensure that the callback function is executed only once in each screen refresh interval, so that frames are not lost and animations are not stuck. SetTimeout animates an image by constantly changing it at an interval. This method may cause stalling and jitter on some low-end machines. SetTimeout belongs to JS engine, there is event polling, there is event queue. RequestAnimationFrame is a GUI engine that redraws and rearranges portions of the rendering process, in line with computer resolution.Copy the code

Understanding the browser kernel?

It is mainly divided into two parts: layout engineer and Rendering Engine and JS Engine. Takes the content of a web page (HTML, XML, images, etc.), collates information (e.g. adding CSS, etc.), and calculates how the web page should be displayed for output to a monitor or printer. The syntax of the web page will be interpreted differently depending on the browser kernel, so the rendering effect will be different. All web browsers, email clients and other elements of the need to edit, display the network applications require the kernel JS engine: parse and execute javascript to achieve the dynamic web page started rendering engine and JS engines did not distinguish clearly, then JS engine is more and more independent, the kernel will tend to only refers to the rendering engineCopy the code

Cookies, sessionStorage and localStorage difference?

A cookie is data stored (usually encrypted) on a user's Client Side by a website to identify the user. Cookie data is always carried (even if it is not needed) in a same-origin HTTP request. SessionStorage and localStorage will be passed back and forth between the browser and the server. SessionStorage will not automatically send data to the server. Cookie data size cannot exceed 4K sessionStorage and localStorage although there is also a storage size limit, it is much larger than cookie, can reach 5M or more expiration time: LocalStorage stores persistent data, data will not be lost after the browser is closed unless the data is actively deleted sessionStorage data automatically deleted after the current browser window is closed cookie set cookie expiration time remains valid, Even if the window or browser closes and sets the expiration date for the cookie (not often asked): If the cookie does not set expires, the lifetime of the cookie is only for the current session. Closing the browser means the session ends and the cookie expires. Cookies. Set (' name ', 'value' {expires: 7, 7 days / /}); If expires is set to a past point in time, the cookie is immediately deleted (expires).Copy the code

XSS attacks

Cross-site scripting (XSS-Cross-site Scripting, named XSS to differentiate it from CSS cascading stylesheets), is the most common Web application security vulnerability. XSS attack usually refers to the use of the vulnerabilities left in the development of the web page, through a clever way to inject malicious command code into the web page, the user load and execute the malicious web program made by the attacker. These malicious web programs are usually JavaScript, but can actually include Java, VBScript, ActiveX, Flash, or even plain HTML. After the success of the attack, an attacker might get including but not limited to a higher authority (e.g., to perform some operation), private web content, sessions and cookies and other content method of attack: (1) XSS reflective attacks, malicious code is not stored in the target site, by luring users click on a link to the target site malicious link to carry out attacks. 2.XSS stored attack, malicious code is saved to the server of the target website. This attack has strong stability and persistence. Reliable input validation for all user-submitted content, including URL, query keywords, HTTP headers, POST data, etc. 2. On the output side, use tags in user input. The contents of the tag are not interpreted and are displayed directly. 3. Strictly control the number of characters input. 4. No user input is allowed in the script execution area.Copy the code

CSRF attacks

Csrf-cross-site request forgery is a malicious exploitation of a trusted web site by disguising a request from a trusted user. Understanding: An attacker steals your identity and sends malicious requests on your behalf. CSRF can do things like: send emails in your name, send messages, steal your account, even buy goods, virtual currency transfer... The problems include personal privacy leakage and property security. Defense method: 1. Verify the HTTP Referer field. According to the HTTP protocol, there is a field in the HTTP header called Referer that records the source address of the HTTP request. The backend only needs to validate its Referer value for each request and this approach is not foolproof. The value of the Referer is provided by the browser. Although there are clear requirements on the HTTP protocol, the specific implementation of the Referer by each browser may be different, and there is no guarantee that the browser itself is free of security vulnerabilities. The method of verifying the Referer value relies on the security of a third party (i.e. the browser), which in theory is not secure. 2. Add a token to the request address and verify it. You can add a randomly generated token in the form of a parameter in the HTTP request, and establish an interceptor on the server side to verify the token. The request is rejected as a possible CSRF attack.Copy the code

JS

closure

A closure is a concept that describes the phenomenon of memory remaining after a function has been freedCopy the code

JS data type

The five basic data types (i.e. simple data types) are: Undefined, Null, Boolean, Number, and String. It also contains a complex data type (also known as a reference type) called object; Notice the difference between Undefined and Null, Undefined has only one value, which is Undefined, and Null has only one value, which is Null. Undefined is the output of a declared variable that has no value, and Null is the output of an object that doesn't existCopy the code

JavaScript prototype, prototype chain

All imported types (arrays, functions, objects) have a _ _ proto _ _ attribute (implicit stereotype). Each object initializes a property inside it, called prototype. When we access an object's property, if it doesn't already exist inside the object, So he's going to go to Prototype and look for that property, and that prototype will have its own prototype, and so on and so forth, and that's what we call the concept of prototype chains where JavaScript objects are passed by reference, Each new object entity we create does not have a copy of our own prototype. When we modify a Prototype, the object associated with it inherits the change. When we need a property, the Javascript engine looks to see if the property exists in the current object, and if it doesn't, it looks up whether its Prototype object has the property, and so on, Retrieve all the way to Object built-in Object - NULLCopy the code

The difference between ordinary functions and arrow functions

The difference in writing, and the difference in what this refers to. 1. This refers to the aspect ordinary function: The ordinary function refers to the object which calls the ordinary function. By default, it points to window; in strict mode, it points to undefined; Arrow function: This of the arrow function is an inherited object. Arguments: normal functions that can be overloaded by arguments; Arrow function, no arguments, functions instead of rest (...) . 3. Prototype objects: ordinary functions have their own prototype objects; Arrow function, no prototype object. 4. New aspect: ordinary functions, which can be used as constructors, instantiate child functions through new; Arrow functions cannot be used as constructors. Using new will cause an error. 5. Simplicity: Arrow functions are shorter to use than normal functions; Also, arrow functions are usually anonymous.Copy the code

Arguments, the argument object in the function

The argument object in Javascript functions is an object, not an array. But like an array, it can access its elements through a table of numbers, and it also has a length attribute that identifies the number of its elements. Usually we put it into an Array using an Array slice of function, the example code is as follows: the function fn () {var arr = Array. Prototype. Slice. The call (the arguments, 0); alert(arr.length); }Copy the code

This point

This always refers to the direct caller of the function (not the indirect caller). If there is a new keyword, this refers to the timer of the object from which new came out, and this in the timer refers to the windowCopy the code

The constructor

A function that instantiates an object by the name of a new function is called a constructor. Any function can exist as a constructor. The main function of the constructor is to initialize the object, which is used with new. New is creating an object from scratch, and the constructor is adding properties and methods to the initialized object. Constructors are defined with a capital letter (specification). New allocates memory and creates objects. When new is called, new Object() is implicitly executed in the background to create objects. Therefore, strings and numbers created by new are reference types, not value types. Var arr = [] var arr = new Array(); Grammar sugar. Var obj = {} var obj = new Object(); The syntactic sugarCopy the code

JS array method

Join (): Converts all elements of an array to a string and concatenates them together. Reverse (): Reverses the order of the elements in an array. Concat (): Array concatenation function, returns a new array, the original array is not affected. Slice () intercepts the array to generate a new array, leaving the original array intact. The array returned contains the position specified by the first argument and all elements up to but not including the position specified by the second argument. If negative, it represents the position relative to the last element in the array. If there is only one argument, it is the end of the array. Splice () removes elements from the array, inserts elements into the array, or does both. Input: The first parameter specifies the starting position for insertion or deletion, and the second parameter specifies the number of deletions to be made (passing 0 means no deletions). The arguments that follow represent the elements that need to be inserted into the array. If there is only one argument, all elements following the argument are deleted by default. Output: Returns an array of deleted elements. Note: Pop (): Removes one element from the end of the array (delete and only remove one element) and returns the deleted element Shift (): adds one or more elements to the beginning of the array, Unshift (): removes one element at the beginning of the array (and only one), and returns the removed elements toString() and toLocaleString(): converts each element of the array to a string, and enters a comma-separated list of strings. Function similar to join(); IndexOf() and lastIndexOf():indexOf() takes two arguments: the item to look up and the (optional) index that represents the starting point of the search. Here, we look backwards from the beginning of the array (position 0). Returns -1 if not found. Returns the index value of the search item, lastIndexOf(), starting at the end of the array and looking forward. Returns the index of the search item (the index is always in positive order), or -1 if not foundCopy the code

JS event loop mechanism:

Js code is executed from the top down, directly execute when encountering synchronous task, judge whether it is macro task or micro task when encountering asynchronous task, if it is micro task, put it at the bottom of the current task column, if it is macro task, open another task queue. After performing the synchronous task in the current task column, perform the micro task. After performing the micro task, perform the synchronous and asynchronous tasks in the next task queue to enter different execution environments respectively. The synchronous task enters the main thread, namely the main execution stack, and the asynchronous task enters the task queue. If the task execution in the main thread is empty, it reads the corresponding task in the task queue and pushes the main thread to execute it. The repetition of this process is known as an Event Loop.Copy the code

Ajax principle

1. The browser sends XHR to the server to fetch data. 2. The server returns data to XHR. 4. XHR tells the browser that it received data from the server. 1. Create an Ajax object let XHR = new XMLHttpRequest () 2. Xhr.open () 3. Xhr.send ()Copy the code

New features of ES6, ES7, ES8, ES9, and ES10

ES6:1. Modular Module (export :export/Import import) 2. 3. Template string 4. Const test = (a='a',b='b',c='c')=>{return a+b+c}) 5. Promise ES7: 1.includes (check whether an array contains the specified value, return true or false) 1. async/await 2. Object.values() 3. Object.keys() 4. Object.entries() ES9: 1. ... Expansion operatorCopy the code

async/await

The ultimate state of asynchronous programming is that you don't care if it's asynchronous. Async and await solve this problem by forcing asynchrony into synchronous processing. There is no substitution of async/await and promise because async/await is a syntactic sugar parasitic on promise, Generater. Async /await is a new way to write asynchronous code. Previous methods have callback functions and promises. Async /await is implemented based on promises and cannot be used for normal callback functions. Async /await, like Promise, is non-blocking. Async /await makes asynchronous code look like synchronous code, which is part of its magic. Why Async/Await is better? 1) Using async functions can make the code much simpler. There is no need to need some THEN like Promise, no need to write anonymous functions to handle Promise's resolve value, no need to define redundant data variables, and avoid nested code. 2) Error handling: Async/Await allows try/catch to handle both synchronous and asynchronous errors.Copy the code

Promise and async and await the implementation principle of async and await

promise

Promise is a constructor, a solution to asynchronous programming, with familiar methods all, Reject, and resolve in its body, and equally familiar methods like THEN and catch in its prototype. Let p = new Promise((resolve, reject) => {// do something asynchronous setTimeout(() => {console.log(' done '); Resolve (' I am success!! '); }, 2000); })Copy the code

promise.all()

Promise's All method provides the ability to execute asynchronous operations in parallel and not execute callbacks until all asynchronous operations have been executed. Look at the following example:  let Promise1 = new Promise(function(resolve, reject){}) let Promise2 = new Promise(function(resolve, reject){}) let Promise3 = new Promise(function(resolve, reject){}) let p = Promise.all([Promise1, Promise2, With all, you can perform multiple asynchronous operations in parallel and process all returned data in a single callbackCopy the code

Differences between let and VAR

1. Var is the function scope, let is the block level scope. Declares the var in the function, the function is effective, for example a var variable defined within a for loop, actually in the for loop outside also can access And because the let are block-level scope, so if the block-level scope defined variables, such as within a for loop, in its cannot be accessed outside, Let cannot access this variable before it is defined, but var can. Let must be declared before it is used. The value of var is undefined if it is used directly but not defined. Var has a variable promotion process, when the whole function scope is created, in fact the variable defined by var will be created, and if it is not initialized, the default is to initialize a undefined 3. Let cannot be redefined, but var doesCopy the code

Deep copy and shallow copy

DeepCopy: does not share the same address and does not affect each other. DeepCopy: deepCopy(obj) {let objClone = array.isarray (obj)? [] : {}; if (obj && typeof (obj) === "object") { for (let key in obj) { if (obj.hasOwnProperty(key)) { if (obj[key] && typeof(obj[key]) === "object") { objClone[key] = this.deepCopy(obj[key]); } else { objClone[key] = obj[key]; } } } } return objClone; } var deepCopy = function (source) { var result = {}; for(var key in source) { if(typeof source[key] === 'object') { result[key] = deepCopy(source[key]) } else { result[key] = source[key] } } return result; } -------------------- json.parse (json.stringify (obj)): serialize the JS object (JSON string) with json.stringify, and then use json.parse to deserialize (restore) the JS object; Serialization is for storage and transport. If there is a time object in json, serialize the result: time object => string; Error => {}; RegExp => {}; Error => {}; If json contains function,undefined, function,undefined will be lost in the serialization result; 4. If the json contains NaN, Infinity, and -infinity, the serialized result will be null; 5. If an object in json is generated by a constructor, the serialized result will discard the object's constructor; 6. Deep copy cannot be implemented if circular references exist in the objectCopy the code

Json.parse (json.stringify (obj)) implements some pits for deep copy

Throttling, anti-shaking and application scenarios

Debounce: Performs a callback n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset. ClearTimeout function debounce (f, wait) {let timer return (... args) => { clearTimeout(timer) timer = setTimeout(() => { f(... Args)}, wait)}} Throttle: specifies that functions can be fired only once in a unit of time. If more than one function is fired in this unit of time, only one function will take effect. Timer =timeout; timer=null function throttle (f, wait) { let timer return (... args) => { if (timer) { return } timer = setTimeout(() => { f(... args) timer = null }, wait) } }Copy the code

CSS

Flex layout

Flex layout: the layout of elastic - the display - flex, the default spindle arrangement (horizontal) flex - direction: used to change the direction of the spindle: row (the default horizontal arrangement, from left to right) | row - reverse (the default horizontal arrangement, from right to left) | The column (the default vertically, from top to bottom) | column - reverse (default vertically, from bottom to top); Flex - wrap: whether a newline: nowrap (default is not a newline) | wrap (line, from top to bottom) | wrap - reverse down) on the (a newline, by flex - flow: flex - direction and flex - wrap attribute shorthand, The default value is Row nowrap. 22. justify-content: Flex - start (left) | flex - end (right) | center (center) | space - between (full-justified, interval of equal) | space - around (element on both sides of the equal interval) The align - items: auxiliary shaft alignment: flex - start (start alignment - from top to bottom) | flex - end (the end alignment - from bottom to top) | center (center) | baseline baseline alignment (first line) | stretch (covered); Align - content: root auxiliary shaft alignment, flex - start (start alignment - from top to bottom) | flex - end (the end alignment - from bottom to top) | center (center) | baseline baseline alignment (first line) | stretch (covered); Order: defines the order of items. The smaller the value, the higher the order. Default: 0 flex-grow: Specifies the size of the property defined Align - self: a single element of the auxiliary shaft alignment, the default is auto, said to inherit the parent element flex - start (start alignment - from top to bottom) | flex - end (the end alignment - from bottom to top) | center (center) | baseline (baseline alignment, the first line of text) | Stretch (covered); Flex-shrink: defines the scale by which the project shrinks. The default is 1, that is, if there is insufficient space, the project will shrink flex-basis: defines the main size of the project before the extra space is allocated. Based on this property, the browser calculates whether the main axis has extra space. Its default value is Auto, the original size of the project. Flex: short for flex-grow, flex-shrink, and flex-basis. The default value is 0. 1 Auto. The last two attributes are optionalCopy the code

Range of new features

2. Background-image background-origin(content-box/padding-box/border-box) background-size background-repeat 3. Word-wrap (wrap long indivisible words) word-wrap: break-word 4. Text-shadow: 5px 5px 5px #FF0000; (Horizontal shadow, vertical shadow, blur distance, shadow color) 5. Font face property: define your own font 6. Rounded Corner (border radius) : The border-radius property is used to create rounded corner 7. Border image: border-image: url(border-.png) 30 30 Round 8 Box shadow: box-shadow: 10px 10px 5px #888888 9. Media query: Defines two sets of CSS with different properties when the browser size changesCopy the code

How is the CSS priority algorithm calculated

Element selector: 1 Class selector: 10 ID selector: 100 Element tag: 1000 1.! The most important declaration has the highest style priority and will be evaluated if it conflicts. 2. If the priority is the same, select the style that appears last. 3. Inherited styles have the lowest priority.Copy the code

Block-level labels, the difference between inline labels and inline block labels

Div P H1-H6 ul LI Header footer main nav Section artical A span em strong I Inline labels cannot occupy a single line. They are arranged in the same line by default. You cannot set the width and height of inline block labels: img,textarea, input Form element class tags Inline block labels have the characteristics of inline blocks. Block; Display: inline. display:inline-block;Copy the code

The box model

< font size = "box-sizing: content-box" style = "box-sizing: box-sizing: content-box" style = "box-sizing: content-box"; In the box model in standard mode, the width/height of the actual content of the box is equal to the width/height we set; Box total width/height =width/height+padding+border+margin Box-sizing: border-box: browser width = the sum of the width of the content, the padding, and the border; In weird mode, the box's content width + padding+ border width = the width we set, Box width/height =width/height + margin = Content area width/height + padding + border + margin box-sizing: inherit; // Specify that the value of box-sizing attribute should be inherited from the parent element. Q: How can style compatibility be resolved between the two modes? A: It is recommended not to add an inner margin of a specified width to an element. Instead, try to add an inner margin or a margin to the element's parent and child elements.Copy the code

The position location

Position has five attributes: Static, relative, absolute, fixed, sticky static: default, elements are sorted according to the normal document, Relative: Elements positioned relative to each other are offset in the document flow by top, bottom, left, and right. Absolute: Absolute position is taken out of the normal document flow, relative to the nearest parent element, or relative to the browser window if the parent does not have relative. The element is also removed from the normal document flow and is always positioned relative to the browser window, no matter how the page is swiped, always in the same place on the screen. Sticky: Sticky positioning takes effect only when top, left, right, and bottom are specified. This is how far the element is from the boundary in the visible area.Copy the code

How do I center an element vertically

1. Use absolute positioning

Div {position: absolute; width:100px; height:100px; left:50%; top:50%; margin-left:-50px; margin-top:-50px; background-color:skyblue; }Copy the code

2. Use the transform property

Div {position: absolute; width:100px; height:100px; left:50%; top:50%; transform:translate(-50%,-50%) background-color:skyblue; }Copy the code

3. Use flexible layouts

.container{
    display:flex;
    align-items:center;
    justify-content:center;
 }
.container div{
    width:100px;
    height:100px;
    background-color:hotpink;
}
Copy the code

What are the CSS selectors? Which attributes can be inherited

1. Id selector (#id); Class selector (.class); 3. Tag selector (div); 4. Adjacent selector (H1 + P); 5. Subselector (UL > LI); 6. Descendant selector (Li a); 7. Wildcard (*); 8. Attribute selector (a[rel = 'xyz']; 9. Pseudo-class selector (A :hover, Li :nth-child); Font size font family color ul li DL DD dt; Non-inheritable style: border padding margin width height;Copy the code

What are the pseudo classes and elements in the CSS?

Pseudo-class: :active, which adds styles to the activated element. :focus, adds the style to the selected element. :hover, to add a style to an element when the mouse hovers over it. :link, which adds special styles to unvisited links. :visited, adds a special style to the visited link. :first-child, which adds a special style to the first child of the element. :lang, which allows the author to define the language used in the specified element. Pseudo-element: :first-letter, which adds a special style to the first letter of the text. :first-line adds a special style to the first line of text. :before, insert something before an element. :after, insert something after an element.Copy the code

What is the BFC in CSS?

Block Formatting Context (BFC) is a CSS rendering mode for the layout of a box model in a Web page. It refers to an independent rendering area or an isolated independent container. A BFC element is a float element whose value is none. 2. Position (Absolute, fixed); 3, display as one of the following inline-block, table-cell, table-caption; 4, Overflow values except visible (hidden, auto, scroll); Features: 1. The internal boxes will be placed vertically one after the other. The vertical distance is determined by margin (margins do not merge). The BFC region does not overlap the float element region. 5. The BFC is a separate container on the page, and its children do not affect the outside elements.Copy the code