1. The parent component’s life cycle loads the render
To understand the parent component’s life cycle load rendering. First, let’s talk about the component lifecycle
The life cycle
After a VUE instance is created, it goes through an initialization process that includes data listening, compiling templates, mounting DOM, updating DOM, and so on.
In the declaration cycle, there are functions for lifecycle hooks that add code writing at different loading stages.
beforeCreate()
After an instance is initialized, data is called before it is initialized, and data in methods, data, and computed cannot be accessed
created()
Initialization of the data is complete, but the EL is not yet mounted. In CREATED, data and methods can be accessed and changed
beforeMount()
The first call to the Render function (virtual DOM) completes the initialization of the data and HTML, but has not yet been mounted to the browser
mounted()
Once the HTML rendering is mounted, you can also perform ajax operations (but only once)
beforeUpdate()
In this hook function, the state can be changed without triggering additional rerendering
updated()
Both the data and the DOM have been reupdated, and in most cases, it is best not to change the state there, as this can cause an infinite loop of updates and the hook function will not be called during server rendering
beforeDestroy()
Called before instance destruction, you can also perform operations:
- Use this to get the instance
- Be aware of the timer in the component or the DOM events that it listens to
destroyed()
Called after instance destruction, the hook function is not called during server rendering
The life cycle of parent and child components
Parent beforeCreate–> parent created–> parent beforeMount(–> child beforeCreate–> child created–> child mounted–>) Parent mounted
The activated phase is triggered if a child component is wrapped by keep-alive
Parent beforeUpdate–> Child deactivated–> Parent updated
Parent beforeDestroy–> child beforeDestroy–> child deStoryed –> Parent destroyed
2. Differences between computed and Watch
Characteristics of computed attributes
- Support caching, dependent on data changes, only back to recalculate
- Asynchronism is not supported. When there is asynchronous operation in computed, data changes cannot be monitored
- Values in computed are computed from values declared in data or from values obtained in props
- In computed, the get and SET methods are used. The default get method is used when computed property values are functions, and the default set method is used when data changes
- Computed is mostly used in many-to-one or one-to-one relationships
Watch listens to the characteristics of the property
- Caching is not supported and data changes with changes
- Support asynchronous operation
- The listening function takes two arguments, a new value and a previous value
- The data to be listened on must be declared data (either in data or in props)
- More than a pair of
watch: { watchTest: { handle(newName, oldName) { this.name = newName + oldName }, immediate: Deep: true, // When the component is loaded, the handle callback is triggered immediately.Copy the code
3. V – show and v – the if
v-show
V-show actually controls display in CSS and only compiles once
v-if
V-if dynamically adds and removes elements from the DOM tree, but v-if is a performance drain
In common
Both show and hide elements
4. Introduction to vuex
Vuex is a state management tool for Vue. Vuex consists of five core modules:
- Store is used to store data state
- Mutations for the manipulation of data in the store, use commit to call (state, payload).
- Getters processes the data in the store and returns it
- Actions Asynchronous operation, call with dispatch, (context, payload)
- Modules Modularize state management, dividing the store into different modules, each module has Store, Mutations, getters, actions
5. Introduction to cookies
What is a cookie
Cookies are generally used by the server to determine the state of the user. When the client visits the server, the server will send a cookie to the client and store it in the browser. When the browser is opened next time, the client will send the cookie to the server, and the server will judge the user’s status accordingly.
The mechanism of cookies
Client HTTP request server –> server response Client with cookie– > client HTTP request server with cookie– > server reponse client
Cookies have some property values in them
- NAME=VALUE: Sets the VALUE to be saved
- Expires: Sets the cookie expiration date maxAge(s) (if the internal value is negative, it is a temporary cookie; If the built-in value is 0, the cookie is deleted.)
- Domain: indicates the Domain name that generates cookies
- Path: the Path where cookies are generated. / is all paths
- Secure: If this property is set, cookies are returned only during SSH connections
6. LocalStorage and sessionStorage
In common
Data can be stored in the browser cache (as a string)
The difference between
- Data in localStorage can be stored permanently, while sessionStorage will be deleted after the browser closes
- Different pages in the same browser can share data in localStorage, but different pages cannot share data in sessionStorage
7. Prototypes and prototype chains
What is a prototype chain?
The JS Object has a chain (proTO) that points to the prototype Object. When accessing the properties of an Object, it will follow the chain (header: Object) layer by layer (proximity principle) until the end of the chain.
Why use prototype chains?
- Implementation inheritance
- Everything in the chain is accessible. Prototype implements inheritance and attribute sharing (reference types)
- Code redundancy is avoided and common properties and methods can be called at any time
- Reduced memory
How to use prototype chain?
Proto: a property that exists for every object, like a chain
Prototype: Constructor prototype. Only functions have it
function doSomething(){}
console.log( doSomething.prototype );
var doSomething = function(){};
console.log( doSomething.prototype );
Copy the code
8. V – model principle
V-model is just a syntactic sugar that is essentially triggered by v-bind’s event binding with V-ON. By the way,
Two-way binding of data
The implementation of two-way binding of data comes from the object.defineProperty () function, which listens for GET and set events
The bidirectional binding of Vue is implemented according to the publisher-subscriber pattern. The listener Observer listens for changes in data and tells the subscriber Watcher if they happen (data hijacking using objec.defineProperty and notifying the subscriber via set and GET methods) and updates the corresponding data and views if they are updated.
There is a parser Compile, which can scan and parse the relevant instructions of each node (such as: V-model, V-ON, etc.). If there is a node, it initializes the data, view and trusted subscriber Watcher.
9. v-on
V-on can be bound to multiple events, or multiple events can be individually bound to multiple V-Ons
Bind events have multiple modifiers: prevent, Stop, keyUp, keyPress, keypress, and so on
10. What common loaders does Webpack have
Generally, loader is configured in the following ways:
- webpack.config.js
- Command line arguments
- inline
Common loaders:
- CSS: style-loader, CSS-loader, less-loader, sass-loader, postCSS-loader…
- File: raw-loader, file-loader, url-loader…
- Compiler: babel-loader, ts-loader…
- Check tests: jshint-loader, eslint-loader…
Common plugins:
- Html-webpack-plugin automatically generates HTML files that reference CSS and JS
- Extract-text-webpack-plugin extracts styles referenced in JS into separate CSS files
- DefinePlugin configures global variables at compile time
11. The relationship between Webpack, Vue and Node
Vue development does not depend on Node, but the webpack integrated in VUe-CLI is based on Node development, that is, Webpack depends on Node.
But Node often helps front-end development with engineering, and NPM can help download available plug-ins during development.
12. Packaging process of Webpack
Start from initializing option –> start compiling –> recursively analyze dependency building from Entry Entry –> parse each module location –> build module –> compile module loaded by Loader, generate AST tree –> traverse AST, collect dependencies –> optimize –> output to Dist
13. Performance optimization
- Reduce HTTP requests (debounce) to trigger only once
- Use font ICONS and SVG instead of picture ICONS as much as possible
- Webpack
- Not reloading the same content (max-age)
- Image lazy loading + responsive image + CSS effect instead of image + image compression + WebP format image
- Reduce redraw rearrangements (some page actions cause pages to be rearranged and rendered)
- Reduce event delegation (delegate to the parent using event bubbling to make the parent take on the task of event listening)
- Visual changes are implemented using requestAnimationFrame to ensure that JavaScript runs at the start of the frame
- Use Web Workers to perform tasks without interfering with the page
- Optimize the DOM tree and use gzip to compress files
- Use Object.freeze() in Vue to improve skills
- Component lazy loading
- Server-side rendering (SSR) and Prerender optimize loading performance
- Load balancing
14. Solution for slow loading of the first screen of a single page
Use performance. Timing or DOMContentLoad to calculate the first screen time
- The UI framework loads on demand
- SSR server rendering, through the server to generate HTML strings and then sent to the client (nuxt.js)
- GZIP compression
- Reduce entry file size: route lazy loading
- Compress image resources
- Static resource local cache
- Using HTTP Cache, set cache-Control, last-Modified, Etag and other response headers
- Use Service Worker offline cache
- localStorage
- Modify the CommonsChunkPlugin configuration in config to remove files that are frequently repeated and put them in a public area to avoid repeated invocation
15. Load the progress bar
Returns (n)% progress results (beforeSend, complete, success) when the page is loaded in the specified area between before and after loading
16. Why do some Vue plug-ins use use
Using vue.use () is the component’s install method that is called, and the values passed in internally can only be objects or functions
17. Browser cache
Understanding the browser cache can be optimized to some extent.
The cache location
-
Service Worker
With the Service Worker, the transport protocol must be HTTPS (for security), which gives us freedom to control which files are cached, how the cache is matched, how the cache is read, and the cache is persistent.
-
Memory Cache
A cache in memory that contains resources that have been captured in the current page. However, the window cache is also released once closed. (But it doesn’t care about caching resources)
-
Disk Cache
The cache on the hard disk determines, based on the fields in the HTTP Herder, which resources need to be cached, which resources can be used without being requested, and which resources have expired and need to be re-requested.
-
Push Cache
The push cache, which exists only for sessions, is released once the Session ends, and the cache duration is short.
The cache
The browser’s handling of the cache is determined by the response header returned when the resource is first requested.
Strong cache
Resources are read directly from the cache without sending a request to the server. This is done by setting two HTTP headers: Expires (when the resource Expires) and cache-control (which controls web caching).
Negotiate the cache
After the cache is forcibly invalidated, the browser sends a request to the server with the cache ID. The server decides whether to use the cache based on the cache ID.
-
The negotiated cache takes effect, returns 304 and Not Modified, and continues to use the cache
-
Negotiation cache invalid, return 200 and request result