First, code level optimization
-
Distinguish between v-if and V-show scenarios
V-if is true conditional rendering, which forms a real DOM for switching, continuous destruction and generation. That is, it will shine as backflow.
V-show is much simpler. Regardless of the initial conditions, elements are always rendered and simply switched based on the display property of CSS.
-
Computed and Watch distinguish usage scenarios
Computed: Computed attributes depend on other attribute values, and computed values are cached. Only when the dependent attribute values change, the computed values will be recalculated the next time it obtains computed values. Practical applications such as shopping cart price calculation.
Watch: More of a “watch” function, similar to the listening callback for some data, which is executed for subsequent operations whenever the listening data changes.
-
V-for traversal must add a key to the item and avoid using v-if at the same time
In the traversal rendering of list data, the local reuse strategy is adopted to reduce DOM rendering, and a unique key value needs to be set for each item, avoiding the use of index. It is convenient for vue. js internal mechanism to find the list data accurately. When state is updated, the new state value is compared to the old state value to locate the DIFF faster.
V-for has a higher priority than V-if, and if you need to traverse the entire array every time, it will affect speed, especially if you need to render a small part of it. Replace this with a computed attribute if necessary.
-
Long list performance optimization
In our table presentation, the data tends to change very little, so we don’t need Vue to hijack the list variable. In the case of large data presentations, this can significantly reduce component initialization time.
export default { data: () => ({ users: {} }), async created() { const users = await axios.get("/api/users"); this.users = Object.freeze(users); }};Copy the code
-
Event destruction and calculator destruction
When we use addEventListener and $ON in Vue to listen for events, we need to manually remove these events during component destruction to avoid memory leaks.
created() { addEventListener('click', this.click, false) $on("click",function (msg) { console.log(msg) }) }, beforeDestroy() { removeEventListener('click', this.click, false) $off("click") } Copy the code
Of course we can also use $once to listen for an event, but only once. Once triggered, the listener is removed.
-
Route lazy loading
Vue is a single-page application, which may have a lot of routes introduced. In this way, the files packaged with WebPCAk are very large. When entering the home page, too many resources are loaded, and the page will appear white screen, which is not conducive to user experience. We only load it when the user accesses it, so it’s more efficient. This will greatly speed up the first screen display.
const Foo = () => import('./Foo.vue') const router = new VueRouter({ routes: [ { path: '/foo', component: Foo } ] }) Copy the code
-
Component lazy loading
In Vue, the page is composed of components one by one. When there are too many components on the page, we need the user to display only the required components, for example, when the user clicks to load a pop-up component to display.
export default { ..., components: { 'TabBar': ()=>import("./TabBar"); } } Copy the code
-
Use of keep-alive tags
When we switch back and forth between two components frequently, we use keep-alive to wrap and cache. For example: menu bar, etc.
<keep-alive> <comp-a v-if="a > 1"></comp-a> <comp-b v-else></comp-b> </keep-alive> Copy the code
-
Unpack to generate.map files
Some map files are automatically generated in JS after vUE project packaging. If an error is reported, the output error message does not know exactly where the code reported the error. With a map, you can output exactly which lines and columns are wrong, just like unencrypted code. But we don’t need that in a real production environment. Map files are said to leak project source code. So we unbuild in vue.config.js configuration.
module.exports = { build: { productionSourceMap: false, } } Copy the code
Second, use third-party plug-ins
-
Optimize infinite list performance
If your application has very long or infinitely scrolling lists, you may need to use windowing techniques to optimize performance, rendering only a few areas of content, reducing the time to re-render components and create DOM nodes. You can optimize this infinite list scenario by referring to the following open source projects vue-virtual-Scroll list and vue-virtual-scroller.
-
On-demand loading of component libraries
With babel-plugin-Component, we can reduce the size of the project by introducing only the required components. The following is an example of introducing an element-UI component library into a project:
1.1 installation Babel – plugin – component
npm install babel-plugin-component -D Copy the code
1.2 Changing the Configuration File Then change.babelrc to:
{ "presets": [["es2015", { "modules": false }]], "plugins": [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ] } Copy the code
-
Use server-side rendering
Server-side rendering refers to the process of Vue rendering the entire HTML fragment of the tag on the client side at 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. In the process of rendering on the client side, the data has been retrieved on the server side and put into HTML.
- 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;
- 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 just serves static files, so if you expect to use it in a high-traffic environment, prepare for the server load and use caching wisely.
Third, based on Webpack
The specific use here is not detailed. The version of the plug-in may be slightly different, basically the same, first install, then introduce the plug-in, then the plug-in related configuration.
-
Use image-webpack-loader to compress images.
-
Use uglipi.js to compress the code
-
Use vue-lazyLoad to implement lazy loading of images.
-
Use vue-skeleton-webpack-plugin to realize skeleton screen and reduce the anxiety of waiting for blank screen.
Fourth, the optimization of Web technology
The following optimizations are not only for VUE, but also for other projects.
-
Use compression to enable gzip compression. The response header will have a content-Encoding: gzip field when enabled. Of course, this requires our server to be configured with GZIP.
-
Browser cache, in order to improve the user load page speed, the cache of static resources is very necessary, according to whether to re-initiate a request to the server to classify, the HTTP cache rules are divided into two categories (mandatory cache, comparison cache).
-
Use of CDN.