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 - Provide / Inject ### [예시 - 코드샌드박스 by yejineee](https://codesandbox.io/s/composition-api-provide-inject-ef4ms?file=/src/components/MyMarker.vue) # 🍒 Provide / inject ![](https://i.imgur.com/FfzdZdk.png) ## provide/inject의 필요성 기존에는 부모에서 자식 컴포넌트로 데이타를 전달해야할 경우엔 `props`를 사용하였다. 만약, 컴포넌트 구조가 복잡하게 중첩되어있을 경우엔, drilling으로 데이타를 전달해야 하며, 이 작업은 매우 짜증난다... 이러한 문제를 해결하기 위해 `provide`, `inject`를 사용한다. 부모 컴포넌트가 provider가 되어 그 하위의 모든 자식들에게 데이타를 전달하게 된다. 부모는 `provide` option으로 데이타를 전달하게 되고, 자식 컴포넌트는 `inject` option으로 데이타를 사용하게 된다. (리액트의 Context API가 이러한 역할을 한다. Context.Provider / Context.Consumer가 provide/inject에 대응한다.) ## 예시 부모 컴포넌트 쪽에서 provide로 데이터를 넘긴다. 이 때, **provide는 객체를 넘기는 함수인데, 이렇게 해야 component instance property를 자식 컴포넌트에게 넘길 수 있다.** ```javascript app.component('todo-list', { data() { return { todos: ['Feed a cat', 'Buy tickets'] } }, provide() { return { todoLength: this.todos.length } }, template: ` ... ` }) ``` ```javascript app.component('todo-list-statistics', { inject: ['todoLength'], created() { console.log(`Injected property: ${this.todoLength}`) // > Injected property: John Doe } }) ``` 만약, component instance property가 아닌 값을 넘겨줄 때는 provide는 다음과 같은 형태여도 된다. ```javascript provide: { location: "North Pole", geolocation: { longitude: 90, latitude: 135, }, }, ``` ## provide/inject에 반응형 추가하기 **기본적으로 provide/inject는 reactive하지 않다**. 따라서, todos 배열의 길이가 달라져도, 주입된 todoLength property에는 반영되지 않는다. 반응형을 추가하고 싶으면 - **ref** property 전달 or - **reactive** object 전달 을 해야 한다. 여기서는 Composition API의 `computed` 프로퍼티를 todoLength에 추가하였다. injected property를 가져올 때는 this.todoLength.value로 가져온 것을 알 수 있다. ```javascript app.component('todo-list', { // ... provide() { return { todoLength: Vue.computed(() => this.todos.length) } } }) app.component('todo-list-statistics', { inject: ['todoLength'], created() { console.log(`Injected property: ${this.todoLength.value}`) // > Injected property: 5 } }) ``` # 🍒 Composition API - provide/inject Composition API에서 provide, inject를 사용할 수 있다. ## Provide 사용하기 setup()안에서 provide를 사용하기 위해서는 vue에서 provide를 import해야 한다. provide 함수로는 두 값을 전해주어야 한다. - name (String type) - value ```javascript <!-- src/components/MyMap.vue --> <template> <MyMarker /> </template> <script> import { provide } from 'vue' import MyMarker from './MyMarker.vue' export default { components: { MyMarker }, setup() { provide('location', 'North Pole') provide('geolocation', { longitude: 90, latitude: 135 }) } } </script> ``` ## Inject 사용하기 setup()안에서 inject 사용하려면 vue에서 import 해와야 한다. inject함수는 두 파라미터를 받는다. - inject할 프로퍼티 이름 - default value(optional) ```javascript <!-- src/components/MyMarker.vue --> <script> import { inject } from 'vue' export default { setup() { const userLocation = inject('location', 'The Universe') const userGeolocation = inject('geolocation') return { userLocation, userGeolocation } } } </script> ``` ## 반응형 추가하기 **반응형을 추가하기 위해선 `ref`나 `reactive`** 를 provide할 value에 추가해야 한다. ```javascript <!-- src/components/MyMap.vue --> <template> <MyMarker /> </template> <script> import { provide, reactive, ref } from 'vue' import MyMarker from './MyMarker.vue' export default { components: { MyMarker }, setup() { const location = ref('North Pole') const geolocation = reactive({ longitude: 90, latitude: 135 }) provide('location', location) provide('geolocation', geolocation) } } </script> ``` ## 반응형 프로퍼티 변경하기 - provider안에서 값 변경하기 : 가능한한 그렇게 할 것 ! **reactive property를 변경하는 것은 provider 안에서 하는 것을 추천한다.** ```javascript <template> <MyMarker /> </template> <script> import { provide, reactive, ref } from 'vue' import MyMarker from './MyMarker.vue' export default { components: { MyMarker }, setup() { const location = ref('North Pole') const geolocation = reactive({ longitude: 90, latitude: 135 }) provide('location', location) provide('geolocation', geolocation) return { location } }, methods: { updateLocation() { // provider안에서 location property 변경하는 메소드 추가 this.location = 'South Pole' } } } </script> ``` - inject한 컴포넌트에서 값 변경하기 만약, 데이타를 inject받은 컴포넌트에서 데이타를 변경해야 할 경우도 있을 것이다. 이럴 때는, **reactive property를 변경할 메소드를 provider쪽에서 전달할 것을 추천**한다. ```javascript <!-- src/components/MyMap.vue --> <template> <MyMarker /> </template> <script> import { provide, reactive, ref } from 'vue' import MyMarker from './MyMarker.vue' export default { components: { MyMarker }, setup() { const location = ref('North Pole') const geolocation = reactive({ longitude: 90, latitude: 135 }) const updateLocation = () => { location.value = 'South Pole' } provide('location', location) provide('geolocation', geolocation) provide('updateLocation', updateLocation) } } </script> ``` - **`readonly` 사용하여 상수화하기** **값이 변경되어서는 안될 프로퍼티에는 `readonly`를 provider 쪽에서 추가**하여, injected component 쪽에서 값을 변경시키지 못하도록 할 것을 추천한다. ```javascript <script> import { provide, reactive, readonly, ref } from 'vue' import MyMarker from './MyMarker.vue' export default { components: { MyMarker }, setup() { const location = ref('North Pole') const geolocation = reactive({ longitude: 90, latitude: 135 }) const updateLocation = () => { location.value = 'South Pole' } provide('location', readonly(location)) provide('geolocation', readonly(geolocation)) provide('updateLocation', updateLocation) } } </script> ```

    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