Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

了解哪些vue性能优化的方法 #76

Open
GGXXMM opened this issue Dec 29, 2020 · 0 comments
Open

了解哪些vue性能优化的方法 #76

GGXXMM opened this issue Dec 29, 2020 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Dec 29, 2020

1. 路由懒加载

const router = new VueRouter({
    routes: [
       {path: '/foo', component: ()=> import('./Foo.vue)}
    ]
})

2. keep-alive缓存页面

<template>
    <div id="app">
         <keep-alive>
             <component v-bind:is="currentTabComponent"></component>
         </keep-alive>
    </div>
</template>

3. v-show复用DOM(频繁切换v-show较好)

4. v-for遍历避免同时使用v-if(提前过滤需要遍历的数据)

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

5. 长列表性能优化

  • 如果列表是纯粹的数据展示,不会变动,就不需要做响应式
  • 如果是大数据长列表,可采用虚拟滚动,只渲染少部分区域的内容

6. 事件的销毁

Vue组件销毁时,会自动将Vue实例的所有指令、事件监听器解绑,但仅限于组件本身的事件。

created(){
   this.timer = setInterval(this.refresh, 2000)
},
destroyed(){
   clearInterval(this.timer)
}

7. 图片懒加载(图片资源很多)

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

依赖第三方插件:vue-lazyload

8. 第三方插件按需引入

像element-ui这样的第三方组件库可以按需引入避免体积太大。

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);

9. 无状态的组件标记为函数式组件(展示型组件适用)

<template functional>
   <div class="cell">
       <div v-if="props.value" class="on"></div>
       <div v-else class="off"></div>
   </div>
</template>
<script>
export default {
   props: ['value']
}
</script>

参考:https://cn.vuejs.org/v2/guide/render-function.html

10. 子组件合理分割

11. 变量本地化

需要频繁计算的值,先暂存成本地变量,不要频繁引用。

<template>
  <div>{{result}}</div>
</template>

<script>
import {heavy} from '@utils';
export default {
  computed: {
    base() {return 42},
    result() {
      let base = this.base;// 不要频繁引用this.base
      for (let i = 0; i < 1000; i++) { 
        result += heavy(base) 
      }
      return result
    }
  }
}
</script>

12. SSR

ssr是一种优化策略,有利于首屏加载和SEO

@GGXXMM GGXXMM added the vue label Dec 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant