0
点赞
收藏
分享

微信扫一扫

使用Vue,你需要知道的性能优化

路由懒加载
   const router = new VueRouter({
      routes: [
        { path: '/foo', component: ()=> import ('./foo.vue')}
      ]
    })
Keep-alive缓存页面
 <template>
    <div id="app">
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
  </template>
使用v-show复用DOM
 <template>
    <div id="app">
      <div v-show="value">
        <heavy :n="1000"></heavy>
      </div>
    </div>
  </template>
v-for遍历同时避免使用v-if

对数据过滤,需要显示才显示,而不是每一次循环都去判断

<template>
    <div id="app">
     <ul>
       <li v-for="item in activeUsers" :key="item.id">{{item.name}}</li>
     </ul>
    </div>
  </template>
  
  <script>
    export default {
      computed: {
        activeUsers: function() {
          return this.users.filter(function(user) {
            return user.isActive
          })
        }
      }
    }
  </script>
如果是纯粹的展示数据,这些数据不会有任何改变,就不需要做响应式

可以对获取过来的数据进行冻结

export default {
     data: () => ({
       users: []
     }),
     async created() {
       const users = await axios.get('/api/users');
       this.users = Object.freeze(users);
     }
    }
Vue组件销毁时,会自动解绑它的全部指令及事件监听,但仅限于组件本身的事件
    created() {
       this.timer = setInterval(this.refresh, 2000)
     },
     beforeDestroy() {
       clearInterval(this.timer)
     }
图片懒加载

对于图片较多的页面,为了加载页面速度,所以很多时候我们需要将未出现在视口的图片先不做加载,等滚动到时在加载

<img v-lazy="/static/img/1.png">
第三方插件尽量按需引入

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

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

  Vue.use(Button)
  Vue.use(select)
无状态的展示型组件标记为函数式组件

由于没有组件实例,所以在运行中所消耗的资源较少

  <template functional> 
    <div class="cell">
     <ul>
       <li v-for="item in activeUsers" :key="item.id">{{item.name}}</li>
     </ul>
    </div>
  </template>
举报

相关推荐

0 条评论