A brief
Collected some interview questions that I think are good (please delete them if there is infringement)
HTML
Semantic HTML
HTML semantematization is about structuring the content of a page, and it has the following advantages
1, easy for users to read, style loss can make the page show a clear structure. 2, conducive to SEO, search engines according to the label to determine the context and the weight of each keyword. 3, convenient for other devices to parse, such as blind readers according to the semantic rendering of web pages 4, conducive to development and maintenance, semantic more readable, better maintenance of the code, and CSS3 more harmonious relationship, such as: <header> represents the header, <nav> represents the hyperlink area. <main> defines the main content of a document. <article> can represent articles, blogs, etc. <aside> usually represents a sidebar or embedded contentCopy the code
HTML 5 new label
<header>, <footer>, <aside>, <nav>, <video>, <audio>, <canvas>, etc...Copy the code
CSS
The box model
Box model is divided into standard box model and weird box model (IE model)
Box-sizing: content-box // Width +margin+border+padding Border-box // Weird box model element width is equal to the width in styleCopy the code
CSS features
-Howard: Transition to a transform, zoom, move, or tilt animation gradient shadow border-radiusCopy the code
Horizontal and vertical center
Flex layout
Display: flex // set flex mode flex-direction: column // determine whether the element is horizontal or vertical flex-wrap: wrap // determine whether the element is context-content: Space between / / under the same row alignment, blank space to separate each element align - items: center / / how to align the align - under the same row of elements content: space between / / alignmentCopy the code
Horizontal center
Inline elements: display: inline-block; Margin: 0 auto; Flex: display: flex; justify-content: centerCopy the code
Vertical center
Flex: display: flex; align-item: centerCopy the code
Ellipsis of text for multi-line elements
overflow : hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 3; // Set how many rows can be displayed -webkit-box-orient: verticalCopy the code
JavaScript
JS several basic specifications
1. Do not declare multiple variables on the same line. 4. Do not use global variables. 5. Switch statements must have default branches. IF statements must use curly braces. 9. Variables in for-in loops should be explicitly scoped with the var keyword to avoid scope contaminationCopy the code
JS base data type/reference type data
Data type Number, String, Boolean, Null, undefined, Object, symbol, bigInt Basic type (single type) String, Number, Boolean, Null, undefined Reference type The object. It contains function, Array, and DateCopy the code
An array of operating
ForEach: cannot break, can be stopped by throw new Error in a try/catch filter some: if one of the items returns true, the whole is true every: Join: generates string push/pop by specifying the concatenator, changes the array, returns push/pop Sort (fn)/reverse: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat: concat Return splice(start, number, value...) IndexOf/lastIndexOf(value, fromIndex): fromIndex: fromIndex: fromIndex: fromIndex: fromIndex: fromIndex Find the array item and return the corresponding subscript reduce/reduceRight(fn(prev, cur), defaultPrev): execute in pairs, prev is the return value of the last reduction function, cur is the current value (starting from the second item)Copy the code
What built-in objects do JS have
Object is the parent Object of all JavaScript objects: Object, Array, Boolean, Number, and String Other objects: Function, Arguments, Math, Date, RegExp, ErrorCopy the code
Error in the length of get request parameters
Myth: We often say that get request parameters are limited in size, while POST request parameters are unlimited (depending on the database field storage size). The HTTP protocol never specifies a get /POST request length limit. The restriction on get request parameters is the source and browser or Web server, which limits the length of the URL. To clarify this concept, we must reiterate the following points: The maximum length of GET is displayed because browsers and Web servers limit the LENGTH of URIs. 3. Different browsers and Web servers limit the maximum length of GET. If only Chrome is supported, the value contains a maximum of 8182 bytesCopy the code
closure
If function A contains function B and function B uses variables of function A, function B is called A closure. Function A() {var A = 1; function B() { console.log(a); } return B(); } ** Features of closures ** Functions are nested within functions. Internal functions can refer to arguments and variables that are not garbage collected. ** Understanding closures ** Closures are used primarily to design private methods and variables. The advantage of closures is that they can avoid the pollution of global variables, but the disadvantage is that closures will live in memory, which will increase the memory usage, and improper use will easily cause memory leaks. In JS, functions are closures, and only functions have scope. One of the main uses of closures is that you can read variables inside a function, and one of the other uses of closures is to keep those variables in memory at all times, The disadvantages of closures ** are that they consume memory. Improper use can cause memory overflow. Do not abuse closures, which can cause performance problems on web pages and memory leaks in IE. The solution is to remove all unused local variables before exiting the functionCopy the code
Prototype and prototype chain
** The concept of prototype and prototype chain ** Every object initializes a property inside it, which is prototype. When we access an object's property, if the property doesn't exist inside the object, it will look for the property in Prototype. This prototype will have its own prototype, Then I'll keep looking for the prototype and the relationship between the prototype chain of * * * *. The instance constructor. The prototype = instance. The prototype and the characteristics of the prototype chain __proto__ * * * * JavaScript object is 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 the Object built-in ObjectCopy the code
Componentization and modularization
Sometimes the page code is too large, too much logic or the same functional component is used in many pages, maintenance is quite complex, at this time, it is necessary to component development for function splitting, component encapsulation, component versatility has been achieved, enhance code readability, Maintenance costs can also be greatly reduced ** The advantages of componentized development ** greatly reduce the coupling of the various functions of the system, and improve the cohesion within the functions. This is of great benefit to front-end engineering and reduce the maintenance of the code. The reduction of coupling improves the extensibility of the system, reduces the complexity of development and improves the development efficiency. Reducing development costs Principles of component-based development Specificity configurability standards reusability maintainability ** ** Why modularity early versions of javascript had no block-level scope, no classes, no packages, and no modules, which caused some problems, Such as reuse, dependencies, conflicts, code organization chaos, etc., with the expansion of the front end, modularization is very urgent ** The benefits of modularization ** Avoid variable pollution naming conflicts improve code reuse rate improve maintainability easy dependency managementCopy the code
The difference between mouseover and MouseEnter
Mouseover: Events are triggered when the mouse moves over an element or its child, so there is a repetitive, bubbling process. The corresponding remove event is mouseout mouseEnter: When the mouse removes the element itself (which does not contain any child elements of the element), the event is triggered, that is, does not bubble, and the corresponding remove event is mouseleaveCopy the code
Understanding This object
This always refers to the direct caller of the function (not the indirect caller). If there is a new keyword, this refers to the object that came out of the new. In an event, this refers to the object that triggered the eventCopy the code
Vue
Tell me your understanding of SPA single page. What are its advantages and disadvantages?
SPA (Single-Page Application) loads the corresponding HTML, JavaScript, and CSS only 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, routing mechanisms are used to transform HTML content, interact with the user and avoid page reloading. ** advantages: ** - User experience is good, fast, content changes do not need to reload the entire page, avoid unnecessary jumps and repeated rendering; - Based on the above point, SPA exerts less pressure on the server; - The responsibilities of the front and back ends are separated, and the architecture is clear. The front end carries out interactive logic, and the back end is responsible for data processing; ** disadvantages: ** - Time-consuming initial loading: In order to achieve single-page Web application function and display effect, it is necessary to load JavaScript and CSS uniformly when loading the page, and some pages are loaded on demand; - Forward and backward route management: Because a single page application displays all contents on a page, the browser's forward and backward function cannot be used. All page switches need to establish their own stack management. - SEO is difficult: because all content is displayed dynamically on a page, it has a natural disadvantage in SEO.Copy the code
Vue life cycle
(1) What is the life cycle?
A Vue instance has a full life cycle, that is, from the start of creation, initialization of data, compilation of templates, Dom mounting -> render, update -> render, uninstall, etc. We call this the life cycle of a Vue.
(2) The role of each life cycle
The life cycle | describe |
---|---|
beforeCreate | When a component instance is created, before its properties take effect |
created | The component instance is fully created and the properties are bound, but the real DOM is not yet generated and $EL is not yet available |
beforeMount | Called before the mount begins: The associated render function is called for the first time |
mounted | El is replaced by the newly created vm.$el, which is called after being mounted to the instance |
beforeUpdate | Called before component data is updated and occurs before the virtual DOM is patched |
update | After the component data is updated |
activited | Keep-alive is exclusive and is called when the component is activated |
deactivated | Keep-alive is exclusive and is called when a component is destroyed |
beforeDestory | Called before component destruction |
destoryed | Called after component destruction |
Vue parent and child component lifecycle hook function execution order?
Vue's parent and child component lifecycle hook function execution sequence can be categorized into the following four parts: - Load the rendering process parent beforeCreate -> Parent created -> Parent beforeMount -> child beforeCreate -> child created -> child mounted -> Parent Mounted - Child component update process Parent beforeUpdate -> Child beforeUpdate -> Child updated -> Parent updated - Parent component update process Parent beforeUpdate -> Parent updated - Process parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyedCopy the code
In what lifecycle is the asynchronous request invoked?
You can call hook functions created, beforeMount, and Mounted because in these three hook functions, data is already created and can be assigned to the data returned by the server. However, I recommend calling an asynchronous request from a Created hook function, because invoking an asynchronous request from a Created hook function has the following advantages: - Faster access to server data, reducing page loading time; - SSR does not support beforeMount and Mounted hook functions, so creating in created helps consistency.Copy the code
What’s the difference between V-show and V-IF?
V-if is true conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch; Also lazy: if the condition is false during the initial render, nothing is done -- the conditional block does not start rendering until the condition is true for the first time. V-show is much simpler -- elements are always rendered regardless of initial conditions, and simply switch based on the "display" property of CSS. Therefore, V-IF is suitable for scenarios where conditions are rarely changed at runtime and do not need to be switched frequently; V-show is suitable for scenarios that require very frequent switching of conditions.Copy the code
Bind the array usage of class
V-bind :class="{'orange': isRipe, 'green': IsNotRipe}" array method v-bind:class="[class1, class2]" inline V-bind :style="{color: color, fontSize: fontSize+'px'}"Copy the code
What is the difference between computed and Watch?
**computed:** 1. Computed is a calculated attribute, that is, a calculated value, which is more commonly used in scenarios where values are calculated. 2. The next time the value of computed data is obtained, the corresponding getter is re-invoked for calculation. 3. Computed data is suitable for computing scenarios that compare consumption performance **watch:** 1. More of a "watch" function, similar to a listening callback for some data, to watch the props $emit or the value of this component, and perform the callback when the data changes. 2. No caching, the page is re-rendered without changing the value of ** summary :** 1. When we do numerical calculations, and we rely on other data, let's design this for computed 2. If you need to do something when the data changes, use Watch to watch the data changeCopy the code
Can Vue detect a change when it assigns a value directly to an array item? }
Due to JavaScript limitations, Vue cannot detect the following array changes:
- When you set an array item directly using an index, for example:
vm.items[indexOfItem] = newValue
- When you modify the length of an array, for example:
vm.items.length = newLength
To solve the first problem, Vue provides the following operations: Vue. Set Vue. Set (vm.items, indexOfItem, newValue) // Vue. $set(vm.items, indexOfItem, newValue) // array.prototype.splice vM. items. Splice (indexOfItem, 1, // array.prototype.splice vm.items. Splice (newLength)Copy the code
Can a parent component listen to the life cycle of a child component?
If the Parent component listens to the mounted component, then the Parent component does some logical processing.
// Parent.vue
<Child @mounted="doSomething"/>
// Child.vue
mounted() {
this.$emit("mounted");
}
Copy the code
$emit triggers the parent component’s event manually. A simpler way is to use @hook to listen when the parent component references the child component, as shown below:
// Parent. Vue <Child @hook:mounted="doSomething" ></Child> doSomething() {console. '); }, // child.vue mounted(){console.log(' Child component raises mounted hook function... '); }, // The child component triggers the mounted hook function... // The parent listens to the mounted hook function...Copy the code
The @hook method not only listens for Mounted, but also for other lifecycle events, such as created, updated, etc.
What do you know about Keep-Alive?
Keep-alive is a built-in component of Vue that can preserve the state of contained components and avoid re-rendering. It has the following features:
- It is used together with routing and dynamic components to cache components.
- Provide include and exclude attributes. Both of them support strings or regular expressions. Include indicates that only components with matching names will be cached, and exclude indicates that components with matching names will not be cached.
- The hook function activated is activated when a component is activated, and the hook function deactivated is activated when a component is removed.
Why is data a function in a component?
Why does data in a component have to be a function and then return an object, while data in a New Vue instance can be an object? // data data() {return {message: "child component ", childName:this.name}} // new Vue new Vue({el: '#app', router, template: '<App/>', components: {App} })Copy the code
If data is an object in a component, then the scope is not isolated. The data property values in the subcomponent will affect each other. If the data option in a component is a function, then each instance can maintain an independent copy of the returned object. Data property values between component instances do not affect each other; The instance of new Vue is not reused, so there is no object reference problem.
How does v-Model work?
In the VUE project, we mainly used v-Model instructions to create two-way data binding on form input, Textarea, SELECT, etc. We knew that v-Model was essentially just syntax sugar. The V-Model internally uses different attributes for different input elements and throws different events:
- Text and Textarea elements use value attributes and input events;
- Checkbox and radio use the Checked attribute and the change event;
- The SELECT field takes value as prop and change as an event.
Take the input form element for example:
<input V-model ='something'> equivalent to <input v-bind:value="something" V-on :input="something = $event.target.value">Copy the code
If in a custom component, the V-Model defaults to use a prop named Value and an event named input, as follows:
Parent: <ModelChild V-model ="message"></ModelChild> Child: <div>{{value}}</div> props:{value: String}, methods: {test1(){this.$emit('input', 'red ')},}Copy the code
How can Vue components communicate with each other?
Communication between Vue components is one of the knowledge points often tested in the interview. This question is similar to the open question. The more methods you answer, of course, the more bonus points, indicating that you are more proficient in Vue. Vue component communication refers only to the following three types of communication: parent-child component communication, intergenerational component communication, and sibling component communication. We will introduce each of these communication modes and explain which types of component communication this method can be applied to.
(1)props / $emit
Applicable to parent-child component communication
This method is the basis of the Vue component, and I believe most of you have heard of it, so I will not introduce it here with examples.
(2)ref
与 $parent / $children
Applicable to parent-child component communication
ref
If used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference refers to the component instance$parent
/$children
: Accesses the parent/child instance
(3)EventBus ($emit / $ON)
It is suitable for communication between father-child, intergenerational, and sibling components
This approach uses an empty Vue instance as the central event bus (event hub), which triggers events and listens for events to communicate between any component, including parent, generational, and sibling components.
(4)$attrs
/$listeners
It is suitable for intergenerational component communication
$attrs
: contains property bindings (except class and style) in the parent scope that are not recognized (and retrieved) by prop. When a component does not declare any prop, all parent-scoped bindings (except class and style) are included and can passv-bind="$attrs"
Pass in internal components. Often used in conjunction with the inheritAttrs option.$listeners
: contains a V-ON event listener in the parent scope (without the.native modifier). It can go throughv-on="$listeners"
Passing in internal components
(5)provide / inject
It is suitable for intergenerational component communication
The ancestor component provides variables through provider, and the descendant component injects variables through Inject. Provide/Inject API mainly solves the communication problem between cross-level components, but its usage scenario is mainly that sub-components obtain the state of the upper level components, and a relationship between active provision and dependency injection is established between cross-level components.
(6) Vuex is suitable for father-son, intergenerational and sibling component communication
Vuex is a state management mode developed specifically for vue.js applications. At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app.
- Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.
- The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change.
Have you ever used Vuex?
Vuex is a state management mode developed specifically for vue.js applications. At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app.
(1) The state storage of Vuex is responsive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.
(2) The only way to change the state in a store is to explicitly commit mutation. This allows us to easily track each state change.
It mainly includes the following modules:
- State: Data structure that defines the State of the application, where the default initial State can be set.
- Getter: Allows the component to get data from the Store. The mapGetters helper function simply maps the getters in the Store to local computed properties.
- Mutation: is the only method that changes the state in the store, and must be a synchronization function.
- Action: Used to commit mutation rather than directly change the state, and can include any asynchronous operation.
- Module: Allows you to split a single Store into multiple stores and Store them simultaneously in a single state tree.
Have you used Vue SSR? Tell me something about the SSR?
Vue.js is a framework for building client applications. By default, the Vue component can be exported to the browser for DOM generation and DOM manipulation. However, it is also possible to render the same component as server-side HTML strings, send them directly to the browser, and finally "activate" these static tags into a fully interactive application on the client side. That is, SSR roughly means that vUE renders the entire HTML fragment of the label on the client side and completes the work on the server side. The HTML fragment formed by the server side is directly returned to the client side. This process is called server side rendering.Copy the code
Advantages and disadvantages of server rendering SSR are as follows:
(1) Advantages of server-side rendering:
- Better SEO: Because the content of SPA page is obtained through Ajax, and the search engine crawl tool does not wait for the completion of Ajax asynchronism before grabbing the page content, so the content of SPA page obtained through Ajax cannot be captured; SSR is directly returned by the server to the rendered page (data has been included in the page), so the search engine crawler can grab the rendered page;
- Faster content arrival time (faster loading on the first screen) : SPA will wait for all Vue compiled JS files to be downloaded before rendering the page. File download takes a certain amount of time, so rendering on the first screen takes a certain amount of time. SSR directly returns the page rendered by the server directly, without waiting to download JS files and render again, so SSR has a faster content arrival time;
(2) Disadvantages of server-side rendering:
- More development constraints: for example, server-side rendering only supports the beforCreate and Created hook functions, resulting in some external extension libraries requiring special handling to run in server-side rendering applications; And unlike fully static single-page application SPA, which can be deployed on any static file server, server-side rendering applications need to be in the Node.js server running environment;
- More server load: Rendering a full application in Node.js is obviously more CPU-intensive than a server that only serves static files, so if you expect to use it in a high traffic environment, Prepare your server load and use caching strategies wisely.
How many vue-router routing modes are there?
Vue-router has three routing modes: hash, history, abstract. The corresponding source code is as follows:
switch (mode) { case 'history': this.history = new HTML5History(this, options.base) break case 'hash': this.history = new HashHistory(this, options.base, this.fallback) break case 'abstract': this.history = new AbstractHistory(this, options.base) break default: if (process.env.NODE_ENV ! == 'production') { assert(false, `invalid mode: ${mode}`) } }Copy the code
The three routing modes are described as follows:
- Hash: Uses the URL hash value for routing. Support for all browsers, including those that don’t support the HTML5 History Api;
- History: Relies on the HTML5 History API and server configuration. See the HTML5 History mode;
- Support all JavaScript runtime environments, such as node.js server side. If the browser API is not found, routing automatically forces the mode into this mode.
Can you explain the hash and history routing modes used in vue-router?
(1) Implementation principle of hash mode
Early implementations of front-end routing were based on location.hash. The principle is simple: the value of location.hash is what comes after the # in the URL. For example, here’s a website whose location.hash value is ‘#search’ :
https://www.word.com#search
Copy the code
The hash routing mode is implemented based on the following features:
- The hash value in the URL is only a state of the client, that is, when a request is made to the server, the hash part will not be sent.
- Changes to the hash value add a record to the browser’s access history. So we can switch the hash through the browser’s back and forward buttons;
- You can use the a tag and set the href attribute. When the user clicks on the tag, the HASH value of the URL will change. Or use JavaScript to assign loaction.hash to change the HASH value of the URL.
- We can use the HashChange event to listen for changes in the hash value to jump (render) the page.
(2) The realization principle of history mode
HTML5 provides the History API to implement URL changes. The two main apis are history.pushstate () and history.repalcestate (). Both apis allow you to manipulate the browser’s history without refreshing it. The only difference is that the former is to add a history, while the latter is to replace the current history directly, as shown below:
window.history.pushState(null, null, path);
window.history.replaceState(null, null, path);
Copy the code
The history routing pattern is implemented based on the following features:
- PushState and repalceState apis to implement URL changes;
- We can use the PopState event to listen for URL changes to jump (render) the page;
- History.pushstate () or history.replacEstate () will not trigger the popState event, so we need to trigger the page jump (rendering) manually.
How does Vue implement bidirectional data binding?
Vue two-way data binding mainly refers to: data changes update view, view changes update data, as shown in the following figure:
That is:
- When the content of the input box changes, the Data in Data changes synchronously. View => Data changes.
- As the Data in Data changes, the content of the text node changes synchronously. Data => View changes.
Among them, View changes update Data, can be achieved through the way of event listening, so Vue two-way Data binding work is mainly how to update the View according to Data changes.
Vue implements bidirectional data binding through the following four steps:
Implement a listener Observer that iterates over data objects, including properties of child property objects, adding setters and getters to all properties using Object.defineProperty(). So, if you assign a value to this object, it will trigger the setter, so you can listen for changes in the data.
Implement a parser Compile: parse Vue template instructions, replace variables in the template with data, and then initialize render page view, and bind the corresponding node of each instruction to update function, add subscribers to listen to the data, once the data changes, receive notification, call update function for data update.
Implement a subscriber Watcher: The Watcher subscriber acts as a bridge between the Observer and Compile. Its main task is to subscribe to the message of the change of attribute value in the Observer. When the message of the change of attribute value is received, the corresponding update function in the parser Compile is triggered.
Implement a subscriber Dep: The subscriber uses a published-subscribe design pattern to collect subscriber Watcher and manage listener Observer and subscriber Watcher uniformly.
Proxy versus Object.defineProperty
Advantages of Proxy are as follows:
- Proxies can listen directly on objects rather than properties;
- Proxy can listen for array changes directly;
- Proxy has up to 13 interception methods, not limited to apply, ownKeys, deleteProperty, has, etc. Object. DefineProperty does not have;
- Proxy returns a new Object. We can only manipulate the new Object to achieve our purpose. Object.defineproperty can only be modified by iterating through Object attributes.
- Proxy as the new standard will be subject to browser vendors focus on continuous performance optimization, which is the legendary performance bonus of the new standard;
Object.defineproperty has the following advantages:
- It has good compatibility and supports IE9, but Proxy has browser compatibility problems and cannot be smoothed by Polyfill. Therefore, the author of Vue announced that Proxy can be rewritten until the next big version (3.0).
What does a key do in Vue?
The key is a unique token for a Vnode in a Vue. With this key, our diff operation can be more accurate and faster. The DIff process of Vue can be summarized as follows: OldCh and newCh variables each have two end oldStartIndex, oldEndIndex and newStartIndex, newEndIndex, they will be old and new node node pairwise comparison, namely a total of 4 kinds of comparative way: NewStartIndex and oldStartIndex, newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, If none of the four comparisons match, if the key is set, the comparison will be performed using the key. During the comparison, the traversal will move towards the middle, and the comparison will end once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed.
Therefore, the function of key in Vue is: Key is the unique mark of Vnode in Vue. Through this key, our diff operation can be more accurate and faster
The sameNode function a. keey === B. Keey can be compared with the sameNode function a. keey === B. So it’s more accurate.
Faster: using the uniqueness of the key to generate map objects to obtain the corresponding nodes, faster than traversal, the source code is as follows:
function createKeyToOldIdx (children, beginIdx, endIdx) {
let i, key
const map = {}
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key
if (isDef(key)) map[key] = i
}
return map
}
Copy the code
What optimizations have you made to the Vue project?
** (1) Optimization at the code level ** -V-if and V-show distinguish between use scenarios - computed and Watch distinguish between use scenarios - V-for traversal Must add key for item, And avoid using v-if - long list performance optimization - event destruction - image resource lazy loading - route lazy loading - third party plug-in on demand - optimization of infinite list performance - Server render SSR or pre-render ** (2) Optimization of Webpack level ** - Webpack to compress images - reduce ES6 to ES5 redundant code - Extract common code - template precompile - Extract components CSS - optimize SourceMap - Build result output analysis - Optimize compilation of Vue projects ** (3) basic Web Technical optimizations ** - Enable Gzip compression - Browser caching - Use CDN - Use Chrome Performance to find Performance bottlenecksCopy the code
ES6
Var, let, const
Var is not limited to block level. Var maps to window. Let does not map to window. Var can access variables above the declaration. Const, like let, does not map to window, supports block-level scope, and calls variables above the declaration do not get an errorCopy the code
Deconstruction assignment
Deconstruction of * * * * array let [a, b, c] = [1, 2, 3] / / a = 1, b = 2, c = 3 let [[e] d, f] = [[2] 1, 3] / / nested array deconstruction d = 1, e = 2, f = 3 let [g, ... h] = [1, 2, 3] / / array resolution g = 1, h = [2, 3] let [I, j] = [1, 2, 3] / / discontinuous deconstruction I = 1, j = 3 let [k, l] = [1, 2, 3] / / not completely deconstruction k = 1, L = 2 object deconstruction of * * * * let {a, b} = {a: 'aaaa' b: 'BBBB'} / / = a = 'aaaa' b 'BBBB' let obj = {d: "aaaa", e: {f: Let 'BBBB'}} {d, e, {f}} = obj / / nested deconstruction d = 'aaaa' f = 'BBBB' let g; (g = {g: "aaaa"}) / / to declare variables deconstruction g = 'aaaa' let (h, I, j, k) = 'nice' / / string deconstruction h = 'n' I = 'I' j = 'c' k = 'e'Copy the code
Function default arguments
Error: if main is set to a default value, then avoid using it. function saveInfo({name= 'william', age= 18, address= 'changsha', gender= 'man'} = {}) { console.log(name, age, address, gender) } saveInfo()Copy the code
ForEach, for in, for of
ForEach is more commonly used to iterate over numbers, such as objects, or json for of array objects. To iterate over objects, loop over keys with object.keys () for in and loop over valuesCopy the code
What should I pay attention to when using arrow functions?
This cannot be used as a constructor. This means that you cannot use the new command, otherwise an error will be thrown. Therefore, arrow functions cannot be used as Generator functionsCopy the code
The difference between Set and Map
Application scenario Set for data reorganization, Map for data storage **Set: **\ 1, the member cannot repeat \ 2, only the key value has no key name, similar to the array \ 3, can be traversed, the methods are add, delete,has **Map:**\ 1, is essentially a collection of key pairs, similar to the set \ 2, can be traversed, can be converted to various data formatsCopy the code
Write a promise by hand
Var promise = new promise ((resolve,reject) => {resolve(value)} else {reject(error)}}) promise.then(function (value) { // success },function (value) { // failure })Copy the code
Ajax
How do I create an Ajax
(1) Create an XMLHttpRequest object, that is, create an asynchronous call object; (2) create a new HTTP request and specify the method, URL, and authentication information for the HTTP request; (3) set up the function that responds to the change in the status of the HTTP request; (4) send the HTTP request (5) Get the data returned by the asynchronous call; (6) Use JavaScript and DOM to implement local refreshCopy the code
The difference between synchronous and asynchronous
Synchronization: When the browser requests the server, the user sees the page refresh and sends the request again. After the request is complete, the page is refreshed and the user sees the new content and performs the next operation
Asynchronous: The browser requests from the server. The user performs normal operations and the browser requests from the back end. When the request is finished, the page is not refreshed, the new content will also appear, and the user will see the new content
Advantages and disadvantages of Ajax
** Advantages of Ajax ** 1, updating data without refreshing (maintaining communication with the server without refreshing the entire page); 2, asynchronous communication with the server (communicating with the server in an asynchronous manner without interrupting user operations); 3, front-end and back-end load balancing (giving some back-end work to the front-end, Reduce server and width burden) 4, separation of interface and application (Ajax separates interface and application i.e. data and presentation) ** Disadvantages of Ajax ** 1, Ajax does not support the browser back button; 2, security issues Aajax exposes the details of server interaction Weak search engine support; 4. Broken browser mechanisms such as the normal behavior of the Back and History buttonsCopy the code
Get and POST
2. Get is less secure than POST. 3. Get is cached, while POST is not. Post is not visible \ 6. Get accepts only ASCII characters as parameter data types, and there is no restriction on POST. Post will submit the request againCopy the code
How to solve cross-domain problems
The concept of cross-domain is that only the protocol, domain name, and port are the same. Otherwise, cross-domain problems are solved: * * 1, using the json (json + padding) filling in the data \ 2, CORS mode (cross-domain resource sharing), on the backend configuration can cross domain \ 3, server agent, through the server file resources, access to a third partyCopy the code
Github
Git common commands
Git add. Git commit -m or git commit -a Check the workspace status: git status -s Pull and merge remote branches: git fetch/git merge or git pull Check the commit records: git reflogCopy the code
webpack
Webpack packaging principles
Webpack is simply a mechanism for packaging modules and simply turning dependent modules into static files that represent those packages. Webpack is the entry file that identifies you. Identify your module dependencies to package your code. Whether your code is using CommonJS or AMD or ES6 import. Webpack will analyze it. To get the code’s dependencies. What WebPack does is analyze the code. Transform code, compile code, output code. Webpack is a node module, so webpack.config.js is written in CommonJS (modularity in Node is the CommonJS specification).
Module hot update
Module hot update is a feature of Webpack that enables code changes to be updated without refreshing, the advanced version of the auto-refresh browser
In devServer, hot replacement of modules can be controlled through the hot propertyCopy the code
Through the configuration file
const webpack = require('webpack'); const path = require('path'); let env = process.env.NODE_ENV == "development" ? "development" : "production"; const config = { mode: env, devServer: { hot:true } } plugins: [new webpack HotModuleReplacementPlugin (), / / thermal load plugins], module. Exports = config;Copy the code
Through the command line
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "NODE_ENV=development webpack-dev-server --config webpack.develop.config.js --hot",
},
Copy the code
How to speed up WebPack building
2. Use DllPlugin and DllReferencePlugin to precompile NPM packages that we reference but never modify. The Happypack plugin does not support file-loader and url-loader. The Happypack plugin does not support file-loader and urL-loader. So these two loaders do not need to be replaced with Happypack, Use tree-shaking and Scope as an example to remove redundant code. Use fast-sass-loader instead of sass-loader The cacheDirectory parameter or transform-Runtime plugin can be added to the babel-loader to create common files that duplicate during runtime
// webpack.config.js
use: [{
loader: 'babel-loader',
options: {
cacheDirectory: true
}]
// .bablerc
{
"presets": [
"env",
"react"
],
"plugins": ["transform-runtime"]
}
Copy the code
No need to package compiled plug-in libraries with the global “script” tag introduced the way
JQuery plugin, React, react-dom, etc., it’s a lot of code, it’s a lot of time to package it up. Then use the expose-Loader or externals or ProvidePlugin in the Webpack configuration to provide the corresponding variables for use inside the module
// @1
use: [{
loader: 'expose-loader',
options: '$'
}, {
loader: 'expose-loader',
options: 'jQuery'
}]
// @2
externals: {
jquery: 'jQuery'
},
// @3
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
Copy the code
8. Optimize the search path at build time
When WebPack is packaged, there are all kinds of paths to query and search, and we can add some configuration to make it search faster for example, module paths that are easy to change to absolute paths, Use the resolve alias alias field and exclude to exclude files that do not need to be traversed
### WebPack advantages focus on the processing of modular projects, can be done out of the box, one-step can be extended by plugin, complete and easy to use and flexible use scenarios are not limited to the Web development community large and active, often introduce new features to keep up with the development of The Times, Find existing open source extensions for most scenarios Good development experience ### Disadvantages of WebPack The disadvantage of WebPack is that it can only be used for projects with modular developmentCopy the code
Wechat applets
Main contents and functions of files
- component —————————————————— Component folder - navBar - Bottom component - navbar. js - JS code for bottom component - navbar. json - Configuration file for bottom component - WXSS -- CSS code of the bottom component -- pages ————————————————————— Page folder -- index -- Home page -- index.js WXML -- HTML code of the home page -- index.wxss -- CSS code of the home page -- public -- -- -- -- -- -- -- -- -- -- - picture folder - utils -- -- -- -- -- -- -- -- -- -- -- tools folder - API. Js - control API file - md5. Js - tools - md5 encrypted file - Timestamp. Js - tools - timestamp files - app. Json -- -- -- -- -- -- -- -- --, set the global data, and so on the basis of - app. WXSS -- -- -- -- -- -- -- -- -- --, common style, You can import more -project.config. json ———————— project configuration files by using importCopy the code
Wechat applets life cycle
OnLoad () : Triggered when the page loads. OnShow () : triggered when the page is displayed/cut to the foreground. OnReady () : Triggered when the first rendering of the page is complete. OnHide () : triggered when the page is hidden or in the background. OnUnload () : Triggered when a page is unloaded.Copy the code
How to encapsulate data requests
1. Encapsulate interfaces
Project/utils/API. JsCopy the code
Const fetch = ({url, data}) => {console.log(' 【step 1】API: ${url} '); Console. log(" [step 2] data: "); console.log(data); Return new Promise((resolve, reject) => {wx.request({url: getApp().globaldata.api + url, data: If (res.data.code == 0) {console.log("【step 3】 request success: "); console.log(res.data); return resolve(res.data); } else {wx.showmodal ({title: 'request failed ', Content: res.data.message, showCancel: false}); }}, fail: err => {// Processing console.log(err); return reject(err); }})} /** * code for openId * @data {* jsCode - wx.login() return code *} */ export const wxLogin = data => {return fetch({ url: "tbcUser/getWechatOpenId", data: data }) }Copy the code
Page data passing
Options: <navigator URL =".. /index/index? userId={{userId}}"></navigator> <! OnLoad: function(options) {console.log(options.userid); } Pass arguments to Storage: wx.setStoragesync ('userId', 'jsliang'); wx.getStorageSync('userId'); WXML <text bindtap="clickText" data-labelid ="{{userId}}"> Click to transfer data to JS</text> login. JS clickText(e) { Console. log(e.currenttarget.labelid)} Component calls parameter component to receive data: component-tag-name Component({properties: {// The innerText property is defined here. The value of the innerText property can be specified when used by the component: {type: String, value: Json {"usingComponents": {"component-tag-name": ".. /component/component"}} Use the component page HTML code <view> <! -- The following is a reference to a custom component --> <component-tag-name inner-text="Some text"></component-tag-name> </view> Pass parameters through interface callsCopy the code
Load performance optimization method
Use this.$preload() to preload the second page that the user may click on. 2Copy the code
Differences between wechat applets and native APP, Vue and H5
** Advantages of wechat applets ** 1, no download; 2, faster opening speed; 3, lower development cost than native APP ** Disadvantages of wechat applets ** 1, more restrictions. The page size should not exceed 1M, and no more than 5 levels of pages should be opened. The internal components of the small program have become permanent, and the style can not be modified. Micro channel small program has the advantages of low development cost, low customer cost, no need to download ** micro channel small program VS H5** 1, depending on different environment. One runs in multiple mobile browsers. A non-complete browser that can only be used in wechat. 2. Different development costs. One may have problems in various browsers. A ** wechat applet that can only run in wechat VS Vue** * wechat applet looks like a neutered version of VueCopy the code
Micro channel small program principle
Essentially a single page application, all page rendering and event processing, are in a page structure for data-driven mode, UI and data separation, all page updates, all need to change the data to achieve micro channel small program is divided into two parts: WebView and appService. Among them, WebView is mainly used to display UI, and appServer is used to process business logic, data and interface call. They are carried out in two processes, through the system layer JSBridge to achieve communication, UI rendering, event processing
Similarities and differences between WXML and standard HTML
WXML is based on XML design, and tags can only be used in wechat mini programs, not HTML tags
Network protocol
The network layer
At present, network stratification can be divided into two types: OSI model and TCP/IP model
OSI model Application layer Presentation layer Session layer Transport layer Network layer Data Link layer Physical
TCP/IP model Application Host-to-host Transport Layer Internet Network Interface layer
HTTP/HTTPS
2. HTTP is a hypertext transfer protocol that transmits information in plaintext, while HTTPS is a secure SSL encryption transfer protocol. 3. 4. HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP.
The HTTP status code
Discriminant Status code 1 x x start – Information 2 x X start – The request succeeds 3 x X start – The request is redirected 4 x X start – Request error 5 x X start – Server error
Common status code 200 – Request successful, Ajax received message 400 – Server does not understand request 403 – server rejected request 404 – Request page error 500 – Server internal error, unable to complete the request
Performance optimization
HTML optimization
1. Avoid writing CSS code in HTML as it is difficult to maintain. 2. Use Viewport to speed up page rendering. Use semantic tags to reduce CSS code, increase readability and SEO. 4, reduce the use of tags, DOM parsing is a large traversal process, reduce unnecessary tags, can reduce the number of traversal. 5. Avoid null SRC, href, etc., because browsers will initiate HTTP requests even if they are null. 6. Reduce the number of DNS queriesCopy the code
CSS optimization
1. Optimize the selector path: use.c {} instead of.a.b. c {}. 2. Selector merge: common attribute content is lifted to compress space and resource overhead. 3, Precise style: Use padding-left: 10px instead of padding: 0, 0, 10px. Sprite images: Combine small ICONS into one image so that all images only need to be requested once. Avoid wildcard:.a. b * {}, according to the parse order from right to left in the parsing process encountered wildcard * {} 6, will traverse the entire DOM, performance significant loss. 7. Use less float: Float is computationally expensive to render, so use Flex layouts instead. 8, for 0 value to unit: increase compatibility. 9, compress the file size, reduce the burden of resource download.Copy the code
JavaScript to optimize
1, as far as possible to put the <script> tag after the body, to avoid JS execution stuck DOM rendering, to ensure the page as soon as possible to display 2, as far as possible to merge JS code: extract public methods, object-oriented design...... 3, CSS can do things, as far as possible not JS to do, after all, JS parsing execution is rougher, and CSS is more efficient. 4. Manipulate the DOM as much as possible, and pre-order CSs styles to reduce reflow or repaint. 5. Create the DOM as little as possible and use display: None in HTML and CSS to hide and display as needed. 6, compress the file size, reduce the burden of resource download.Copy the code