Vue2 與 Vue3 主要用法差異 - daniel-qa/Vue GitHub Wiki
- 取得 API
this.$api.serviceDriveAuth.getSchoolProduct(this.$store.state.userInfo.schoolCode).then(
res => {
this.productData = res
}
)
.then(res => { ... }) 等待 API 回應成功後,把結果 res 拿來做事(這裡是設定 productData)
this.productData = res 把從伺服器取得的資料響應式變數 productData,可直接用在畫面上綁定顯示
- 使用 prop 傳資料給子組件
service 資料的傳遞方式
從 Index.vue 到 Product.vue 的傳遞: 在 Index.vue 的模板中,可以看到 service 資料是通過 props 傳遞給 Service 組件(即 Product.vue)的:
<Service v-if="tabName == 'service'" :service="productData.service"></Service>
productData.service 是從 API 獲取的服務資料,通過 :service 屬性傳遞給 Service 組件。
在 Product.vue 中,通過 props 接收這個 service 資料:
props: {
service: {
type: Array,
default: () => {
return []
}
}
}
- Watch 監看
watch: {
service: {
deep: true,
immediate: true,
handler(n, o) {
if (n) {
this.formatData()
}
}
}
}
屬性 | 意義 |
---|---|
service |
要監聽的資料欄位(可以是 props、data、computed) |
deep: true |
深層監聽(如果 service 是一個物件或陣列,內部屬性改變也會觸發) |
immediate: true |
立即執行 handler,一進來就觸發一次(不是等資料變動才執行) |
handler(n, o) |
變動時的處理函式,n 是新值,o 是舊值 |
- props 與 data:
props:
用於接收從父組件傳來的數據
是單向數據流(父組件 → 子組件)
子組件不應該直接修改 props 的值
在
data:
用於定義組件內部的響應式數據
是組件私有的,其他組件無法直接訪問
組件可以自由修改 data 中的值
- props: { productInfo: { ... } }
這是 Vue 2 的 props 宣告方式。
這段定義了 productInfo 這個 prop,代表這個元件可以從父元件接收到一個 productInfo 的屬性。
- type: Object
指定這個 prop 必須是「物件」型別。
- default: () => { return {} }
錯誤的例子
props: {
productInfo: {
type: Object,
default: {}
}
}
這樣寫會讓 所有使用這個元件的實例共用同一個物件記憶體位址。
正確寫法(每次都回傳新物件):
default: () => {
return {}
}
如果使用箭式,可以直接使用 箭號,省去 return
props: {
tags: {
type: Array,
default: () => []
}
}
這裡的 () => [] 是 一個箭頭函式(arrow function),
而因為沒有大括號 {},所以它是 隱式 return。
它其實等同於:
default: () => {
return []
}
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}
<script setup>
import { ref } from 'vue'
const count = ref(0)
const increment = () => {
count.value++
}
</script>
- Vue 2
data() {
return {
message: 'Hello',
user: {
name: 'John',
age: 30
}
}
}
- Vue 3
<script setup>
import { ref, reactive } from 'vue'
const message = ref('Hello')
const user = reactive({
name: 'John',
age: 30
})
</script>
- Vue 2
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
- Vue 3
<script setup>
import { computed } from 'vue'
const fullName = computed(() => {
return firstName.value + ' ' + lastName.value
})
</script>