iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Modern Web

【網頁是什麼,能吃嗎】── 零基礎也能學會網頁製作系列 第 11

【Day 11】把檔案拆開吧── Vue.js 入門篇

  • 分享至 

  • xImage
  •  

雖然之前筆者提到過Vue.js的檔案有著十分特殊的 SFC(Single-File Components)的特性,不過往往專案作到後來都會因太長或求簡潔等因素而將它根據內容與功能分成多個檔案,因此今天筆者將來與各位一起學習如何實作這個功能,並匯入我們自己製作的於其他檔案中的元件(component)。那麼就讓我們開始今天的內容吧!

匯入(import)模組

匯入其他檔案中元件的方式與許多其他程式語言的相似,只需要在上方的 <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,來叫他們。

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() 建立的,直接傳入字串在此會出現錯誤
  • 傳入參數時要記得使用 v-bind
  • 利用 defineProps() 所建立的變數將能在該檔案中直接呼叫

上一篇
【Day 10】DOM的處理小助手:Vue.js 入門篇
下一篇
【Day 12】子元件的更多應用── Vue.js 入門篇
系列文
【網頁是什麼,能吃嗎】── 零基礎也能學會網頁製作14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言