script setup
<script setup> 是單檔元件裡使用 Composition API 的語法糖。頂層的 import、變數、函式會自動暴露給樣板,不必寫 setup() 再 return。官方:script setup。
基本形狀
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<Child />
<button @click="increment">{{ count }}</button>
</template>
編譯時會變成 setup()。每個元件實例會各自跑一遍,所以頂層的 ref 是該實例自己的狀態,不是模組單例。
編譯器巨集
這些函式不必 import,編譯器會處理:
| 巨集 | 用途 |
|---|---|
defineProps() |
宣告 props |
defineEmits() |
宣告事件 |
defineModel() |
簡化 v-model(3.4+) |
defineExpose() |
決定父層透過 template ref 能拿到什麼 |
defineOptions() |
設 name、inheritAttrs 等 |
<script setup>
const props = defineProps({ title: String })
const emit = defineEmits(['close'])
</script>
defineProps 的回傳值在 <script setup> 裡是響應式的,不要解構(會丟追蹤),需要解構時用 toRefs(props) 或編譯器的解構預設值語法。
注意事項
- 一般
<script>與<script setup>可以並存:前者跑一次(適合宣告額外 options 或具名 export),後者每實例一次。 - 頂層
await會讓元件變成 async component,要有<Suspense>才能用。入門先避開。 - 不要在
<script setup>頂層操作 DOM;那時候元件還沒掛載,改放到onMounted。見 生命週期。
推薦影音
The New Vue by Evan You
來源:VueConf Toronto 約 36 分鐘
作者說明為什麼推薦 <script setup>、它怎麼少寫樣板碼,以及和 Vite、TypeScript 怎麼一起用。對應本頁「基本形狀」與編譯器巨集的背景。