Vue Composition API
Composition API 是撰寫 Vue 應用的一種替代方法,它不同於本教程其他部分使用的 Options API。
在 Composition API 中,我們可以更自由地編寫程式碼,但它需要更深入的理解,並且被認為對初學者不太友好。
Composition API
使用 Composition API,程式碼是透過匯入的 Vue 函式來編寫的,而不是像我們從 Options API 中習慣的那樣使用 Vue 例項結構。
這是 Composition API 如何用於編寫一個 Vue 應用程式,該應用程式透過一個按鈕來減少庫存打字機的數量。
示例
App.vue
:
<template>
<h1>Example</h1>
<img src="/img_typewriter.jpeg" alt="Typewriter">
<p>Typewriters left in storage: {{ typeWriters }}</p>
<button @click="remove">Remove one</button>
<p style="font-style: italic;">"{{ storageComment }}"</p>
</template>
<script setup>
import { ref, computed } from 'vue'
const typeWriters = ref(10);
function remove(){
if(typeWriters.value>0){
typeWriters.value--;
}
}
const storageComment = computed(
function(){
if(typeWriters.value > 5) {
return "Many left"
}
else if(typeWriters.value > 0){
return "Very few left"
}
else {
return "No typewriters left"
}
}
)
</script>
執行示例 »
在上面示例的第 9 行,setup
屬性使使用 Composition API 更加容易。例如,透過使用 setup
屬性,變數和函式可以直接在 <template>
中使用。
在第 10 行,ref
和 computed
在使用前必須匯入。在 Options API 中,我們不需要匯入任何東西來宣告響應式變數或使用計算屬性。
在第 12 行,ref
用於宣告 'typewriters' 屬性為響應式的,並以 '10' 作為初始值。
宣告 'typewriters' 屬性為響應式意味著 <template>
中的 {{ typewriters }}
行將在 'typewriters' 屬性值改變時自動重新渲染以顯示更新的值。使用 Options API,資料屬性在應用程式構建時如果需要就會變為響應式的,不需要顯式宣告為響應式。
如果示例是用 Options API 編寫的,第 14 行宣告的 'remove()' 函式將宣告在 Vue 的 'methods' 屬性下。
如果示例是用 Options API 編寫的,第 20 行宣告的 'storageComment' 計算屬性將宣告在 Vue 的 'computed' 屬性下。
Options API
Options API 是本教程其他部分使用的。
本教程選擇 Options API 是因為它具有可識別的結構,並且被認為對初學者更容易上手。
例如,Options API 中的結構將資料屬性、方法和計算屬性放置在 Vue 例項的不同部分,清晰地分開。
這是上面示例用 Options API 編寫的版本
示例
App.vue
:
<template>
<h1>Example</h1>
<img src="/img_typewriter.jpeg" alt="Typewriter">
<p>Typewriters left in storage: {{ typeWriters }}</p>
<button @click="remove">Remove one</button>
<p style="font-style: italic;">"{{ storageComment }}"</p>
</template>
<script>
export default {
data() {
return {
typeWriters: 10
};
},
methods: {
remove(){
if(this.typeWriters>0){
this.typeWriters--;
}
}
},
computed: {
storageComment(){
if(this.typeWriters > 5) {
return "Many left"
}
else if(this.typeWriters > 0){
return "Very few left"
}
else {
return "No typewriters left"
}
}
}
}
</script>
執行示例 »