iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0
JavaScript

歡迎參加我的原生JS畢業典禮系列 第 10

【Day9】組件化概念—Vue Components註冊與使用

  • 分享至 

  • xImage
  •  

昨天提到了ES6的模組化概念、也稍微提到了Module與Components間的相似卻有著些許差異之處,趁著記憶猶新,再繼續看Vue Components!

Components在網頁上扮演什麼角色?

昨天我們用教室布置來比喻元件化的概念,是透過UI的角度切割組件:原本是一個動物園,個別切割成老虎、斑馬和草地(當然!要分割多細都是由我們來定義),但這樣的解釋套用到網頁上要怎麼來看?
https://ithelp.ithome.com.tw/upload/images/20240924/20169356kkbgcACON2.png
在先前的練習中,我們了解到Vue的網頁架構是由放置html的<template><script><style>標籤組成,元件化的概念就是在頁面上的區塊再各自獨立出來,有自己的<template><script><style>,至於要怎麼切?就要靠我們來定義了。

如何撰寫Components?

在開始使用組件前,我們必須先向應用程式註冊(就像JS變數一樣要先做一個宣告的動作),同理,組件也有分為全域性和區域性:

  • 全域註冊:在main.js中可以找到應用程式根實體
    我們在components中新增一個CountTest.vue(SFC單文件組件)的內容之後,到main.js註冊它:
//CountTest.vue
<script setup>
    import { ref } from 'vue'
    const count = ref(0)
</script>
<template>
    <div>
        <text>
            <button @click="count++">互動的次數{{count}}</button>
        </text>
    </div>
</template>
//main.js
import { createApp } from 'vue'
...
import CountTest from '@/components/CountTest.vue'

const app = createApp(App)
app.component("CountTest", CountTest)
...
app.mount('#app')

註冊好之後在任何地方都可以使用它:

//AboutView.vue
<template>
    <div class="about">
        <CountTest />
    </div>
</template>

https://ithelp.ithome.com.tw/upload/images/20240924/20169356Ap0tqRQQmG.png

  • 區域註冊:在父元件上導入CountTest.vue組件
//AboutView.vue
<script>
    import CountTest from '@/components/CountTest.vue'
    export default {
         components: {
             CountTest
         },
         setup() {
         }
    }
</script>

當我們使用<script setup>的情況下,可以省略註冊components的動作:

//AboutView.vue
<script setup>
    import CountTest from '@/components/CountTest.vue'
</script>

非建構式組件

上面我們註冊組件都是以建構模式下單文件組件(SFC)進行示範,那所謂的非建構式呢?

//CountTest.js
import { ref } from 'vue'
export default {
    setup() {
        const count = ref(0)
        return { count }
    },
    template: `<button @click="count++">互動的次數 {{count}} </button>`
}

▲我們有一個純JS檔組件就是非建構式的形式,我們重新引用它看看

//AboutView.vue
import CountTest2 from '@/javascript/CountTest.js'

這時候介面會報錯,它告訴我目前使用的vue版本並不支援非建構式的寫法,替換為vue/dist/vue.esm-bundler.js才可以執行:

main.js:11 [Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".

小結

今天嘗試使用實體掛載非建構式的組件都沒有成功,不知道是不是當前vite版本不支援這樣的寫法,或是我又被小bug卡住啦!看到官方有提醒要在vite.config.js中排除自定義組件,才不會在編譯階段報錯(雖然所有錯誤都排除後我的內容還是沒有出來!),只好先往下走…後續再回頭更新了:

//vite.config.js
vue({
    template: {
        compilerOptions: {
            // 將所有帶短橫線的標籤名都視為自定義元素
            isCustomElement: (tag) => tag.includes('-')
        }
    }
})

參考資料
Vue-組件基礎
Vue-組件註冊
Vue 與 Web Components
重新認識Vue.js 2-1 元件系統的特性


上一篇
【Day8】模組化概念—ES6 Modules
下一篇
【Day10】組件間溝通—Vue Prop&Emit
系列文
歡迎參加我的原生JS畢業典禮12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言