Skip to main content

<script setup> 下使用 <component :is>

前提

專案結構在使用 Composition API <script setup> 的寫法,在 Component 內進行切換並搭配 <Transition>,進而達成切換 Component 的同時產生轉場動畫。

不過,原本在 Options API 可正常運作的寫法,改成 <script setup> 後便無法正常動作,於是開始問題排解。

解決方案

切換 card 的 function cardFlip() 加上 markRaw 即可正常動作

根據官方文件表示,此用法的作用為 "Marks an object so that it will never be converted to a proxy. Returns the object itself."

<script setup>
import { ref, markRaw, computed } from 'vue'
import Card from './Card.vue'
import Card1 from './Card1.vue'

const toggleArrow = ref(false)
const activeCard = ref(null)

cardFlip()
function cardFlip() {
if (activeCard.value === BingoCard) {
activeCard.value = markRaw(Card)
} else {
activeCard.value = markRaw(BingoCard)
}
}
</script>
<template>
...
<Transition name="fade" mode="out-in">
<component :is="activeCard"></component>
</Transition>

</template>

心得

因為在新專案中全面使用 <script setup>,導致之前在 Options API 正常使用的寫法會有些出入、甚至無法正常運作,像是 <component :is> 就算是其中一個實例。

原本以為是自己不熟悉用法還是邏輯有問題,比對官方文件翻找了半天,才發現要用 <makeraw>方能正常運作,而且網路上討論度也不太高,算是剛好踩到這個坑,順手記錄起來提醒自己。

參考資料