• 为什么在Vue中使用函数式组件能提高性能?
  • 发布于 2个月前
  • 151 热度
    0 评论

前言

对于某些组件,如果我们只是用来显示一些数据,不需要管理状态,监听数据等,那么就可以用函数式组件。函数式组件是无状态的,无实例的,在初始化时不需要初始化状态,不需要创建实例,也不需要去处理生命周期等,相比有状态组件,会更加轻量,同时性能也更好。


我们可以写一个简单的 demo 来验证下这个优化:
// UserProfile.vue
<template>
  <div class="user-profile">{{ name }}</div>
</template>
// 堆代码 duidaima.com
<script>
  export default {
    props: ['name'],
    data() {
      return {}
    },
    methods: {}
  }
</script>
<style scoped></style>

// App.vue
<template>
  <div id="app">
    <UserProfile v-for="item in list" :key="item" : />
  </div>
</template>

<script>
  import UserProfile from './components/UserProfile'

  export default {
    name: 'App',
    components: { UserProfile },
    data() {
      return {
        list: Array(500)
          .fill(null)
          .map((_, idx) => 'Test' + idx)
      }
    },
    beforeMount() {
      this.start = Date.now()
    },
    mounted() {
      console.log('用时:', Date.now() - this.start)
    }
  }
</script>

<style></style>
UserProfile 这个组件只渲染了 props 的 name,然后在 App.vue 中调用 500 次,统计从 beforeMount 到 mounted 的耗时,即为 500 个子组件(UserProfile)初始化的耗时。

经过我多次尝试后,发现耗时一直在 30ms 左右,那么现在我们再把改成 UserProfile 改成函数式组件:
<template functional>
  <div class="user-profile">{{ props.name }}</div>
</template>
此时再经过多次尝试后,初始化的耗时一直在 10-15ms,这些足以说明函数式组件比有状态组件有着更好的性能!
用户评论