All Articles

[Vue] Vue.js 성능 개선 방법들

함수형 컴포넌트 사용

리액트에서의 function component처럼 상태를 가지지 않고 ⇒ data를 가지지 않고, 라이프 사이클을 가지지 않는 컴포넌트를 만들 수 있다.

component의 functional 속성을 true로 설정하거나,

Vue.component('my-component', {
  functional: true,
  props: {
    // ...
  }
})

템플릿 기반으로 함수형 컴포넌트를 정의할 수 있다.

<template functional>
</template>

함수형 컴포넌트는 단순한 함수이기 때문에, 렌더링 비용이 훨씬 적다고 한다.

v-once로 한 번만 렌더링하기

첫 렌더링 이후 변경되지 않는 요소는 v-once를 사용해 한 번만 렌더링 한 후 상태를 캐싱시켜 성능을 향상시킬 수 있다.

<user-avatar
	v-once
	:user-obj="userObj
>
</user-avatar>

Keep-alive를 사용한 캐싱

keep-alive 를 사용하면 컴포넌트가 destroy되지 않고 상태가 보존된다. ⇒ 컴포넌트 인스턴스가 전역 큐에 저장되어 재활성화 될 때도 다시 렌더링되지 않고 캐싱된 상태를 사용할 수 있다

<keep-alive>
	<component :is="currentView>
	</component>
</keep-alive>

v-if와 v-show 구분하기

v-if는 컴포넌트가 토글되는 상황에서 DOM이 제거되고 다시 만들어진다. 초기 렌더링 시 거짓인 경우 만들어지지 않음

v-show는 초기 조건과 관계 없이 렌더링되고, CSS 속성만 변경된다. 초기 렌더링이 오래걸리더라도 지속적으로 토글되는 경우 v-show를 사용하는 것이 더욱 효율적이다.

캐싱이 필요한 곳에 computed 쓰기

watch와 구분하여 필요한 상황에 맞게 써야한다. watch는 비동기 처리 로직이나 매번 호출해야 하는 상황에 쓰고, 캐싱이 필요한 상황에는 computed를 쓰자

Lazy Loading 사용하기

  • lazy loading?
  • 앱의 초기 구동 시에 모든 컴포넌트의 리소스를 다 다운받을 필요는 없다
  • 리소스를 컴포넌트 단위로 분리시켜 필요한 것들만 다운로드 받을 수 있도록 함
  • 라우터에서의 컴포넌트 import 부분을 함수로 변경해준다
// before
component: MyProfile

// after
component: () => import( "./components/MyProfile.vue" )

before

import Home from './components/Home.vue'
import MyProfile from './components/MyProfile.vue'
import About from './components/About.vue'

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/myProfile",
    name: "myProfile",
    component: MyProfile
  },
  {
    path: "/about",
    name: "about",
    component: About
  }
]

export default routes;

after

  • Home 컴포넌트는 lazy-loading 시키지 않는다 ⇒ 랜딩 페이지이기 때문
import Home from './components/Home.vue'

const routes = [
  {
    path: "/",
    name: "home",
    component: Home
  },
  {
    path: "/myProfile",
    name: "myProfile",
    component: () => import( "./components/MyProfile.vue" )
  },
  {
    path: "/about",
    name: "about",
    component: () => import( "./components/About.vue" )
  }
]

export default routes;

[코드 출처] https://dev.to/reiallenramos/lazy-loading-in-vue-81o

참고) lazy loading in React

리액트에서는 React.lazy를 사용한다

const OtherComponent = React.lazy(() => import('./OtherComponent'));

Router와 함께 이렇게 사용한다

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/about" component={About}/>
      </Switch>
    </Suspense>
  </Router>
);

Suspense 는 컴포넌트가 로드될 때까지 기다리는 동안 보여줄 것을 fallback prop으로 받아서 렌더링한다