Vue.js Lifecycle

|

Vue.js Lifecycle

라이프사이클 순서

Vue의 라이프사이클은 아래와 같은 순서로 이루어집니다.

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeUnmount
  • unmounted

beforeCreate

인스턴스가 생성된 후 가장 처음 실행되는 단계입니다. datamethods 속성이 아직 인스턴스에 정의되지 않았으며, DOM 요소에도 접근할 수 없습니다.

created

datamethods 속성이 정의되었습니다. 하지만 인스턴스가 화면에 마운트되지 않았기 때문에 DOM 요소에는 접근할 수 없습니다.

beforeMount

인스턴스가 DOM에 마운트되기 직전에 호출되는 단계입니다. render() 함수가 호출되기 직전의 로직을 넣기 적합합니다.

mounted

DOM에 인스턴스가 마운트되고나서 호출되는 함수입니다.

App.vue 예제 코드

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
</template>

<script>
export default {
  name: "App",
  components: {},
  beforeCreate() {
    console.log("[snowdeer] beforeCreate()");
  },
  created() {
    console.log("[snowdeer] created()");
  },
  beforeMount() {
    console.log("[snowdeer] beforeMount()");
  },
  mounted() {
    console.log("[snowdeer] mounted()");
  },
  beforeUpdate() {
    console.log("[snowdeer] beforeUpdate()");
  },
  updated() {
    console.log("[snowdeer] updated()");
  },
  beforeUnmount() {
    console.log("[snowdeer] beforeUnmount()");
  },
  unmounted() {
    console.log("[snowdeer] unmounted()");
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

예제 코드를 실행하면 모든 로그가 출력되는 것이 아니라 beforeCreate, created, beforeMount, mounted 까지만 출력됩니다. 그 이유는 updated는 데이터 변경이 발생했을 때 화면 갱신을 위해 호출되는 로직이기 때문입니다.

따라서 아래와 같이 코드를 조금 수정해서 데이터를 변경하면 updated 까지 로그가 출력되는 것을 확인할 수 있습니다.

수정된 App.vue 예제 코드

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <h1></h1>
</template>

<script>
export default {
  name: "App",
  components: {},
  data() {
    return {
      message: `hello, snowdeer`,
    };
  },
  beforeCreate() {
    console.log("[snowdeer] beforeCreate()");
  },
  created() {
    console.log("[snowdeer] created()");
  },
  beforeMount() {
    console.log("[snowdeer] beforeMount()");
  },
  mounted() {
    console.log("[snowdeer] mounted()");
    this.message = `hello, snowdeer +_+`;
  },
  beforeUpdate() {
    console.log("[snowdeer] beforeUpdate()");
  },
  updated() {
    console.log("[snowdeer] updated()");
  },
  beforeUnmount() {
    console.log("[snowdeer] beforeUnmount()");
  },
  unmounted() {
    console.log("[snowdeer] unmounted()");
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Vue.js 설치 방법(MacOS)

|

Vue.js 설치 방법

Node.js 설치

$ brew install node

$ node -v
v17.7.1

$ npm -v
8.5.2

Yarn 설치

위에서 Node.js를 이미 설치했기 때문에 --ignore-dependencies 옵션을 주고 설치합니다.

$ brew install yarn --ignore-dependencies

$ yarn -v
1.22.17

Vue-Cli 설치

npm install @vue/cli -g

또는 

yarn global add @vue/cli

샘플 프로젝트 생성해보기

$ vue create snow-vue-sample

?  Your connection to the default yarn registry seems to be slow.
   Use https://registry.npmmirror.com for faster installation? Yes


Vue CLI v5.0.3
? Please pick a preset: Default ([Vue 3] babel, eslint)
? Pick the package manager to use when installing dependencies: Yarn


Vue CLI v5.0.3
✨  Creating project in /Users/snowdeer/Workspace/snow-vue-sample.
🗃  Initializing git repository...
⚙️  Installing CLI plugins. This might take a while...

yarn install v1.22.17
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...

success Saved lockfile.
✨  Done in 45.85s.
🚀  Invoking generators...
📦  Installing additional dependencies...

yarn install v1.22.17
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
✨  Done in 9.32s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project snow-vue-sample.
👉  Get started with the following commands:

 $ cd snow-vue-sample
 $ yarn serve

Chrome의 Vue.js devtools 설치

Chrome 웹스토어에서 Vue.js devtools 플러그인을 설치합니다.

Visual Studio 터미널 폰트 설정

|

터미널 폰트 설정

vscode에서 터미널 폰트가 깨져서 나오는 경우가 있습니다. 저 같은 경우는 zsh을 쓰다보니 특정 글자에서 다음과 같이 폰트가 깨져서 출력이 되네요.

image

설정 방법은 Preferences > Settings 메뉴로 진입합니다. 그리고 다음 화면과 같이 터미널의 Font Family 항목을 검색합니다.

image

여기서 맨 위의 칸에 다음 그림과 같이 D2Coding을 입력합니다. 물론 PC에 D2Coding 폰트가 설치되어 있어야 합니다.

image

이제 터미널 폰트가 정상적으로 출력되는지 확인합니다.

image

Docker 실전 예제(Nginx 컨테이너 실행)

|

Docker를 이용해서 Nginx 컨테이너 실행하는 예제

Nginx 이미지 다운로드

$ docker pull nginx:latest
latest: Pulling from library/nginx
8998bd30e6a1: Downloading [=====================>                             ]  13.03MB/30.06MB
6fba654dd4ee: Downloading [======================>
8998bd30e6a1: Pull complete
6fba654dd4ee: Pull complete
661b4150d3a3: Pull complete
13b3c8cc8cde: Pull complete
573040833908: Pull complete
5de8f8b958d2: Pull complete
Digest: sha256:2834dc507516af02784808c5f48b7cbe38b8ed5d0f4837f16e78d00deb7e7767
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

다운로드된 이미지 확인

$ docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
nginx        latest    2e7e2ec411a6   3 weeks ago   134MB

Nginx 컨테이너 실행

PC의 포트는 5050, 컨테이너 내부의 포트는 80 입니다.

$ docker run --name sample_webserver_1 -d -p 5050:80 nginx:latest
8b0debd502109efc121d28c3de74c1b804580807d9df1e6339afb8b2bfbaf493

컨테이너 실행 확인

$ docker ps -a
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                  NAMES
8b0debd50210   nginx:latest   "/docker-entrypoint.…"   56 seconds ago   Up 56 seconds   0.0.0.0:5050->80/tcp   sample_webserver_1

호스트의 포트 확인

로컬 웹브라우저에서 http://localhost:5050 주소로 접속해서 페이지가 잘 열리는 지 확인합니다. 또는 터미널에서 curl localhost:5050 명령어로 확인할 수 있습니다.

컨테이너에서 실행 중인 프로세스 출력

$ docker top sample_webserver_1
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                2021                1996                0                   11:59               ?                   00:00:00            nginx: master process nginx -g daemon off;
uuidd               2077                2021                0                   11:59               ?                   00:00:00            nginx: worker process
uuidd               2078                2021                0                   11:59               ?                   00:00:00            nginx: worker process
uuidd               2079                2021                0                   11:59               ?                   00:00:00            nginx: worker process
uuidd               2080                2021                0                   11:59               ?                   00:00:00            nginx: worker process

컨테이너 정지

$ docker stop sample_webserver_1
sample_webserver_1

pip3 freeze 명령어(requirements.txt)

|

pip3 freeze 명령어

pip3 freeze 명령어를 이용하면 다음과 같이 현재 사용하고 있는 파이썬 패키지 리스트를 확인할 수 있습니다.

$ pip3 freeze

Deprecated==1.2.13
packaging==21.3
pyparsing==3.0.7
redis==4.1.2
wrapt==1.13.3

패키지 리스트 내보내기

다음 명령어를 이용해서 현재 사용중인 패키지 리스트를 requirements.txt에 저장할 수 있습니다.

pip3 freeze > requirements.txt

패키지 리스트 가져와서 설치하기

pip3 install -r requirements.txt