preface

Hello, everyone, I am _ like a boy ❤ Recently the company is really too idle, just want to put the summary before into a running account, when nothing kang Yikang, is usually writing some small experience of the project and steal from you there, no more nonsense, start my performance ~~

Code optimization

1. Modularization and componentization
  • Components encapsulate commonly used things, and the most important thing is reuse.
  • Module is to separate the same function or business code, reduce the coupling between modules, can run and manage independently.
  • CSS is also available with less and SASS to reduce duplicate code.
2. VFor key

When v-for is used to render a list of elements, a unique key is set for each item to make it easier to locate the data inside the Vue.

We all know to avoid using index subscripts as keys, for example:

let arr = [
   { id: 1.title: 'one' },
   { id: 2.title: 'two' },
   { id: 3.title: 'three' }
]
arr.splice(1.1) console.log(arr) Copy the code

When the index changes and all the keys in the list change, V-for re-renders the element with the changed key, but nothing else changes except the deleted element, causing Vue to use the wrong old child node to do a lot of unnecessary work. So try not to use index as the key, use id as the key, don’t use random number as the key, delete old nodes, create new nodes, your boss will be angry.

3. VFor and 2 vIf is based

When used with V-if, v-for has a higher priority. Obviously, you need to make a judgment every time you render a list. It’s better to use computed to filter out unwanted values.

V-show is the simple operation of display, which has a higher initial rendering cost, and is suitable for frequent DOM switching. (Find yourself using V-IF directly for most projects)

4. Lazy loading

4.1 Lazy Route Loading

Speed up the first screen rendering.

{
  path: "/tips".  name: "tips".  component: resolve= > require(["@/views/tips"], resolve),
  meta: {
 title: "Route lazy loading"  } } Copy the code

As for the optimization of the first screen, a large project may have a blank screen due to incomplete loading, so you can add a loading prompt or start page.

4.2 Lazy loading of images

  • Most frameworks have a lazy image loading function, use it often.
  • Load small images using Base64
  • Use SVG and font ICONS whenever possible
5. Keep alive the cache

Keep-alive is an abstract component used to cache components to save performance. The state of a component wrapped in keep-alive is preserved to avoid re-rendering.

<! '<transition>' -->
<transition>
  <keep-alive>
    <component :is="view"></component>
  </keep-alive>
</transition> Copy the code

Using the include and exclude attributes, both can be represented as comma-delimited strings, regular expressions, or an array. Include indicates that only components whose name attribute is A and B will be cached, but other components will not be cached. Exclude indicates that all components will be cached except those whose name attribute is C.

<! -- component name, not route name
<keep-alive include="a,b">
      <router-view></router-view>
</keep-alive>
<keep-alive exclude="c">
 <router-view></router-view> </keep-alive> Copy the code
6. Hook hook

I always thought hook was exclusive to react until I used this callback hook.

(1) In the same component

mounted() {
 // In Vue components, you can use $on,$once to listen for all lifecycle hook functions
 // You can use the hook listener component to destroy the hook function and cancel the listener event
 this.$once("hook:beforeDestroy", () = > {   // It is recommended that private property names start with $_
 window.removeEventListener("resize".this.$_handleListen);  }); }, Copy the code

(2) parent and child components

<! All lifecycle hooks of a component can be listened for by @hook: hook function name.
<component @hook:updated="$_handleListen" />
Copy the code

Most functions can be implemented without a hook, but when a third-party component library does not implement the @change callback, a hook is really a thief!

7. Object.freeze()

If you have a large Array or Object and are sure the data won’t change, using object.freeze () can give performance a big boost.

mounted() {
  let arr = [1.2.3.4.5]
  Object.freeze(arr)
}
Copy the code

Concat can also be used to add data when it is scrolling, and using object.freeze () properly can save a lot of rendering performance.

8. Watch to monitor

For example, on a list page, we hope that when users enter search keywords in the search box, the search can be triggered automatically, and the change of search keywords can be monitored through watch.

data() {
  return {
    serachValue: ' '
  };
},
watch: {  // Reload the data after the value changes  searchValue: {  // Use handler to listen for property changes. The first call to newValue is an empty string and oldValue is undefined  handler(newValue, oldValue) {  if(newValue ! == oldValue) { console.log('Did something');  }  },  // Trigger immediately if initialization is required to load data  immediate: true. If the deep property is true, watch will listen for every change in the value of the object  deep: true  } }, Copy the code
9. Functional components

Functional components can be considered for purely presentational business components that only need to present data that is passed in from the outside without internal state or processing in lifecycle hook functions. (I didn’t do it, but I’ll add it later.)

// Since functional components do not create component instances, all properties traditionally called through this need to be called through context
Vue.component('my-functional-button', {
  functional: true.  render: function (createElement, context) {
    return createElement('button', context.data, context.children)
 } }) Copy the code

Project optimization

1. On demand

Use UI framework as much as possible as needed to introduce, reduce redundant overhead, reasonable timely stop loss.

2. Load some resources externally through CDN
  • External reference modules that need not be packaged can be brought in through the CDN.
  • There are also some big pictures accelerated by CDN
3. Vue. Config. Js configuration

If you do not set the package to generate some map files, the production environment can use the map to view the source code.

module.exports = {
    productionSourceMap: false.}
Copy the code

Official Config Reference documentation

4. Remove unnecessary code and reduce the use of images
  • Remove some comments and printed code…
  • Images take up a large part of the volume, and some image effects can be achieved with CSS3…

Afterword.

Project optimization is very important, every little optimization is to improve their own responsibility for the project, about the project optimization is not so simple, there are a lot of things we need to learn, I hope we try more, learn together.

If you feel that the article is not bad, point a praise to point to encourage by, also hope that you can point out in the comments I good timely correction, big guys have what good method also comment out let me learn to learn ~ (this this this this skin also Mrs. Mrs. Good-looking!

This article is formatted using MDNICE