本文將依 Options API、Composition API、<script setup> 的順序,先條列式三者的特徵,後面再附上最基本的程式碼比較其語法差異。
Options API
- 使用 <script> 標籤
- 比較舊
- 效能或安全性與 Composition API 並無差異
- 較不適合 TypeScript
- 大型元件用 Options API 較難管理
- 程式碼的可重用性較差
- 變數及方法定義於各個屬性內,例如 data 屬性定義變數,method 屬性定義方法。
- 變數具備 Reactivity,樣版會即時反應變數變化。
Composition API
- 使用 <script> 標籤
- 比較新
- 效能或安全性與 Options API 並無差異
- 更適合 TypeScript
- 大型元件用 Composition API 較容易管理
- 程式碼的可重用性較佳
- 使用 setup( ){ },變數及方法都定義於 setup 屬性內。
- 需使用 ref( ) 方法為變數賦值才可使變數具備 Reactivity,促使樣版即時反應變數變化。
<script setup>
- 使用 <script setup> 標籤
- 比 Composition API 更新,Composition API 的語法糖。
- 效能比原始的 Composition API 佳
- 不使用 setup( ){ },也不需要 export default,變數及方法都定義於 <script setup> 標籤之間。
Options API 範例
<template>
<h1>Hello Options API: {{ count }}</h1>
<button @click.prevent="increment">Hello Options API Increment</button>
</template>
<script>
export default {
name: "OptionsAPI",
data() {
return {
count: 0,
};
},
methods: {
increment() {
this.count++;
},
},
};
</script>
Composition API 範例
<template>
<h1>Hello Composition API: {{ count }}</h1>
<button @click.prevent="increment">Hello Composition API Increment</button>
</template>
<script>
import { ref } from "vue";
export default {
name: "CompositionAPI",
setup() {
const count = ref(0);
function increment() {
count.value++;
}
return {
count,
increment,
};
},
};
</script>
<script setup>
範例
<template>
<h1>Hello <script setup>: {{ count }}</h1>
<button @click.prevent="increment">
Hello <script setup> Increment
</button>
</template>
<script setup>
import { ref } from "vue";
const count = ref(0);
function increment() {
count.value++;
}
</script>