Code optimization makes us easy to ignore a point in our usual work, this note will briefly talk about some optimization points at the vUE code level

Route lazy loading

  • Definition: Lazy loading is simply lazy loading or on-demand loading, that is, loading when needed.

  • Function: The component is loaded only when the route is accessed, which is more efficient

  • Use:

    1. The import method proposed by ES6 (most commonly used)

    const router = new VueRouter({
        routes: [{path: '/foo'.component:() = > import('./Foo.vue')}]})Copy the code
2. Vue asynchronous components implement lazy loadingCopy the code
    const router = new Router({
      routes: [{path: '/'.name: 'HelloWorld'.component: resolve= >(require(["@/components/HelloWorld"],resolve))
        }
      ]
    })
Copy the code

The official document: router.vuejs.org/zh/guide/ad…

Keep-alive cache page

  • Definition: Keep-Alive is a built-in component of Vue that caches inactive component instances rather than destroying them when wrapping dynamic components. Like Transition, keep-Alive is an abstract component: it does not render itself as a DOM element, nor does it appear in the parent component chain.

  • Function: The state is kept in memory during component switching to prevent repeated DOM rendering, reduce loading time and performance consumption, and improve user experience.

  • Use:

    1. Cache all pages

    //App.vue
    <template>
      <div id="app">
      	<keep-alive>
          <router-view/>
        </keep-alive>
      </div>
    </template>
    Copy the code

    2. Cache pages based on specific criteria

    <template> <div id="app"> //1. <keep-alive include='test'> <router-view/> </keep-alive> //2. <keep-alive include='a,b'> <router-view/> </keep-alive> //3. Use regular expressions, you need to use the v - bind < keep alive: - include = '/ a | b/' > < the router - view / > < / keep alive - > / / 4. <keep-alive :include='includedComponents'> <router-view/> </keep-alive> //5. <keep-alive exclude='test'> <router-view/> </keep-alive> </div> </template>Copy the code

    3. Cache some pages with vue-Router

    const router = new Router({
          routes: [{path: 'user'.name: 'user'.component: User,
              meta: {
            	keepAlive: true  // Cache is required}}, {path: 'list'.name: 'list'.component: List,
              meta: {
            	keepAlive: false  // No caching is required}]})Copy the code

    4. Run the $route.meta command to set whether to cache

    <template> <div id="app"> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="! $route.meta.keepAlive"></router-view> </div> </template>Copy the code

Reference: cn.vuejs.org/v2/api/#kee…

V – show reuse DOM

Here’s a question: When do you use V-if and when do you use V-show

<template> <div class="cell"> <! <div v-show="value" class="on"> <div v-show="value" class="on"> - Heavy is a relatively Heavy dom element - > < Heavy: n = "10000" / > < / div > < div v - show = "!" value" class="off"> <Heavy :n="10000"/> </div> </div> </template>Copy the code

Use v-show if you need to repeatedly display the hidden DOM frequently, because v-show is the underlying use of display control to show the hidden dom.

V-if is to delete and re-add a DOM element to control the show hiding, also from the dom optimization point of view, more frequent show hiding V-show is more appropriate.

And if the DOM element is heavy and bulky, v-show is more appropriate.

V-for traversal avoids using v-if simultaneously

 <template>
     <ul>
         <li v-for="user in activeUsers"
         :key="user.id"
         >
         	{{user.name}}
         </li>
     </ul>
 </template>
<script>
export default {
  computed: {
    activeUsers:function () {
      return this.users.filter(function(user){
        return user.isActive
      })
    }
  }  
};
</script>
Copy the code

If you need an if judgment in v-for, it is recommended to make a calculation attribute, filter the array to be displayed first, and loop through only the data to be displayed. This avoids the if judgment every time

Reference: cn.vuejs.org/v2/style-gu…

Long list performance optimization

Judge the presentation of long lists and do different processing

  • If the list is purely a data presentation and nothing changes, there is no need to be reactive

    export default {
      data: () = > ({
        user: []}),async created () {
        const users = await axiox.get('/api/users');
        // object. freez Freezes data
        this.users = Object.freeze(users); }};Copy the code
  • If it is a long list of big data, virtual scrolling can be used to render only parts of a small area

    <recycle-scroller
          class="items"
          :items="items"
          :item-size="24"
        >
          <template v-slot="{item}">
            <FetchItemView
              :item="item"
              @vote="voteItem(item)"
            >
            </FetchItemView>
          </template>
      </recycle-scroller>
    Copy the code

    Reference materials: vue-virtual-scroller, vue-virtual-scroll list

Destruction of events

When a Vue component is destroyed, all its instructions and event listeners are automatically unbound, but only for the component’s own events

 created () {
    this.timer = setInterval(this.refresh, 2000);
  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
Copy the code

There is a timer set in this component that is functionally bound to the component’s Created life cycle. It is recommended to clear this timer in beforeDestroy to prevent memory leaks

Lazy loading of images

For pages with too many pictures, in order to optimize the loading speed of the page, we often need to not load the pictures that do not appear in the visual area of the page, and then load them after scrolling to the visual area

<img v-lazy="/static/img/1.png">
Copy the code

Reference plug-in: vue-lazyload

Third-party plug-ins are introduced on demand

In actual development, some UI libraries, such as Ant Design or Element UI, which are very large, can be introduced as needed rather than as a whole, reducing the burden

import Vue from 'vue'
import { Button, Select } from 'element-ui'

Vue.use(Button)
Vue.use(Select)
Copy the code

Stateless components are marked as functional components

Set up some components that simply present data as functional components, which have no component instances and consume less resources at run time.

<template functional>
    <div class="cell">
        <div v-if="props.value" class="on"></div>
        <section v-else class="off"></section>
    </div>
</template>

export default {
  props: [value],
};
Copy the code

Subcomponent segmentation

If you have some time-consuming tasks in a child component, it is recommended that you treat it as a separate component and let it render itself

<template> <div> <ChildComp/> </div> </template> export default { components:{ ChildComp:{ methods: {heavy () {/ * time-consuming task * /}}, render: (h) {return h (' div ', this heavy ())}}},};Copy the code

Localization of variables

Example:

<template> <div :style="{opacity:start / 300}"> {{result}} </div> </template> <script> import {heavy} from '@/utils' export default { props: ['start'], computed: {base() {return 42}, result(){const base = this.base // don't use this.base let result = this.start for (let I = 0; i < 1000; i++) { result += heary(base); } return result } }, }; </script>Copy the code

In this case, base localization prevents multiple uses of this.base to access computed properties

SSR

  • What is SSR? The simple idea is to pass a component or page through the server to generate AN HTML string, send it to the browser, and finally “blend” the static markup into a fully interactive application on the client side

  • SSR server rendering

    Advantages:

  1. Friendlier SEO:

    Fully rendered pages can be viewed directly due to search engine crawler crawl tools

  2. Better for first screen rendering

The rendering of the first screen is an HTML string sent from Node, not a JS file, which makes it easier for the user to see the content of the page. Especially for large single-page applications, the file volume is relatively large after packaging, and it takes a long time for ordinary clients to render and load all required files. The home page will have a long white screen waiting time.

Disadvantages:

  1. Project complexity: Due to the need to do node intermediate processing, more file processing sub-services, and browsing side files are required

  2. Learning costs are relatively high

    In addition to being familiar with Webpack and Vue, you also need to master node, Koa2 and other related technologies. Compared to client rendering, the project construction and deployment process is more complex.

  3. The server is under heavy pressure

    Rendering was done by the client, but now it is done by the server node service. Especially in the case of high concurrent access, it consumes a lot of SERVER CPU resources.

  4. Limited development conditions

    In server-side rendering, only lifecycle hooks are executed before componentDidMount, so no other lifecycle hooks are available to third-party libraries referenced by the project, limiting the selection of reference libraries.

  • Application Scenarios:
    1. Single-page application scenario: Background management pages that do not have high SEO requirements
    2. SSR applicable scenarios: the official website and advertising pages, and other pages that need to see the effect very quickly