LoginSignup
38
6

【Vue.js】単一ファイルコンポーネント(SFC)

Last updated at Posted at 2024-06-16

はじめに

Vue.jsのチュートリアルで学んだことをアウトプットしていきます。

概要

単一ファイルコンポーネント(SFC)とは

Vueコンポーネントのテンプレート、ロジック、スタイルを1つのファイルにカプセル化できるコンポーネントの形式(拡張子は.vue

SFCの書き方

OptionAPIとCompositionAPIの違いについてはこちら

SFC(Options API)

<script>
export default {
  data() {
    return {
      greeting: 'Hello World!'
    }
  }
}
</script>

<template>
  <p class="greeting">{{ greeting }}</p>
</template>

<style>
.greeting {
  color: red;
  font-weight: bold;
}
</style>

SFC(Composition API)

<script setup>
import { ref } from 'vue'
const greeting = ref('Hello World!')
</script>

<template>
  <p class="greeting">{{ greeting }}</p>
</template>

<style>
.greeting {
  color: red;
  font-weight: bold;
}
</style>

<script setup>と記述することで、CompositionAPIで書ける。

SFCのメリットとデメリット

メリット

HTML、CSS、JSが同じファイルにまとまるので、機能ごとにコンポーネントを分割して保守・管理しやすい。

デメリット

関心の分離がうまくできず、コードの重複・複雑化が起こりやすい
→デザインとロジックをひとまとめにしているので、「デザインのみ(ロジックのみ)再利用したい時はどうするか?」といった問題が発生する。

まとめ

単一ファイルコンポーネント(SFC)は、テンプレート(template)、ロジック(script)、スタイル(style)を一つのファイルで管理できる。

参考記事

単一ファイルコンポーネント
Tutorial(Vue.js)
SFC(単一ファイルコンポーネント)とは?【Vue.js公式パートナーが解説】

38
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
6