HTML, CSS,

1. The elements are horizontally and vertically centered

Margin-left, margin-top -50%, margin-left, margin-top -50%, margin-left, margin-top -50%, margin-left, margin-top -50%, margin-left, margin-top -50%, margin-left, margin-top -50%, margin-left, margin-top -50%, margin-left, margin-top -50% • Center the spindle and cross axis of the elastic box • Table parent block, child table-cellCopy the code

2. New C3 features

1 rounded border: border-radius 2 multi-background: background 3 color and transparency: background: rgba(0,0,0,.5) 4 multi-column layout and elastic box: display: Flex 5 transform: Translate (50px,100px); // rotate: rotate(); // Rotate transform: scale(); // Scale transform: skew(); // Transition: width 1s linear 2s; Animation: myFirst 5s; @keyframes myfirst { 0% {background: block; } 25% {background: red; } 50% {background: yellow; } 100% {background: green; 7 Introduce Web fonts (stored on the server) 8 Media query 9 Text shadow text-shadow 10 Box shadow box-shadowCopy the code

3. New features of H5

• Semantic tags header, footer, nav, section, article, aside, etc. • Media tags audio, video • functional tags SVG, Canvas • Smart forms some input type, And new input properties • localstorage localstorage and sessionstorage • API websocket, • New events onrisize, onDrag, onScroll, onMouseWheel, onError, onPlay, Onpause etc.Copy the code

4, mobile terminal adaptation

• Use the pre-compiled mixin functions of CSS such as media query + less or Sass, Automatic calculation with parameters • Use the latest PostCSS-Pxtorem and lib-flexible plug-ins for PostCSSCopy the code

5, landing the

A BFC is an independent space, only block elements are involved, it determines how block elements are placed inside, it has nothing to do with the external environment. Float cannot be None. Position is absolute or fixed. Display is inline-block, table-cell, flex, Inline-flex etc. 5. When overflow is not visible • Features 1. 2. The vertical distance is determined by margin. The upper and lower margins of two elements belonging to the same BFC will overlap. The margin-left of each element touches the border-left of the parent element. 4. The BFC area does not overlap with the floating area. When calculating the height of the BFC, floating elements are also involvedCopy the code

6. H5 offline storage

How it works: HTML5 offline storage is based on the caching mechanism (not the storage technology) of a newly created.appCache file, which stores resources offline through parsed lists that are stored like cookies. Later, when the web is offline, the browser will use the data stored offline to display the page: • Add a manifest attribute to the page header like the following; • Write resources stored offline in the cache.manifest file • Operate window.applicationCache to implement requirements while offlineCopy the code

JavaScript

1. Js data type

Value types: String, Number, Boolean, Null, Undefined, Symbol Reference data types: Object, Array, Function. Note: Symbol is ES6's introduction of a new primitive data type that represents unique valuesCopy the code

2. The type of the js value

• Basic data types are stored in the stack, reference data types (objects) are stored in the heap, and Pointers are placed in the stack. • The differences between the two types are as follows: o Different storage locations: Original data types are directly stored in simple data segments in the stack, occupying small space and fixed size, and are frequently used data, so they are stored in the stack; O A reference data type stores a pointer on the stack to the starting address of the entity in the heap. A reference data type stores a pointer on the stack to the starting address of the entity in the heap. When the interpreter looks for a reference value, it first retrieves its address in the stack and then retrieves the entity from the heapCopy the code

3, closures

• Closures are when a function can access variables in another function's scope. A common constructor is to define a function within another function. Inner functions can refer to outer variables; Outer variables are not collected by the garbage collection mechanism. • Note that closures work by chain of scopes, so the variable in the parent scope accessed by a closure is an object whose value is the last value after the operation. • Advantage: Avoid global variable contamination. Disadvantages: easy to cause memory leakage • Usage scenarios: O 1, bind events to multiple DOM nodes on the page through the loop o 2, encapsulate private variables (counters) O 3, extend the life of local variables O 4, high-order components O 5, function shake proofCopy the code

4. Reflow and redraw

• When part (or all) of the render tree needs to be rebuilt due to changes in element size, layout, hiding, etc. This is called reflow. Each page needs to be refluxed at least once, the first time the page loads. • On backflow, the browser invalidates the affected portion of the render tree and reconstructs it. When the backflow is complete, the browser redraws the affected portion of the screen, a process known as redrawCopy the code

5. Common DOM operations

• (1) Create a new node o createDocumentFragment() // Create a DOM fragment o createElement() // Create a concrete element o createTextNode() // create a text node • O appendChild() o removeChild() o replaceChild() o insertBefore( GetElementsByTagName () // By the tag Name o getElementsByName() // by the value of the element's Name attribute. This includes id = name) o getElementById() // by element ID, uniqueCopy the code

Native methods for array objects

• POP, Push, Shift, unshift, splice, reverse, sort, concat, Join, Slice • toString, indexOf, lastIndexOf, Reduce, reduceRight • ForEach, map, filter, every, someCopy the code

Progressive enhancement and graceful degradation

• Progressive enhancement: Build the page for the lower version browser to ensure the most basic functions, and then improve the effect and interaction for the advanced browser to achieve better user experience. • Graceful downgrading: Build full functionality from the start and then make it compatible with older browsersCopy the code

Webworker and Websocket

• Web Socket: Provides full-duplex, two-way communication over a single persistent connection. Using user-defined protocols (WS ://, WSS ://), the same origin policy does not apply to Web sockets. • Web worker: JavaScript running in the background does not affect page performance. O create worker: var worker = new worker (url); O Send data to worker: worker.postmessage (data); O Receive the data returned by the worker: worker.onmessage terminates the execution of a worker: worker.terminate();Copy the code

9, depth copy

• Shallow copy o array methods: Slice, concat, filter, map O Object methods: Object.assign({},obj), object. create(obj) O extension operators: {... Parse (json.stringify (obj)) object --> String --> object o Native implementation recursion + shallow copy O tool implementation LoadshCopy the code

10. Scope chain

• Because the nesting of functions creates a hierarchy of scopes. When a function is executed, the search starts from the current scope, and if it doesn't find any variables, it looks up the upper scope until it reaches the global function. This is called the scope chain. But local functions can see the function details above them, down to the global detailsCopy the code

11. Prototypes and Prototype Chains (FAQ)

• Each object has a __proto__ that points to its Prototype object, which in turn has a Prototype object of its own, and so on up until an object's prototype is null; The path to the query is the constructor in the O Prototype object that points to the constructor itselfCopy the code

12, inheritance,

• Constructor binding: use call or apply to bind the constructor of the parent object to the child object. • Instance inheritance: Point the prototype of the child object to an instance of the parent object. The prototype that points the child object's prototype to the parentCopy the code

13. The new keyword

This refers to the object and inherits the stereotype of the constructor. Attributes and methods are added to the object referenced by this. The newly created object is referred to by this, and this is implicitly returnedCopy the code

14, This refers to

• This always points to the direct caller of the function • If there is a new keyword, this points to the instance object that comes out of new • In the event, • This in an attachEvent in IE always points to the global object Window • The this object inside the function is the object in scope at definition, not the object in scope at useCopy the code

15, Apply, call, bind

• Call, apply, and bind are the three built-in methods of the Function object that change the direction of this inside the Function body. • The first argument to apply, call, and bind is the object to which this refers, i.e. the context that you want to specify; • Apply, call, and bind can all be passed with subsequent parameters; • Bind returns the corresponding function for later call; Apply and call are immediate callsCopy the code

16. Browser rendering process

• 1. The browser parses the HTML source code and creates a DOM tree. In a DOM tree, there is a node for each HTML tag and a text node for each text. The root node of the DOM tree is the documentElement, which corresponds to the HTML tag. • 2. The browser parses the CSS code and calculates the final style data. Build the CSSOM tree. It ignores invalid syntax in CSS code. CSS parses are priorised in the following order: default browser Settings < user Settings < external style < inline style < STYLE in HTML. • 3.DOM Tree + CSSOM --> rendering Tree Render trees are similar to DOM trees, but there are differences. DOM trees correspond exactly to HTML tags, but render trees ignore elements that do not need to be rendered, such as head and display: None elements. And each line in a large section of text is an independent node in the render tree. Each node in the render tree stores a corresponding CSS property. • 4. Once the render tree is created, the browser can draw the page directly onto the screen from the render treeCopy the code

17. Garbage collection mechanism

• JS garbage collection mechanism is to prevent memory leakage, which means that a block of memory still exists when it is no longer needed. Garbage collection mechanism is to find variables that are no longer used and release the memory they point to intermittently and irregularly. • JS garbage can be collected in two ways: • Mark and sweep o Most browsers do garbage collection this way. When a variable is entered into the execution environment (a function declares a variable), The garbage collector marks variables as "in", as "out" when they leave the environment (function execution ends), and as variables that remain after they leave the environment that need to be deleted. The notation varies, from the inversion of a particular bit to the maintenance of a list. The garbage collector marks all variables in memory and then removes the marks of variables in the environment and those referenced by variables in the environment. Variables tagged after this point are the ones that need to be reclaimed because they are no longer accessible to variables in the environment. • Reference counting o This method often causes memory leaks and is used in earlier versions of Internet Explorer. The mechanism is to keep track of the number of references to a value. When you declare a variable and assign a reference type to that variable, the number of references to that value increases by 1, and when that variable points to another value, the number of references to that value decreases by 1. The value is reclaimed when the number of references is zero.Copy the code

18. Front-end performance optimization

• Image processing o Sprite images, Base64, font ICONS instead of images, webP images can be used under Android • Reduce the size of resources O HTML compression, CSS compression, JS compression, image compression • Optimize network connectivity O CDN(Content Distribution Network) It can optimize resource loading o resource loading location (CSS, JS file placement) o resource loading timing (asynchronous script tags, module loading on demand, lazy resource loading and resource preloading) • reduce redrawing and backflow • DOM optimization o Cache DOM, reduce DOM depth and number, timely clean up the environment, anti-shake and throttlingCopy the code

19, Promise

• Promise is a solution to asynchronous programming • Promise has three states: Pending, fulfiled, and Rejected; Once the state has changed, it will never change. Once a Promise instance is created, it executes immediately • Promises are designed to solve two problems: O Promise can support multiple concurrent requests, retrieving data from concurrent requests. If the promise state is success, the callback in the first argument is executed. If the promise state is failure, the callback in the second argument is executed. O 2. Catch: The second argument is usually replaced by catch; O 3.finally: an operation introduced by ES9 for execution regardless of state o promise.all() : Package multiple Promise instances into a new instance with an array of parameters. The new resolved state is resolved only when all the states in the array are Resolved. The returned value will be an array of results if all the states are successful and the array order is the same as the order received. O promise.race() : passes the result of the first completed promise object in the argument through then • The Promise constructor is executed synchronously, and the THEN method is executed asynchronouslyCopy the code

Cookie, localStorage, sessionStorage

• Cookies are passed between the browser and the server, usually encrypted, but not the other two; • sessionStorage and localStorage have larger storage space, more interfaces, and their own storage space; • No more than 50 cookies, 4KB size, the other two can be up to 5M; • localStorage does not actively delete will be permanently stored, sessionStorage closed browser will be automatically deleted, cookie storage time by their own definition, and whether to close the browser has nothing to doCopy the code

21. Check whether the object is empty

• according to the for... In traversal object, return true if it exists, false otherwise • Use JSON's json.stringify () method to check; Keys () : {} (); The object.keys () method returns an array of the given Object's own enumerable properties. If our object is empty, it returns an empty arrayCopy the code

Var, let, const

• Variables defined by var, without the concept of a block, can be accessed across blocks, not functions. • Let variables can only be accessed within the block scope, not across blocks or functions. • Const is used to define constants, which must be initialized (that is, assigned), accessed only in the block scope, and cannot be modifiedCopy the code

Anti shake, throttling

• Throttling (mouse sliding in the block) : Continuously triggered events are executed only once in n seconds, diluting the frequency; (similar to skill cooling in the game) • Shake prevention (search box typing search) : there can only be one event within n seconds after the event is triggered. If there is a trigger within N seconds, the execution time will be refreshed (similar to return to the city in the game)Copy the code

24, async, await

• Async is used to decorate functions and perform functions asynchronously. An async modified function is a Promise object, and an async modified function also has then and catch methods. Await can only be placed in async and only modify promise objects. Await is an async function that blocks the execution until await is complete. Async returns a reject method and throws an exception equal to reject • Promise is used to simplify nested calls. • Async /await defines an asynchronous function and waits for a promise object inside it with await, blocking subsequent execution for more brevity and semantics • Async /await advantages: O 1 Simple, no anonymous functions, no need for extra data to avoid nesting o 2. Catch can handle json.parse errors O 3. Conditional statements can be usedCopy the code

25. New features in ES6

• Block fields, classes, arrow functions, template strings, object destructions, extension operators • Promise, modules, Symbol, proxy sets, function default parameters, REST, arrays, and extension of objectsCopy the code

26. HTTP and HTTPS

The default port number is 443. The default port number is 443. • HTTPS is more secure than HTTP, requiring a certificate from the CACopy the code

27. Browser rendering principle

• Browsers parse HTML documents into A DOM Tree • Css stylesheets are parsed into a CSSOM Tree • DOM and CSSOM are merged into rendering Tree This process is called attachment • Coordinates of each element of the rendering tree are given after accurate calculation, which is called layout • Each node of the rendering tree is drawn on the screen, which is called paintingCopy the code

28. What happened to entering the URL in the address bar

• The browser sends the requested URL to the DNS for domain name resolution, finds the real IP address, and sends a request to the server. • The server returns data after the background processing is completed, and the browser receives files (HTML, JS, CSS, images, etc.); • The browser parses the loaded resources (HTML, JS, CSS, etc.) and establishes the corresponding internal data structure (such as HTML DOM); • Load the parsed resource file, render the page, completeCopy the code

29. Callback functions

• A callback function is a function called through a pointer to a function. If you pass a pointer to a function as an argument to another function, when the pointer is used to call the function to which it points, Let's say this is a callback function • a callback function is not called directly by the executor of the function but is called by the other party when a particular event or condition occurs in response to that event or conditionCopy the code

Cookie, session

• (1) Cookie data is stored in the browser of the client, while session data is stored in the service. • (2) Cookies are not very secure, and others can analyze cookies stored locally and cheat cookies. (3) Session will be kept on the server for a certain period of time. When the access increases, the performance of the server will be affected. Therefore, in order to reduce the burden of the server, • (4) The amount of data stored in a cookie should not exceed 4KB, and many browsers limit the maximum number of cookies stored in a site to 20 • (5) For user information, important information related to login should be stored in session. Other information can be stored in cookies if it needs to be keptCopy the code

31, cross-domain

Cause: The same origin policy of the browser means that pages belonging to different domains cannot access each other. Different domain names 2 different port numbers 3 Different protocols (HTTP or HTTPS) 4. Domain names and corresponding IP addresses 5. Same primary domain names (127.0.01 and localhost) Multiple domain names match one IP address 6 2, JSONP principle: using the browser "vulnerability" SRC is not affected by the same origin policy, can request any link. Create a script tag dynamically, pass the pre-written function name to the server, (2) Get (pass function name); (3) callback (pass function name); { "/index.php": { "target": "http://qinqin.net", "changeOrigin": CORS is a W3C standard, full name is "cross-origin Resource Sharing". It allows browsers to make XMLHttpRequest requests to servers across sources (protocol + domain + port), overcoming the limitation that AJAX can only be used in the same source. The following two sentences need to be added to the server (source code that provides the interface). header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Method:POST,GET'); Jsonp is an informal transport protocol for solving cross-domain problem processes: SRC =test; SRC =test; callback=test; callback=test The script request completes and deletes itself from the pageCopy the code

Set and map

The default object representation of map in JS is {}, which is a set of key-value pairs, but the keys must be strings. To use Number or other data types as keys, the ES6 specification introduces a new data type Map. A Map is a structure of key-value pairs with extremely fast lookup times. Initializing a Map requires a two-dimensional array, or an empty Map has the following methods: var m = new Map(); // empty Map m.sat ('Adam', 67); // add a new key-value m.set('Bob', 59); m.has('Adam'); // if there is key 'Adam': true m.et ('Adam'); // 67 m.delete('Adam'); // delete key 'Adam' m.net ('Adam'); // undefined set Set is a set of keys, similar to Map. The difference is that a Set does not store a value, and its key cannot be repeated. To create a Set, provide an Array as input, or create an empty Set with the following methods: // Add (key) can be used to add elements to the Set. s; // Set {1, 2, 3, 4} s.add(4); s; Set {1, 2, 3, 4} var s = new Set([1, 2, 3]); s; // Set {1, 2, 3} s.delete(3); s; // Set {1, 2} add(value) : add a value, return the Set structure itself. Delete (value) : deletes a value and returns a Boolean value indicating whether the deletion is successful. Has (value) : Returns a Boolean value indicating whether the value is a member of Set. Clear () : Clears all members with no return value. 1. A MAP object is a collection of key-value pairs, similar to a JSON object, except that a key can be a string and can be a variety of other types of values, including objects that can be map keys. 2Copy the code

33, Instanceof principle

Instanceof can correctly determine the type of an object because the internal mechanism is to determine if the prototype of the object can be found in the prototype chain. Implement instanceof: - First get the prototype of the type - then get the prototype of the object - then keep checking whether the prototype of the object is equal to the prototype of the type until the prototype of the object is null, Because the prototype chain ends up null function myInstanceof(left, right) { let prototype = right.prototype left = left.__proto__ while (true) { if (left === null || left === undefined) return false if (prototype === left) return true left = left.__proto__ } }Copy the code

34. Monitoring data types

Four kinds of test method 1, the Object. The prototype. ToString. Call () function: all data types can detect, and correct grammar very much: Object. The prototype. ToString. Call (' XXX '/ 11 / []), the return value: [Object] XXX, XXX is the type of the Object, the constructor function 2: basic data types, and reference data types can detect defects: ("xx")/([])/(function(){}). Constructor === String/Array/ function True /false 3, The principle: determine the Object type, based on the prototype chain to determine (obj instanceOf Object) the left of the prototype chain proto has the right of the constructor's propToType property: Syntax: "/[]/true instanceOf String/Array/Boolean TypeOf (Arrary/function/object) returns object (Arrary/function/object); typeOf ""/[]/xx "String "/" Boolean "/"object"Copy the code

Constructors and ordinary functions

A constructor does not have a return value type. A normal function has a return value type. A void is used even if the function does not return a value. 2. Difference of function names: The function name of a constructor must be the same as the name of a class, and the function name of a common function must comply with the naming rules of identifiers. 3. Call difference: Constructors are called by the JVM when the object is created. Ordinary functions are called by us using objects. An object can object ordinary functions more than once, 4. The constructor is used to initialize an object. Ordinary functions are used to describe the common behavior of a class of things.Copy the code

Default events and bubbling events

To prevent bubbles: the W3C method is e.topPropagation (), IE cancels the default event with e.ancelBubble = true: The w3c method is e.preventDefault(), IE is e.returnValue = false;Copy the code

37, The difference between window object and document object

The window object represents an open window or frame in the browser. The window object is automatically created every time or every time it appears. In client-side JavaScript, the Window object is the global object, and all expressions are evaluated in the current environment. No special syntax is required to refer to the current window. You can use that window property as a global variable. For example, you can write document instead of window.document. You can also use window object methods as functions, such as alert() instead of window.alert. Window objects implement the global properties and methods defined by core JavaScript. The Document object represents the entire HTML document and can be used to access all elements in the page. Every HTML document loaded into the browser becomes a Document object. The Document object allows us to access all elements of an HTML page using scripts (JS). The Document object is part of the Window object and can be accessed through the window.document attribute. The HTMLDocument interface is extended to define htML-specific properties and methods. Many of these properties and methods are HTMLCollection objects. It holds references to anchors, forms, links, and other scriptable elementsCopy the code

38. Event loops

First, JS is executed in a single thread. Tasks in JS are executed one by one, but sometimes a task takes too long. Then the following tasks need to wait. In order to solve this situation, tasks are divided into synchronous tasks and asynchronous tasks. Asynchronous tasks can be divided into micro tasks and macro tasks. 1) Synchronous tasks and asynchronous tasks enter different execution "places" respectively. Synchronous tasks enter the main thread, and asynchronous tasks enter the Event Table and register functions. 3) If the tasks in the main thread are empty after execution, the Event Queue will read the corresponding function and enter the main thread for execution. 4) The above process is repeated over and over again, known as an Event Loop. So the main thread of the task execution is empty? In the JS engine, there is a monitoring process that continuously checks the main thread and, if it is empty, checks the Event Quene to see what functions are waiting to be executed. SetImmediate (Node) requestAnimationFrame(browser) {{setTimeout setInterval js} {setImmediate(Node) {{ In the then method of Process. nextTick Promise, the priority of micro task is higher than that of macro taskCopy the code

Js import and require

Import and require are used for JS modular programming. Modularity is a method of separating a system into separate functional parts. A module is a program or subroutine that performs a function. "Module" is the distinction between a single, replaceable part of a system: Import /export is a new specification introduced in ES6 due to browser engine compatibility issues. You need to compile ES6 syntax into ES5 syntax with Babel in Node require is called at runtime, so it can theoretically work anywhere in the code import is called at compile time, so it has to be at the beginning of the file require is assignment procedure, The result of require is an object, a number, a string, a function, etc., and the result is assigned to a variable. It is normal value copy passing. Import is a deconstruction process. Using import to import module properties or methods is reference-passing. Import is read-only, and the value is passed in one direction. Default is a keyword unique to ES6 modularity. Export default {} outputs the default interface object. If there is no name, you can define a name to associate this object when importingCopy the code

Vue

1. MVC and MVVM

• MVC (React) O Model: Data storage o View: user interface O Controller: View -> Controller -> Model -> View • MVVM (VUE) o model: data layer o view: view layer o View -> Controller -> Model -> View o MVVM: view <-> viewmodel -><- modelCopy the code

2. Vue life cycle

• beforeCreate: o Indicates the life cycle of the initialization event. • Cteated: indicates that data is injected to initialize responsive data. • beforeMount: indicates whether the EL and template options exist. • beforeUpdate, updated: o Triggers when data changes, and updates the DOM before and after • beforeDestroy, destroyed: O Trigger when a component is destroyed O When to use beforeDestroy WebSocket constantly connects, eliminates timer, listens for events • Activated: o Cache component is activated • Deactivated: O Called when a cache component is disabled • errorCaptured: called when a descendant component has failedCopy the code

3. Transfer values between components

The parent passes a value to the parent using the props property, and the child receives a value from the parent using the props property. When the parent passes a value, the parent uses v-bind to bind the variable name reserved in the child to the data in the data. Use this.$emit(' myEvent ') to emit and @myevent to listen on the parent component. Use custom event emit to emit and listen on the parent component. We can then pass values to any componentCopy the code

4. Define nested routines by

• Use the children configuration in the parameters of the VueRouter so that routing nesting is possibleCopy the code

5. Route redirection

• Declarative <router-link :to="/index/page1"></router-link> • Programmatic (js jump) router.push('index')Copy the code

6. Lazy route loading

Vue asynchronous component technology ==== Asynchronous loading VUE-router Configures routes and uses VUE asynchronous component technology to load routes on demand. /* Vue asynchronous component technology */ {path: '/home', name: 'home', component: resolve => require(['@/components/home'],resolve) },{ path: '/index', name: 'Index', component: resolve => require(['@/components/index'],resolve) },{ path: '/about', name: 'about', component: Resolve => require(['@/components/about'],resolve)} const Home = () => import('@/components/ Home ')  const Index = () => import('@/components/index') const About = () => import('@/components/about') { path: '/about', component: About }, { path: '/index', component: Index }, { path: '/home', component: Home} // Require. Ensure () // Vue -router configures routes using Webpack's require. Ensure technology, which can also be loaded on demand. // In this case, multiple routes with the same chunkName are combined and packaged into a single JS file. /* Require. Ensure () */ {path: '/home', name: 'home', component: r => require.ensure([], () => r(require('@/components/home')), 'demo') }, { path: '/index', name: 'Index', component: r => require.ensure([], () => r(require('@/components/index')), 'demo') }, { path: '/about', name: 'about', component: r => require.ensure([], () => r(require('@/components/about')), 'demo-01') }Copy the code

7, vuex

• Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue's official debugging tool devTools Extension, providing advanced debugging functions such as zero-configuration time-travel debugging, state snapshot import and export, etc. • Store in main.js, injection. Create a new directory store... . Export. The scenarios are as follows: Status between components in a single-page application. Music playing, login status, add to shopping cart O state unique data source. Data in Vue instances follows the same rules. O getters can be considered calculated properties of store. Getters are exposed as store.getters objects, The only way for o mutation to change the state in Vuex's store is by submitting mutation, which is very similar to an event, and triggering o Action via the store.mit method, which is similar to mutation, The difference is that an Action commits mutation instead of a direct mutation state. The Action can contain any asynchronous operation o Module. Because of the use of a single state tree, all the states of the application are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated. To solve the above problems, Vuex allows us to split the Store into modules.Copy the code

Vue-router hook

• Global navigation hook O router. BeforeEach (to, from, next), o router. BeforeResolve (to, from, next), o router. From,next) • Component inner hook O beforeRouteEnter, O beforeRouteUpdate, O beforeRouteLeave • Standalone route Exclusive component o beforeEnterCopy the code

9. Principle of two-way data binding

• Vue. Js adopts data hijacking combined with published-subscriber mode, using Object.defineProperty() to hijack the setter and getter of each property, publish messages to subscribers when data changes, and trigger corresponding listener callback. Observe's data objects need to be recursively traversed, including those of its child properties, with setters and getters so that assigning a value to the object triggers the setter and listens for data changes. Compile parses the template instructions, replaces variables in the template with data, initializes the render page view, and binds the corresponding node of each instruction to update functions, adds subscribers to listen to the data, once the data changes, receives notification, updates the view O step 3: Watcher subscribers serve as a communication bridge between the Observer and Compile and do the following: Update () = deP = deP = deP = deP = deP = deP = deP = deP = deP; O Step 4: MVVM, as the entry of data binding, integrates Observer, Compile and Watcher, uses Observer to monitor its model data changes, and uses Compile to parse and Compile template instructions. Finally, Watcher is used to build a communication bridge between Observer and Compile to achieve data change -> view update; View Interactive Changes (INPUT) -> Bidirectional binding effect of data model changesCopy the code

10, axios

• Install: NPM I axios-s • If a cross-domain request is sent, configure the reference in config/index.js: Because AXIos is not a plug-in for Vue, you cannot use the use method directly and need to load it into the prototype. To use AXIos globally, you need to set it to global in main.js, and then interact with the backend to fetch data in the vue project via this call. We usually use the AXIos library, which is a Promise-based HTTP library that runs in both the browser and Node.js. He has many good features, such as interception, transform json requests and responses, cancellation request, the client defense XSRF such as https://zhuanlan.zhihu.com/p/262665309Copy the code

11. The role of key in VUE

• Element uniqueness, diff method improves the performance of matching element index. Traversal of key-index object with key (fast), traversal of old Vnode without key (slow). • When the list of elements is constantly changing, it is very accurate to find/not find the changed element when the key is set to unique. When the key is not unique, it is not accurate to find the matched element.Copy the code

12, $nextTick

• The Vue implementation is responsive, not to change the DOM immediately after the data changes, but to update the DOM according to a certain strategy. • nextTick is a deferred callback performed after the next DOM update cycle, and when you use nextTick after modifying the data, you can retrieve the updated DOM in the callbackCopy the code

13. Vue component packaging process

• First, components can improve the overall development efficiency of the project. Abstract the page into several relatively independent modules, solve our traditional project development: low efficiency, difficult to maintain, reuse and other problems. • Then, create a component using the vue. extend method and register the component using the Vue.component method. Subcomponents need data, which can be defined in props. After modifying the data, the child component wants to pass the data to the parent component. You can use the emit methodCopy the code

14. Vue strict mode

• In strict mode, an error is thrown whenever a state change occurs that is not caused by a mutation function. This ensures that all state changes are tracked by the debugging tool. • Enable it in the vuex. Store constructor option, as follows const Store = new vuex. Store({strict:true,})Copy the code

A router is a route

• Router is VueRouter. If you want to navigate to different urls, use router.pushCopy the code

16. Common Loaders in Webpack

• file-loader: outputs files to a folder and references the output file with a relative URL in the code • url-loader: • source-map-loader: loads additional source map files to facilitate breakpoint debugging • image-loader: • babel-loader: convert ES6 to ES5 • CSS-loader: load CSS, support modularization, compression, file import and other features • style-loader: The CSS code is injected into JavaScript, and the CSS is loaded through DOM manipulation. • ESLint-loader: Checks JavaScript code through ESLintCopy the code

Hash mode and History mode

• Hash mode: O Principle: The Hash value after the # in the URL is monitored for changes in Hash value through the hashChange() event, and the corresponding route load is determined according to the Hash value of the routing table. Advantages: Only the front end is required to configure the routing table, and the back end is not required to participate in the compatibility. Browsers can support hash value changes and do not send requests to the back end, which is completely front-end routing. Disadvantages: • History mode: this mode takes advantage of HTML5's new pushState() and replaceState() apis to complete url jumps without reloading the page. Conforms to the URL address specification, does not need #, use more beautiful o disadvantages: When a user manually enters an address or refreshes a page, a URL request is initiated. The back end needs to configure the situation that the user on the index. HTML page cannot match static resources. Otherwise, a 404 error occurs. Takes advantage of the new pushState() and replaceState() methods in HTML5 History objects, which require browser-specific support.Copy the code

18. Virtual DOM and DIff algorithms

• Virtual DOM principle: Using object as a DOM node, I understand it as a virtual node, called vNode. Then, if the data is changed, a new VNode will be generated and then the old and new will be compared to generate the result and then render to the real DOM. We first generate a virtual DOM according to the real DOM. When the data of a node of the Virtual DOM changes, a new Vnode will be generated. Then Vnode and oldVnode will be compared. • Diff algorithm: compare the DOM node level, and compare whether the key value o is deleted or added. Diff calls a function called Patch to compare the old and new nodes and patch the real DOM as it does so. Comparing old and new nodes only uses keys when comparing lists at the same level so that nodes in the old DOM tree can be reusedCopy the code

V-if and V-for

In the actual development of VUE, we can't avoid using V-for and V-IF to manipulate data. However, when v-for and V-IF are used together, there is a precedence of running the data successively. V-for has a higher precedence than V-IF, which means that v-IF judgment will be called every time in the v-for loop. Therefore, it is not recommended to use v-if and V-for together in the same tagCopy the code

20, V-if and V-show

Differences: Means: V-if controls the explicit and implicit elements by controlling the presence or absence of DOM nodes; V-show sets the DOM element's display style, block to show, and None to hide. Compilation process: The V-IF switch has a partial compile/uninstall process in which internal event listeners and subcomponents are destroyed and rebuilt as appropriate; V-show is simply a CSS-BASED switch; Compile conditions: V-if is lazy, and if the initial condition is false, nothing is done; Local compilation starts only when the condition is true for the first time. The compile is cached and then partially unloaded when switching); V-show is compiled under any condition (whether the first condition is true or not), then cached, and DOM elements are preserved; Performance cost: V-IF has higher switching cost; V-show has a higher initial render cost; If the scenario needs to change very frequently, use V-show. It is better to use V-if if conditions rarely change at run timeCopy the code

21. Dynamic routing

1. The front end writes the routing table locally and the roles corresponding to each route, that is, which roles can see the menu/route. 2. During login, the backend requests the role of the login user (administrator or common user). 3. Use route interception to filter the routes corresponding to the user based on the obtained user role and compare the routes with the local routing table, and use the routes to render the left menuCopy the code

Segmentfault.com/a/119000001…

22. Use of global navigation hooks

1. Call away guard in A component. A beforeRouterLeave in component 2. Call the global beforeEach guard. Router. beforeEach 3. Invoke beforeEnter in route configuration B. 4. Perform the entry guard for component B. B beforeRouterEnter 5. Invoke the global beforeResolve guard (2.5+). Router. BeforeResolve 6. The navigation is confirmed. Call the global afterEach hook. AfterEach 8. Trigger a DOM update.Copy the code

23. The difference between calculating properties, listening properties and methods

• Computed properties: Properties that do not exist in raw data but are computed in real time at run time • Computed properties only have getters by default, although we can provide a setter if we need one. Computed properties are designed so that getters are clean and have no side effects. The final result of a calculated attribute depends on the change in the value on which it depends. O The method does not have a cache, so it only needs to be evaluated once. O If it can be used both times, it is recommended to use the calculated property, which costs less. • The calculated property and the listening property: O Evaluate properties to change themselves by changing other responsive data. Listeners listen for their own changes to change other responsive data. It's easier to evaluate properties if we're relying on multiple responsive data for valuesCopy the code

24. Prevent jitter in VUE

In the VUE project, we carry out anti-shaking, and cancel the last operation when the request is frequent. There are two ways. The first can be resolved using clearTimeout() and setTimeout() timers. The second can be resolved using Axios or throttled using LoDash: Throttling events is as simple as wrapping the functions to be called in LoDash's _.throttle function to prevent buffeting: Buffeting essentially groups our events together and prevents them from firing too often. To use throttling in a Vue component, simply wrap the function to be called in the _. Debounce function of LoDash.Copy the code

25. Vue core

Data driven, component system data driven: ViewModel, to ensure data and view consistency. Component systems: The application UI can be thought of as being entirely composed of component treesCopy the code