雖然之前筆者提到過Vue.js的檔案有著十分特殊的 SFC(Single-File Components)的特性,不過往往專案作到後來都會因太長或求簡潔等因素而將它根據內容與功能分成多個檔案,因此今天筆者將來與各位一起學習如何實作這個功能,並匯入我們自己製作的於其他檔案中的元件(component)。那麼就讓我們開始今天的內容吧!
匯入其他檔案中元件的方式與許多其他程式語言的相似,只需要在上方的 <script>
區塊內加入:import ChildComp from './ChildComp.vue'
其中 './ChildComp.vue' 是執行的檔案到子檔案的路徑、ChildComp 是元件的名稱。
如此一來我們便能夠其他檔案中使用那些元件了!以下為使用範例:
<!-- 檔案名:App.vue -->
<script setup>
import ChildComp from './ChildComp.vue'
</script>
<template>
<ChildComp />
</template>
<!-- 檔案名:ChildComp.vue -->
<template>
<h2>A Child Component!</h2>
</template>
在使用函式時,我們除了單純的呼叫,也能將參數傳給它們。與這個概念相似,我們也可以給子檔案的元件加入「參數」,或應該以它在此的稱呼,Props
,來叫他們。
Props的設定方式非常直覺,我們將要在子檔案建立一個 <script>
區塊,並在其中利用 defineProps()
函式來建立變數。至於使用時則用前面學過得v-bind
來指定參數並傳入。我們直接來看看下面這個簡單的範例:
<!-- 檔案名:App.vue -->
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const greeting = ref('Hello from parent')
</script>
<template>
<ChildComp :msg=greeting />
</template>
<!-- 檔案名:ChildComp.vue -->
<script setup>
const props = defineProps({
msg: String
})
</script>
<template>
<h2>{{ msg || 'No props passed yet' }}</h2>
</template>
不過,在使用時有下面幾點內容需要注意:
defineProps()
是個Compile-Time Macro(巨集指令),不需要在使用前匯入(import)ref()
建立的,直接傳入字串在此會出現錯誤defineProps()
所建立的變數將能在該檔案中直接呼叫