在 Vue 3 的 <script setup> 和傳統(tǒng) <script> 寫法之間存在幾個關鍵區(qū)別,主要體現(xiàn)在代碼結構、功能支持和開發(fā)體驗上。以下是詳細對比:
1. 基本語法對比
<script setup>(Composition API 風格)
<script setup lang="ts">
// 直接編寫邏輯,自動暴露頂層綁定
import { ref } from 'vue'
const count = ref(0)
</script>
-
特點:
- 頂層變量/函數(shù)自動暴露給模板。
- 無需手動注冊組件或返回數(shù)據(jù)。
- 天然支持 TypeScript。
傳統(tǒng) <script>(Options API 或 Composition API)
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const count = ref(0)
return { count } // 需手動返回
}
})
</script>
-
特點:
- 需要
defineComponent包裹。 - Composition API 需在
setup()函數(shù)內編寫邏輯并顯式返回。 - Options API 需按
data、methods等選項組織代碼。
- 需要
2. 核心區(qū)別
| 特性 | <script setup> |
傳統(tǒng) <script> |
|---|---|---|
| 代碼簡潔性 | 更簡潔,減少模板代碼 | 需要更多樣板代碼(如 export default) |
| 數(shù)據(jù)暴露 | 頂層綁定自動暴露 | 需手動返回(Composition API)或定義(Options API) |
| TypeScript 支持 | 原生友好,類型推斷更完善 | 需額外類型聲明(如 defineComponent) |
| 組件注冊 | 直接導入即用 | 需在 components 選項中注冊 |
| 指令與宏 | 支持 defineProps、defineEmits 等編譯宏 |
需通過 props 和 emits 選項定義 |
| Ref 模板引用 | 直接使用 ref 變量 |
需通過 this.$refs 訪問 |
| 生命周期鉤子 | 直接導入使用(如 onMounted) |
在 setup() 內或選項式 API 中定義 |
3. 功能差異詳解
(1)Props & Emits 聲明
-
<script setup>:const props = defineProps<{ msg: string }>() const emit = defineEmits<{ (e: 'update'): void }>() -
傳統(tǒng)
<script>:export default defineComponent({ props: { msg: String }, emits: ['update'], setup(props, { emit }) { /* ... */ } })
(2)組件注冊
-
<script setup>:<script setup> import ChildComp from './Child.vue' // 自動注冊 </script> -
傳統(tǒng)
<script>:export default defineComponent({ components: { ChildComp }, // 手動注冊 setup() { /* ... */ } })
(3)對外暴露方法
-
<script setup>:
使用defineExpose:const publicMethod = () => {} defineExpose({ publicMethod }) -
傳統(tǒng)
<script>:
setup()返回的方法自動暴露。
4. 編譯差異
-
<script setup>:- 在編譯時轉換為高效的渲染函數(shù),無運行時性能開銷。
- 宏(如
defineProps)會被編譯為靜態(tài)代碼。
-
傳統(tǒng)
<script>:- Options API 依賴運行時解析,體積略大。
5. 使用場景建議
| 場景 | 推薦寫法 | 理由 |
|---|---|---|
| 新項目/Vue 3 | <script setup> |
更簡潔、類型安全、性能優(yōu)化 |
| 維護舊代碼 | 傳統(tǒng) <script>
|
兼容 Options API |
| 需要顯式控制暴露 | 傳統(tǒng) <script>
|
setup() 返回更靈活 |
| 庫開發(fā) | 根據(jù)使用者環(huán)境選擇 | 確保兼容性 |
6. 代碼轉換示例
Options API → <script setup>
<!-- 傳統(tǒng) -->
<script>
export default {
data() {
return { count: 0 }
},
methods: {
increment() { this.count++ }
}
}
</script>
<!-- <script setup> -->
<script setup>
const count = ref(0)
const increment = () => count.value++
</script>
Composition API → <script setup>
<!-- 傳統(tǒng) -->
<script>
export default {
setup() {
const count = ref(0)
return { count }
}
}
</script>
<!-- <script setup> -->
<script setup>
const count = ref(0) // 自動暴露
</script>
總結
-
<script setup>是 Vue 3 的現(xiàn)代寫法,適合追求簡潔和 TypeScript 的項目,但需熟悉編譯宏。 -
傳統(tǒng)
<script>更適合需要顯式控制或兼容舊代碼的場景。
選擇時需權衡 開發(fā)效率、維護成本 和 團隊習慣。