0Pricing
Frontend Academy · レッスン

setup() 関数と script setup

setup() 関数にロジックを書き、または の構文糖を使い、値をテンプレートに公開し、Composition API のライフサイクルフックを理解します。

「setup() 関数と script setup」はCoddyKit上の無料Frontend Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはFrontend Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Frontend Academyコースには全4レッスンが含まれています。

setup() 関数

Vue 3 の Composition API では、setup() は data、methods、computed、watch を置き換えるコンポーネントオプションです。props と setup コンテキストを引数として受け取り、テンプレートに必要なものを返します。

export default {
  props: { userId: String },
  setup(props, { emit, attrs, slots }) {
    const user = ref(null);
    onMounted(async () => {
      user.value = await fetchUser(props.userId);
    });
    return { user }; // must return what template uses
  }
};

<script setup> — シンタックスシュガー

<script setup> は setup() のコンパイル時シンタックスシュガーです。トップレベルで宣言したものはすべて自動的にテンプレートから利用できます。return 文は必要ありません。

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const count = ref(0);
// count is automatically available in template
</script>

setup() のライフサイクルフック

Vue 3 のライフサイクルフックはインポートして使用する関数です。onMounted、onUpdated、onUnmounted、onBeforeMount、onBeforeUpdate などがあります。複数回呼び出して、複数のハンドラーを登録できます。

<script setup>
import { onMounted, onUnmounted } from 'vue';

let timer: ReturnType<typeof setInterval>;

onMounted(() => {
  timer = setInterval(tick, 1000);
  console.log('Component mounted');
});

onUnmounted(() => {
  clearInterval(timer); // cleanup
});
</script>

setup() の props

setup() 内の props はリアクティブです。直接分割代入しないでください — リアクティビティを維持するには、toRefs(props) を使用するか、props.x でアクセスします。

const props = defineProps<{ userId: string }>();

// Reactive access:
watch(() => props.userId, (id) => fetchUser(id));

// toRefs for destructuring:
const { userId } = toRefs(props);

defineExpose() — 親コンポーネントへの公開

デフォルトでは、