yejineee
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- tags: vue --- # Vue2 Lifecycle & Lifecycle Method ## 라이프사이클 다이어그램 ![](https://i.imgur.com/klukddB.png) ## 순서 1. **new Vue()** 2. **Init Events & Lifecycle** 3. **Init injections & reactivity** 4. **Has "el" option** 5. **Has "template" option** * YES : **Compile template into render function** * NO : **Compile el's outerHTML as template** 6. **Create vm.$el and replace "el" with it** 7. **Mounted** 8. **When data changes** -> **Virtual DOM re-render and patch** 9. **When vm.$destroy() is called** 10. **Teardown watchers, child components and event listeners** 11. **Destroyed** ## ✅ 예제 확인하기 -> [JSFiddle](https://jsfiddle.net/yejin_yang/ve935huz/35/) ## 인스턴스와 라이프사이클 훅 라이프사이클 훅을 통해, 컴포넌트가 언제 생성되어, DOM에 추가되고, update되고, destoy 되는지를 알 수 있다. Vue 인스턴스가 생성될 때, 일련의 초기화 과정을 거치게 된다. - 초기화 과정 1. 데이터 관찰 설정 2. 템플릿 컴파일 3. DOM에 인스턴스를 마운트 4. 데이터가 변경되었을 때 DOM을 업데이트 그러한 경우에, **라이프 사이클 훅(lifecycle hook)** 이라는 함수를 호출하게 된다. 이는 유저에게 사용자 정의 로직을 특정 stage에 실행시킬 수 있게 한다. 라이프 사이클 훅의 예로 `created`, `mounted`, `updated`, `destroyed`가 있다. **모든 라이프사이클 훅은 해당 함수를 호출한 뷰 인스턴스를 가리키는 `this` context와 함께 호출된다.** <u>따라서 화살표함수를 콜백이나 options 프로퍼티에 사용하면 안된다.</u> options 객체는 인스턴스를 만들 때 넘기는 객체이다. ```javascript new Vue({ data: { a: 1, }, created: function () { // this는 vm 인스턴스를 가리킨다. // 화살표함수는 this에 vm을 가리키지 않으므로, 사용해서는 안된다...! console.log(`a : ${this.a}`); }, }); ``` ## Lifecycle Method ### Creation (Initialization) creation hook은 컴포넌트가 DOM에 추가되기 전에 무언가 액션을 할 수 있게 한다. client rendering이나 server rendering을 하는 동안에 무엇가를 세팅하는 작업을 할 수 있다. 다른 훅들과는 다르게 서버사이드 렌더링에도 이 훅은 호출된다. ```javascript new Vue({ el: "#app", data: { count: 10 }, beforeCreate: function () { console.log('Nothing gets called at this moment') // `this` points to the view model instance console.log('count is ' + this.count); // undefined }, created: function () { // `this` points to the view model instance console.log('count is: ' + this.count) // 10 } }) ``` #### beforeCreate 인스턴스가 초기화된 직후에 동기적으로 호출된다. 이 시점에는 Data observation과 event/watcher가 설정되기 전이다. #### created 이 훅은 인스턴스가 create된 직후에 동기적으로 호출된다. 이 훅이 호출된 시점에는 **이벤트와 data observation에 대한 설정이 끝난 후**이다. 즉, - data observation - computed properties - methods - watch/event callback 이 설정된 후다. 그러나 마운트 단계 전이기 때문에, `$el`프로퍼티는 아직 사용가능하지 않다. ### Mounting (DOM Insertion) #### beforeMount 마운트 전에 호출된다. 처음으로 render함수가 호출된 후이다. 서버사이드 렌더링시에는 호출되지 않는다. #### mounted instance가 마운트된 이후에 호출된다. 여기서의 마운트란 el가 새로 생성된 vm.$el로 대체되는 것을 말한다. 이 시점에서 Reactive component, template, rendered DOM에 완전히 접근할 수 있다. ```htmlembedded <div id="app"> <div> this is textContent </div> </div> ``` ```javascript new Vue({ el: "#app", mounted(){ console.log('---Mount---'); console.log(this.$el.textContent); // this is textContent } }) ``` 주의할 점은 mounted가 모든 자식 컴포넌트들 또한 마운트되었음을 보장하지는 않는다는 것이다. 전체적인 뷰가 렌더링되기를 기다린다면, `vm.$nextTick`를 사용하면 된다. ```javascript= mounted: function () { this.$nextTick(function () { // Code that will run only after the // entire view has been rendered }) } ``` 서버사이드 렌더링시에는 호출되지 않는다. ### Updating (Diff & Rerender) 리렌더링될 때나, 반응형 프로퍼티가 변경될 때 호출된다. ```htmlembedded <div id="app"> <p ref="dom"> {{this.counter}} </p> </div> ``` ```javascript new Vue({ el: "#app", data() { return { count: 10, counter: 0, } }, created: function () { setInterval(() => { this.counter++ }, 1000) }, beforeUpdate(){ console.log(+this.$refs['dom'].textContent === this.counter); // false }, updated(){ console.log(+this.$refs['dom'].textContent === this.counter); // true } }) ``` #### beforeUpdate 데이터가 변경된 후이고, DOM에 적용되어 리렌더링되기 직전에 호출된다. 서버사이드 렌더링에서는 호출되지 않는다. #### updated 데이터가 변경이 VDOM이 리렌더링되고 patch되게한 이후에 호출된다. 이 훅안에서 state를 변경하는 것은 하지 않아야 한다. state 변경에 반응하기 위해서, computed나 watcher를 사용하는 것이 더 좋다. updated 훅이 모든 자식 컴포넌트 또한 리렌더링된 것을 보장하지 앟ㄴ는다. 전체 뷰가 리렌더링될 때까지 기다리고 싶을 경우, `vm.$nextTick`을 사용해야 한다. 서버사이드 렌더링에서는 호출되지 않는다. ### Destruction (Teardown) component가 없어질 때, 사용할 수 있는 훅이다. cleanup이나, 분석할 때 사용할 수 있다. #### beforeDestroy vue instance가 없어지기 바로 전에 호출된다. 이벤트를 없애거나, 반응형 구독을 없애고 싶을 때 beforeDestory에서 하면 된다. 이 시점에 컴포넌트는 functional하다. #### destroy vue instance가 없어진 후에 호출된다. 이 훅이 호출된 시점에, 모든 directive는 바인드가 없어졌으며, 모든 이벤트 리스너가 제거된 상태이다. 또한, 모든 자식 인스턴스들도 없어진 상태이다. ### keep-alive 컴포넌트에서 쓰이는 Hook #### activated keep-alive component가 activate되었을 때, 호출된다. 서버사이드 렌더링시에는 호출되지 않는다. #### deactivated keep-alive component가 deactivate 되었을 때, 호출된다. 서버사이드 렌더링 시에는 호출되지 않는다. ## 출처 - [vue2 lifecycle](https://vuejs.org/v2/api/#Options-Lifecycle-Hooks)

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully