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 - Introduction > 컴포넌트의 장점 - 컴포넌트가 반복할 수 있는 UI와 그 기능을 하나의 코드로 합칠 수 있게 해준다. - 컴포넌트로 인하여 유지보수나, 유연함 측면에서 많은 도움이 된다. > 컴포넌트의 한계 - 애플리케이션이 점점 커짐에 따라 코드를 공유하고 재사용하는 것이 더 중요해진다. 컴포넌트가 점점 커짐에 따라 data, computed, methods, watch와 같은 옵션들에 점점 더 많은 로직이 들어가게 된다. 이는 이 컴포넌트 코드를 읽고 이해하는것을 어렵게 만든다. > composition api의 필요성 - 아래 사진에서 같은 색으로 칠해진 것이 같은 logic을 처리하는 것들이다. 같은 로직을 처리하는 것들이 fragmentation으로 흩어져있다면, 이해하기도 어렵고 유지보수도 어려워진다. - 같은 로직을 처리하는 것끼리 묶는 것이 훨씬 더 나이스해질 것이다. 이것을 해주는 것이 Composition API이다. ![](https://i.imgur.com/TRTikEW.png) ## `setup` component Option > The new setup component option is executed before the component is created, once the props are resolved, and serves as the entry point for composition API's. 새로운 **setup 컴포넌트 옵션은 컴포넌트가 생성(create)되기 전에** 실행된다. setup이 실행될 당시에 컴포넌트 인스턴스가 생성되지 않았으므로, **setup 옵션 안에는 `this`가 없다.** 즉, setup에서 **props를 제외하고는, 컴포넌트에 있는 어떠한 프로퍼티에도 접근할 수 없다**. setup은 **`props`와 `context`를 받는 함수**이다. 또한, setup에서 반환하는 것은 컴포넌트의 나머지(computed, method, lifecycle hook,...등등)부분과 템플릿에서 접근할 수 있다. ```javascript export default { name: 'HelloWorld', props: { }, setup(props){ console.log(props); } }; ``` props를 찍어보면 Proxy라고 뜬다. Proxy... ![](https://i.imgur.com/I7d4Sbq.png) - 첫 번째 logical concern 분리하기 이 로직과 관련있는 부분은 1. repo의 list 2. repo list 업데이트하는 함수 3. list와 함수를 반환하여, 다른 컴포넌트 옵션에서 사용할 수 있도록 하기 ```javascript import { fetchUserRepositories } from '@/api/repositories'; export default { name: 'HelloWorld', setup(props){ let repo = []; const getUserRepo = async() => { repo = await fetchUserRepositories(props.user); }; return{ repo, getUserRepo }; } }; ``` 지금 이 시점에서 repo 변수는 반응형이 아니다. 따라서, 유저가 봤을 때는, repo는 여전히 비어있다. ## `ref` 로 반응형 변수 만들기 > **TL;DR** > > `ref` 함수 > - 어떠한 변수를 반응형으로 만들기 위함 > - value 라는 프로퍼티가 있는 객체를 반환 **Vue3에서는 어떠한 변수도 `ref` 함수를 통해 반응형으로 만들 수 있다.** ref는 argument를 받아서, **`value` 프로퍼티가 있는 객체를 반환**한다. 이 객체는 값에 접근하거나, 반응형 변수의 값을 변화시키는데 사용한다. ```javascript import { ref } from 'vue' const counter = ref(0) console.log(counter) // { value: 0 } console.log(counter.value) // 0 counter.value++ console.log(counter.value) // 1 ``` - 왜 value라는 프로퍼티가 있는 객체로 만들까? - 값을 객체로 한번 감싸서 반환하는 이유는 **자바스크립트의 다른 데이타 타입 사이에서 통일성을 주기 위함**이다. - 자바스크립트에서 primitive type은 pass by reference가 아닌, pass by value 이다. ref의 argument가 primitive type이던 reference type이던 모두 object로 감싸서 pass by reference가 되게할 수 있다. 어떠한 값을 감싸는 wrapper 객체가 있음으로인해, 앱 전체를 걸쳐서 반응형이 사라질 것이라는 걱정없이, 그 객체를 전달할 수 있게 된다. 즉, `ref`는 값에 **반응형 참조(Reactive Reference)** 를 만든다. Reference와 같이 동작한다는 개념은 composition API 전체에 걸쳐 자주 사용된다. 이제 위의 repo 변수를 반응형으로 만들어보자. ```javascript import {ref} from 'vue'; setup(props){ let repo = ref([]); const getUserRepo = async() => { repo.value = await fetchUserRepositories(props.user); }; return{ repo, getUserRepo }; } ``` 이제 getUserRepo 함수를 호출할 때, repo 변수는 변경되고, 뷰 또한 그 변경에 맞추어 변화될 것이다. ## setup 안에서 Lifecycle Hook 등록하기 **composition API안에서 lifecycle hook을 사용하는 것은 options API 이름 앞에 `on`을 붙이는 것**이다. e.g. `onMounted` 이 함수들은 콜백 함수를 받아서, 컴포넌트가 해당 훅을 실행할 때 그 콜백함수를 실행시킨다. ```javascript import { fetchUserRepositories } from '@/api/repositories'; import {ref, onMounted} from 'vue'; export default { name: 'HelloWorld', props: { user:{ type: String, required: true } }, setup(props){ let repo = ref([]); const getUserRepo = async() => { repo = await fetchUserRepositories(props.user); }; onMounted(getUserRepo); return{ repo, getUserRepo }; } }; ``` ## watch로 변화에 반응하기 > **TL;DR** > > vue에서 import 해온 watch는 Reactive Reference(변화를 감지하고자 하는 대상), 콜백, optional 설정 객체를 받는 함수이다. 이제 user prop의 변화에 맞춰서 반응해야 한다. 이를 위해서 watch 함수를 작성할 것이다. 기존에는 컴포넌트의 watch option을 사용해서, user가 변경될 때마다 user repo를 fetch해오는 함수를 호출하였다. ```javascript watch: { user: 'getUserRepositories' // 1 }, ``` 이와 같은 역할을 vue에서 import해온 `watch`로 할 수 있다. - watch는 세 가지 인자를 받는다. 1. Reactive Reference or getter function that we want to watch 2. callback 3. optional configuration options 간단한 예시는 다음과 같다. 콜백의 인자는 newValue, oldValue이다. ```javascript import { ref, watch } from 'vue' const counter = ref(0) watch(counter, (newValue, oldValue) => { console.log('The new counter value is: ' + counter.value) }) ``` 이제 지금까지 해왔던 예제를 수정해야 한다. props.user가 변경됨에 따라 getUserRepo 함수를 호출해야 한다. 여기서 **`toRefs`** 가 사용된다. 이건 **watcher가 `user` prop의 변화에 반응하게 하기 위해 사용**된다. fetchUserRepositories에 user.value를 넘겨준다. 이렇게 하여 Reference 값을 참조할 수 있게 된다. user를 첫 번째 인자로, 실행시킬 콜백으로 getUserRepo를 두 번째 인자로 watch에 등록한다. ```javascript import { fetchUserRepositories } from '@/api/repositories'; import {ref, onMounted, watch, toRefs} from 'vue'; export default { name: 'HelloWorld', props: { user:{ type: String, required: true } }, setup(props){ const {user} = toRefs(props); let repo = ref([]); const getUserRepo = async() => { repo.value = await fetchUserRepositories(user.value); }; onMounted(getUserRepo); watch(user, getUserRepo); return{ repo, getUserRepo }; } }; ``` ## computed Properties > **TL;DR** > - computed 함수는 Read-only 반응형 참조를 반환한다. > - 반응형 값에 접근하려면 .value로 접근해야 한다. computed 또한 vue에서 import 해와서, vue component 외부에 만들 수 있다. ```javascript import { ref, watch, computed } from "vue"; const counter = ref(0); const twiceTheCounter = computed(() => counter.value * 2); counter.value++; console.log(twiceTheCounter.value); //2 ``` `computed` 함수는 read-only Reactive Reference를 반환한다. 여기서 value에 접근하려면, .value로 접근해야 한다. 이제 두 번째 logical concern을 추가해보자. ```javascript import { fetchUserRepositories } from '@/api/repositories'; import {ref, onMounted, watch, toRefs, computed} from 'vue'; export default { name: 'HelloWorld', props: { user:{ type: String, required: true } }, setup(props){ const {user} = toRefs(props); let repo = ref([]); const getUserRepo = async() => { repo.value = await fetchUserRepositories(user.value); }; onMounted(getUserRepo); watch(user, getUserRepo); const searchQuery = ref(''); const repositoriesMatchingSearchQuery = computed(() => { return repo.value.filter( r => r.name.includes(searchQuery.value)); }); return{ repo, getUserRepo, searchQuery, repositoriesMatchingSearchQuery }; } }; ``` 이렇게 함으로써 두 logical concern이 하나의 setup에 모이게 되었다. 관심사 분리가 이루어지지 않은 것이다. 두 관심사를 `useUserRepositories`와 `useRepositoryNameSearch`로 나누자. ```javascript // src/composables/useUserRepositories.js import { fetchUserRepositories } from '@/api/repositories'; import { ref, onMounted, watch } from 'vue'; export default function useUserRepositories(user) { let repo = ref([]); const getUserRepo = async () => { repo.value = await fetchUserRepositories(user.value); }; onMounted(getUserRepo); watch(user, getUserRepo); return { repo, getUserRepo }; } ``` 🛑 여기서 optional chaining을 계속 쓰게 되는 이유는 인자로 받게 되는 repo가 mount된 이후에 비동기적으로 받아오는 값이기 때문인 것 같다. 비동기 값을 어떻게 기다려서 받아야하는지 모르겠다. 이런식으로 optional chaining을 써야하는걸까? ```javascript //src/composables/useRepositoryNameSearch.js import { ref, computed } from 'vue'; export default function useRepositoryNameSearch(repo) { const searchQuery = ref(''); const searchedRepo = computed(() => { return repo?.value?.name?.includes(searchQuery.value) ? repo.value.name : ''; }); return { searchQuery, searchedRepo }; } ``` 분리된 두 파일을 불러와서 사용하면 된다 ```javascript import useRepositoryNameSearch from '@/composables/useRepositoryNameSearch'; import useUserRepositories from '@/composables/useUserRepositories'; import {toRefs} from 'vue'; export default { name: 'HelloWorld', props: { user:{ type: String, required: true } }, setup(props){ const {user} = toRefs(props); const {repo, getUserRepo} = useUserRepositories(user); const { searchQuery, searchedRepo } = useRepositoryNameSearch(repo); return{ repo, searchedRepo, getUserRepo, searchQuery }; }, }; ```

    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