Performance optimization

  1. Functional components have no lifecycle and no parameters, and can be rendered directly by using propo to obtain the parameters passed by the parent component, saving performance
  2. Local variables can also have a performance cost when operations repeatedly fetch those listening properties, so storing variables in local variables can save performance
  3. The use of v-if and V-show should be used when the component will frequently show shadow switching
  4. KeepAlive, when some pages do not need to obtain the latest data and are frequently viewed, can use KeepAlive to avoid repeated loading, and KeepAlive also has a declaration cycle, need to make some small changes can be completed in the declaration cycle
  5. Isn’t data a function? Just hang these properties on this before returning
  6. The import() method loads components in the router using the improt method on demand
  7. Webpack code segmentation, can be more than how many k code separate out, to avoid the first screen loading too slow
  8. Make good use of computed caching
  9. Use vue-lazyLoad to implement lazy loading of images
  10. The on-demand import of UI components can be done with babel-plugin-Component
  11. Vue-virtual-scroll -list is used to load a long list. The principle is to display only the DOM in the visible area
  12. Optimize – CSS-assets-webpack-plugin with the ability to compress CSS with mini-CSs-extract-plugin However, it overwrites webPack’s built-in UglifyJS compression, so terser is also needed to compress JS. This configuration is generally in the production environment optimization
  13. Use your browser’s cache
  14. The CDN to accelerate

Package speed optimization

NoParse: Prevents Webpack from resolving some JS dependencies and speeds up packaging, which is risky and requires more testing

DllPlugin: I usually create a new file to write, which specifies some third party libraries that need to be removed, such as the Vue family, using DllPlugin to generate the index, using the library to set the exposed variables, and using the DllReferencePlugin to specify the index file in the main package file

The little knowledge webpack

Tree Shaking removes code that is not referenced by scope as part of a package. It will preparse the results as part of a package, reducing the size of the code and running faster.

Analysis of interview questions

vue

1. The parent-child component rendering process of vue

BeforeMount The child component starts rendering after the parent component executes to beforeMount the parent component executes mounting

2. New properties of the object cannot update the view. Deleting properties cannot update the view. How to do?

Vue will only listen for the data in the component initialization return data

3. What about nextTick?

It is generally used to get the latest DOM, and it can also be used to get DOM elements in Created. When I was making tables, I needed to implement the previous and next data, so I needed to use nextTick to wrap this function. Otherwise, the selected row of data cannot be set to highlight

4. What are the communication modes of components?

1. The props

2. Emit to the parent component

3. Busevent Intermediate transmission

4.vuex

5. The browser caches such as LocalStroge cookies

5.Vue routing implementation: Hash mode and history mode

Hash mode: hash is present in the URL but not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages. In hash mode, only the content before the hash symbol is included in the request, such as www.xxx.com. Therefore, the back end will not return a 404 error even if the route is not fully covered.

History mode: The URL of the front end must be the same as the URL of the back end, for example, www.xxx.com/items/id. The back end will return a 404 error if there is no routing for /items/ ID. Vue-router’s official website states: “However, this mode needs to be configured in the background to play well… So, you add a candidate resource on the server that covers all cases: if the URL doesn’t match any static resource, the same index.html page should be returned

6.
r o u t e and The route and
The difference between the router

Route is a routing information object, including path, Params, Hash, Query, fullPath, matched, name and other routing information parameters. A router is a “route instance” object that includes hop methods, hook functions, and so on

7. Data is a function

Because directly it’s an object all the components’ data will point to the same memory address, and the object returned by a function will return a whole new object. In fact, you can attach a data property to a constructor’s prototype chain and then the data used by the instance of that function will be the data of that address, If returned by a function, the instance can be called with a new data

8.Com Puted and Watch differences and application scenarios?

Computed is cached, which means that if the parameter that’s passed in doesn’t change, it just returns the value without doing any computation, and watch is listening for a property change, which means that when the value changes, I perform this callback, and when we’re just doing simple value computation, we can use computed, Watch is used when we need to do some asynchronous or special processing based on value changes

react

1. What is the difference between a class component and a function component?

Class components can use other features, such as state States and lifecycle hooks.

A stateless component is a functional component when it simply receives props rendering to the page. It is also called a dumb component or presentation component.

2. Component communication

Father to son

{/* Render child component */} <XiaoWang name={this.state.lastName} getChildMsg={this.getmsg}></XiaoWang> {/* inside child component */} < ponclick = </p> handleClick = ()=>{// Call method this.props. GetChildMsg ()}Copy the code

Child to parent: A child component receives a method from a parent component and passes the parameter as props by calling that method in the child component

3. Life cycle

Constructor, and then componentWillMount that’s what you do before you mount the component, and then render to mount the DOM, and then componentDidMount which is the most important thing to do is to send a request to render data, and then you’re done with the render phase, ShouldComponentUpdate this is used to determine if the data has changed and is updating the view, if it’s updating, then we say componentWillUpdate this is before the update, and then we say componentDidUpdate, Then there is the subcomponents componentWillReceiveProps call when it is to receive new attributes, finally is componentWillUnmount, uninstall before execution

4.render-props

The render function in the component returns a set of data and then using the component you can call render to render the view or you can use children to return it

// Render render() {const {x, y} = this.state return this.children (x, y)} // render render() {const {x, y} = this.state return this.children (x, y)} Y) = > (< p > the current Mouse position: (x: {x}, y: {y}) < / p >)} < / Mouse >Copy the code
5. Advanced components

It takes a component through a function, does some reusable logic inside the function, and returns the wrapped component

6.setState

Setting a value multiple times in a single logical process, only taking the last value to execute, can be avoided by changing the way the call is made

this.setState( state => { return { count: State.count + 1}}, // When the component is rerendered, Log (' component updated ', this.state.count) console.log(document.querySelector('h1').innertext)})Copy the code

js

1. Two methods of inheritance
function Son(name) { Father.call(this); this.name = name || "son"; } // son.prototype = object.create (Father. Prototype); / / repair the constructor to Son. Prototype. Constructor = Son;Copy the code
class Son extends Father {//es6 constructor(name) { super(name); this.name = name || "son"; }}Copy the code
2. Anti-shake and throttle

The concept of anti-shake: set a time, when triggered, into the countdown, before the end of the countdown if triggered again, then the countdown will be re-timed

Throttling concept: set a time, when triggered, into the countdown, before the end of the countdown can not be triggered again, the end of the countdown can be triggered again

3. Which operations cause memory leaks

1. The closure

2. Unexpected global variables

3. The forget timer

5. No dom element references are cleaned

4. Micro and macro tasks

Microtasks: A typical microtask is the THEN method,

Macro task: settimeOut

Priority: First, the browser will execute the synchronization task, and then it will detect the microtask macro task it suspends one by one, and then after the synchronization task is completed, it will retrieve the microtask, and then execute the macro task after the microtask is completed.

5. Differences between Typeof and Instanceof in JS

Typeof: Detects only raw data types and returns only object when an array object is detected

Instanceof: This is based on the prototype chain, a instanceof B is to determine whether A has inherited b returns true and false

6. Const let variables

Const is a constant, and ordinary properties cannot be changed objects and arrays cannot be changed to the address to which they point, meaning you can change the content, not the reference.

Similarities: Let and const are block-level scoped properties. They do not have the same variable promotion as var and cannot be declared repeatedly.

7. What methods does Object have
Seal () seals an object and prevents new properties from being added. The value of the original property can be changed. The original property points to an object and new properties can be added. Freeze () Completely freezes an object. No new attributes can be added, no existing attributes can be deleted, and the prototype of an object cannot be modified after it is frozen. Keys () get all the enumerable key of an object Returned as an array Object. The prototype. ToString, call () are commonly used to check the data type The return value for [object XXXX] String Array, etc HasOwnProperty () determines whether an object has specified attributes in its own attributes. DefineProperty (obj, key, descriptor), which does not include methods on the object's prototype chain, is used to define attributes of an object. If the key does not exist, create a new key for the object. The writable: true can be modified, enumerable: true can be enumerated, and the different: true can be deleted. You can also pass in a Get set method, which is how VUE does the bidirectional binding. IsPrototypeOf () is used to determine whether the current object is on the prototype chain of the passed argument object, such as the constructor. IsPrototypeOf (instance object a) valueOf() returns the original valueOf the object, which may be a string, value, or bool, depending on the object.Copy the code
8. Pseudo-array to true array

Array.call from() [].slice.call

9.ES6 arrow function

Do not use an argumetns constructor. Use an argumetns argument instead. Do not use argumetns. The arrow function has no prototype object.

10. Js array common methods

Push () adds an item to the end of the array

Pop () removes and returns the last element of the array, or undefined if the array is empty

Unshift () adds an entry to the head of the array and returns the array length

Shift () deletes the first item in the array and returns the deleted item

Concat () joins two arrays to return a new array

Join () concatenates each item of an array with the specified character to form a string. The default connection character is “, “comma

Reverse () makes the array that calls the method reverse

Sort (), pass a function as argument, return a-b from small to large, b-a from large to small

Map () iterates through the array and returns a new array. The value of return is the items in the new array

Slice () starts at start, ends before end, and ends before end; If end is not given, start to end of array

ForEach () iterates through the array

Filter () returns a new array after iterating through the array

Every () evaluates each item in the array, returning true if it matches, false otherwise

Some () evaluates each item in the array, returning false if none of them match, and true otherwise

The first argument of reduce() is the callback function, and the second argument is the initial value, which defaults to 0 if the callback is not set. The callback function has four arguments: the first is the return value of the previous round, the second is the item traversed in the current round, the third is the coordinate, and the fourth is the array to call the method

11. The prototype chain

Given a P constructor, the constructor’s prototype points to p.prototype,

The constructor of p.prototype again points to P

Proto, an instance of P, will look up to find P’s prototype

The prototype of P can also use proto and then it will look up to find the prototype of Object and then null

The constructor’s proto points to the prototype of the big constructor’s proto points to the object’s prototype

Both proto and Prototype of the large constructor point to the prototype of the large constructor

The proto of the object constructor points to the prototype of the large constructor

Only large constructors and object constructors have proto. Normal constructors do not

css

1. Clear floats

Overflow: hidden

The parent element sets the height directly

You can also write a div clear both at the end but that’s not very performance friendly

::after {
            content: '.';
            height: 0;
            display: block;
            clear: both;
        }
Copy the code
2. What is BFC

The root element, or HTML tag, is the best BFC, meaning that the internal layout does not affect the external layout, and the floating element is involved in calculating the height

Generate condition float, overflow is auto, scroll, hidden, Display is inline-block, table-cell, table-caption, table, inline-table, flex, and position is absolute and fixed

3. Achieve vertical and horizontal center

Absolute positioning or Flex remember both

4.flex

Flex-direction Specifies the main axis layout mode. Colum is vertical. The default value is Row

The flex – wrap: wrap nowrap | wrap | wrap – reverse;

justify-content: The display mode of the spindle is center space-between space-around flex-start flex-start space-between indicates that there is a gap on both sides, and space-around indicates that there is no gap on both sides.

Align-items: The default display mode is “stretch”. If the height of an item is not set or the value is set to “auto”, it will take up the entire container. Flex-start Flex-end Center baseline: the baseline alignment of the first line of the item is baseline

align-content: flex-start | flex-end | center | space-between | space-around | stretch; Defines the alignment of multiple axes. If the project has only one axis, this property will not work. When you flex-wrap is set to NowRAP, the container will have only one axis, because the project does not wrap, so there will be no multiple axes.

5. The position

Static (default) : Arranges documents according to normal document flow

Relative: does not leave the document flow, refers to its static position by top, bottom, left, right

Absolute: The reference to the nearest non-static parent is located by top, bottom, left, and right

Fixed: A fixed reference to the viewable window

6. What are the new features of CSS3

RGBA and transparency background-image and background-size text-shadow border-radius media query

7. The meanings of 1rem, 1em, 1vh and 1px

1rem: the font size of HTML

1em: Font size relative to the parent element

1vh/1vw: 1% of window width and height

Personal Summary:

1. The principle of MVVM

Two-way binding: Hijacking data via defineProperty

Compiling templates: I’m going to take all the nodes and I’m going to use this createDocumentFragment method and I’m going to go through those nodes and see if it’s a text node or a node, and I’m going to remove the curly braces with the re, and I’m going to replace them with the value, Node nodes are going to recursively iterate over and get the instructions on them and if they’re instructions get the values of the instructions and set them to the element node

Watch: The observer, when detecting the use of attributes on data (v-text model or {{}} on text node) during template compilation, will create a new watch, in which he will get the initial value of corresponding attributes, and since all values are being monitored, The get method on defineProperty is executed when fetching, where watch can be added to the DEP array and wathC provides an update method

Dep. Target = this; Let value = this.getVal(this.vm,this.expr); let value = this.getVal(this.vm,this.expr); Dep.target = null;Copy the code

Dep: Publish subscribe, one deP for each data. When data changes, the set method on defineProperty is executed. This method drops the watch updata in the DEP array and the callback to modify the view is executed

2. Encapsulate components through mixins

We need to bring in the element’s table component and pager, and then we need to accept the column data for props and display it through the for loop, and then we need to accept some Boolean value for props to show image or not to show image, and then create a new mixin. In this to introduce encapsulated table components, through mixin, I can use the data and methods provided by the table in this, and I can use the method of introducing pages as long as the page is written according to my specification of this mixin, which can simplify the development process, but also simplify the code of the page.

3. Verify the VUE permission

The router has a method onReady, which is a method that the router executes only once when it is ready. Then check whether there is a token and request the backend to obtain the permission form, and then compare with the previously written route list. The filtering page is dynamically added to the router, and the token is set during login and the user permission list is directly obtained. We can define a variable in the AXIos request to prevent repeated validation, and then when we find an error in the request 401, WE can refresh the token interface. When entering the home page, there are usually multiple requests, so we need to create an array. When the variable is false, we will put these requests into the array. When the token refresh is completed, we will execute these requests in the callback

4. Implementation principle of VUEX
  1. Install mixin with a beforecreate hook, This.$store. XXX can be used in the template if the root component is mounted directly or not by fetching the parent component’s store
  2. Get getters and extract the key from object. Key and then iterate over it. In the iterate, extract getters function names and functions and assign them to the getter in the Store class
  3. The other two do the same thing but we need to write a prototype link function commit because the user needs that function to change the state and that function takes a function name and then calls the change state function in store
5. Resumable transmission of large files

1. First require an input of type=”file” and then select the file

2. Once the file is selected, the browser turns it into a Blob object with a slice method that slices it and stores it into an array.

3. Then iterate over the array map and add some hash name attributes after filename cutting, and encapsulate the sliced data into one formdata after another.

3.5 Hash Can be generated using Spark-MD5. Create a web-worker to generate hash to avoid UI congestion. Encapsulate spark-MD5 to public because of the same-origin policy.

4. Store the formData in an array, send the formData as a parameter to the back end, and get the progress bar in axios’ onUploadProgress callback.

5. Then you can calculate the total progress from the shard progress you get and bind it to the view. Then you need to use the Promise all method to request the merge API on the back end after the group of upload requests are sent.

6. Can pass axios. CancelToken to suspend transmission, then continuingly can request to the server to have uploaded file hash name, and then filter out already uploaded files, the rest will continue to upload.

7. There is a problem with the progress bar, that is, the progress that has been uploaded successfully is calculated as 100% and then included in the total progress bar, and if the progress bar is smaller than the current progress, it will not be updated.