Tree
    • 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

      This note has no invitees

    • 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
    • Note Insights
    • 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 Note Insights 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

    This note has no invitees

  • 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
    2
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Vue-Composition-API 的學習 (一) ###### tags: `w3HexSchool` . `js` 為何我們需要 Composition 呢 ? 其實我也不是特別清楚 , 不過接下來有一些旅途可以跟在下一起走 , 讓我們發現一些利用 Composition-API 可能會更棒的例子 1. window.innerHeight / window.innerWidth 不知道各位有沒有為測量螢幕長寬而困擾過呢 ? 以下是在下為了要測量螢幕的長寬 , 結果需要作出一個元件才能完成 ```javascript= // measurer.vue <template> <div class="root"> <slot name="body" :width="width" :height="height" /> </div> </template> <script> export default { name: "measurer", mounted() { window.addEventListener('resize', this.reportWindowSize); }, beforeDestroy(){ window.removeEventListener('resize', this.reportWindowSize); }, methods: { reportWindowSize() { this.height = window.innerHeight; this.width = window.innerWidth; }, }, data() { return { width: window.innerWidth, // document.body.clientWidth, height: window.innerHeight, // document.body.clientHeight, } } } </script> <style scoped> .root { width: 400px; height: 200px; font-weight: 900; font-size: 50px; display: flex; flex-direction: column; background-color: #898585; margin: 20px; padding: 20px; } </style> ``` 外加上在使用測量時 , 都需要用 `slot` 將目標元件包成子元件 , 並有可能受到多一層 div 的 side effect , 讓 css 調整困難 ```htmlmixed= <measurer> <template v-slot:body="{height,width}"> <span>寬度:{{width}}px</span> <span>高度:{{height}}px</span> </template> </measurer> ``` 這時我們可以引入 @vue/composition-api 套件 , 讓我們在 vue 2 的環境中使用 setup 的功能 , 如果觀察 measurer.vue 我們可以整理出一個 useMeasurer.js ```javascript= import {onMounted, onBeforeUnmount, reactive} from '@vue/composition-api' const useMeasurer = () => { const state = reactive({ height: window.innerHeight, width: window.innerWidth, }) const reportWindowSize = () => { state.height = window.innerHeight; state.width = window.innerWidth; } onMounted(() => { window.addEventListener('resize', reportWindowSize); }) // beforeDestroy 需要替換成 onBeforeUnmount onBeforeUnmount(() => { window.removeEventListener('resize', reportWindowSize); }) return state; }; export default useMeasurer ``` 之後如果要使用測量工具 , 直接引入 useMeasurer 並放在 setup 區塊中就可以舒服的測量尺寸了 :smiley: ```javascript= <template> <div> <span>寬度:{{state.width}}px</span> <span>高度:{{state.height}}px</span> </div> </template> <script> import useMeasurer from './useMeasurer.js' export default { name: "CompositeMeasurer", setup() { return {state: useMeasurer()} }, } </script> ``` :::warning 做到這裡本樹產生了一些疑惑 🤔 , 如果有 2 個 useXXX 函數都用到了 onMounted 最後會如何呢 ? - 前一個功能被後一個功能覆蓋掉 ? - 2 個功能都按照預期的執行呢 ? ::: 這時我們來試試看監聽滑鼠移動的事件 ```javascript= import {onMounted, onBeforeUnmount, reactive} from '@vue/composition-api' const useMouseMove = () => { const state = reactive({ x: 0, y: 0, }) const getMousePosition = e => { state.x = e.pageX; state.y = e.pageY; } onMounted(() => { window.addEventListener('mousemove', getMousePosition); }) onBeforeUnmount(() => { window.removeEventListener('mousemove', getMousePosition); }) return state; }; export default useMouseMove ``` ### 成果 <iframe src="https://codesandbox.io/embed/vue-composition-api-1g0uc?fontsize=14&hidenavigation=1&theme=dark" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" title="vue-composition-api" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts" ></iframe> :::info ==結論== 如果有兩個 useXXX 都註冊 onMounted 事件 , 二者不會有衝突 , 都可以正常執行相關的程式 , 以後我們可以將相關的邏輯拉出來放在 useXXX 統一處理 , 不用東一塊 . 西一塊了 ! ::: ## 參考資料 - [【🚨万字警告】了不起的Vue3(下)](https://juejin.cn/post/6898121032171945992) - [VueMastery - Vue 3 Composition API](https://www.vuemastery.com/courses/vue-3-essentials/why-the-composition-api)

    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