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
    • Invite by email
      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 Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
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
  • Invite by email
    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: vue3 --- # Vue3 - Composition API - Setup ## 📕 Argument setup function은 두 가지 argument를 받는다. 1. props 2. context ### 📍 Props `setup` 함수의 첫 번째 인자는 props이다. **props는 반응형이다.** 즉, 새로운 props가 들어오면, props는 반응하고, 업데이트된다. `props`가 reactive하기 때문에, ES6의 destructing을 사용하면 안된다. destructing을 사용하면 props reactivity가 없어지기 때문이다. **props를 비구조화해야하는 경우가 생기면 `toRefs` 라는 함수를 이용해야 한다. 이 경우엔, 각각의 프로퍼티가 원래 객체의 프로퍼티의 ref이기 때문에 반응형이 유지된다.** > ### toRefs > 반응형 객체를 각 프로퍼티가 ref인 plain object로 변경시켜준다. ```javascript // MyBook.vue import { toRefs } from 'vue' setup(props) { const { title } = toRefs(props) console.log(title.value) } ``` > ### toRef > 반응형 객체의 프로퍼티에 ref를 만들어낸다. toRef는 source property가 존재하지 않더라도, 사용가능한 ref를 반환한다. 따라서 optional props를 가져와야 할 때 유용하다. toRefs는 원본 객체에 존재하는 프로퍼티들에만 ref를 만들어내기 때문이다. 만약 title이 **optional prop**이라면, props에 title이 없을 수 있다. 이러한 경우에 toRefs는 title의 ref를 만들지 못한다. 대신, **`toRef`를 써야 한다.** (복수나 단수냐의 차이로 이러는거 너무 헷갈리게 만든거 아닌가...) ```javascript // MyBook.vue import { toRef } from 'vue' setup(props) { const title = toRef(props, 'title') console.log(title.value) } ``` ### 📍 Context setup 함수의 두 번째 인자는 `context`이다. context는 세 가지 프로퍼티가 있는 자바스크립트 객체이다. 1. attrs 2. slots 3. emit context 객체는 일반적인 자바스크립트 객체로, **Reactive하지 않다.** => 따라서 destructing으로 값을 가져와도 된다. ```javascript // MyBook.vue export default { setup(props, { attrs, slots, emit }) { ... } } ``` **`slots`와 `attrs`는 stateful object로, 컴포넌트가 업데이트되면, 항상 업데이트**된다. 이 말은 곧 slots와 attrs에는 destructing을 사용하면 안되며 **항상, `attrs.x`, `slots.x`처럼 프로퍼티를 가리켜야 한다**. props와는 다르게, **slots와 attrs는 Reactive하지 않다**. 따라서, **attrs와 slots의 변화에 따른 사이드이펙트를 주고 싶으면, `onUpdated` 라이프사이클 훅 안에서 사이드 이펙트를 줘야 한다.** ## 📕 Component Property에 접근하기 **`setup`이 실행될 때, 컴포넌트 인스턴스는 아직 생성되기 전이다.** 따라서 다음과 같은 프로퍼티에만 접근할 수 있다. - props - attrs - slots - emit 즉, data, computed, methods와 같은 컴포넌트 옵션에는 접근할 수 없다는 의미이다. 참고로 인스턴스가 created되는 시점에는 data observation, computed, methods, watch/event callback이 설정되어있다. ## 📕 템플릿과 같이 사용하기 setup이 객체를 반환하면, 그 객체의 프로퍼티는 템플릿에서 접근할 수 있다. **setup에서 반환하는 refs는 템플릿에서 접근할 때에 automatically shallow unwrapped**되어있다. 따라서, **템플릿에서 `.value`를 사용하지 않는다.** ```javascript <!-- MyBook.vue --> <template> <div>{{ collectionName }}: {{ readersNumber }} {{ book.title }}</div> </template> <script> import { ref, reactive } from 'vue' export default { props: { collectionName: String }, setup(props) { const readersNumber = ref(0) const book = reactive({ title: 'Vue 3 Guide' }) // expose to template return { readersNumber, book } } } </script> ``` ## 📕 Render 함수와 같이 사용하기 setup can also return a render function which can directly make use of the reactive state declared in the same scope setup이 렌더 함수를 반환할 수 있는데, 같은 스코프에 선언된 reactive state를 바로 사용할 수 있다. ```javascript // MyBook.vue import { h, ref, reactive } from 'vue' export default { setup() { const readersNumber = ref(0) const book = reactive({ title: 'Vue 3 Guide' }) // Please note that we need to explicitly expose ref value here return () => h('div', [readersNumber.value, book.title]) } } ``` ## 📕 this 사용하기 **setup 안에서 this는 현재 active instance를 가리키고 있지 않다.** setup()은 컴포넌트 옵션이 resolve되기 전에 호출되기 때문에, this는 다른 옵션에서의 this와는 다르게 동작하게 된다. ## 참고 - [Reactivity API - vue3](https://v3.vuejs.org/api/refs-api.html#torefs)

    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