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>
运行示例 »