2024-12-26 Vue3_script setup

2024-12-26 Vue3_script setup

太好了!這裡是給你的一張超實用 ✅ Vue 3 <script setup> 小抄,超簡明清晰,保證新手也看得懂:


🧠 <script setup> 小抄速查表

✅ 基本語法

1
2
3
4
5
6
7
8
9
<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>

<template>
<button @click="count++">點我:{{ count }}</button>
</template>

📌 常用功能速查表

功能 寫法(<script setup> 說明
定義變數 const name = ref('Lily') ref 用來定義可變變數(響應式)
多個變數 const a = ref(1); const b = ref(2) 多個 ref
陣列/物件 const users = ref([]) 可以用 .value.push(...) 修改
方法(函式) function sayHi() { console.log('Hi') } 直接定義函式即可
引入元件 import MyComponent from './MyComponent.vue' 然後在 <template> 中使用
v-for 用 key <li v-for="item in list" :key="item.id"> 綁定 key 用 :v-bind
計算屬性 import { computed } from 'vue'
const total = computed(() => a.value + b.value)
自動更新的計算值
props(接收外部傳值) defineProps(['title'])defineProps<{ title: string }>() 自動建立 props

🔥 加分技巧

reactive(多層物件)

1
2
3
4
5
6
import { reactive } from 'vue'

const user = reactive({
name: 'Lily',
age: 18
})

✅ 不用 return,變數自動可在 template 用!

1
const message = ref('Hello')
1
2
3
<template>
<p>{{ message }}</p>
</template>

😎 你可以這樣記住:

  • ref():單一值(字串、數字)
  • reactive():多層資料(物件、陣列)
  • <script setup>:變數不用回傳(return),直接就能用!

如果你想,我可以幫你做一個 SplitBill.vue 的練習版,搭配 <script setup> + ref(),讓你邊看邊做!

要現在來寫「新增成員功能」嗎?還是你想再熟悉一下某個概念?🌱