Vue 组合式 API

Composition API(组合式 API)是将 Vue 应用程序编写到本教程其他地方使用的 Options API 的替代方法。

在 Composition API 中,我们可以更自由地编写代码,但它需要更深入的理解,并且被认为不那么友好。


Composition API(组合式 API)

使用 Composition API,逻辑是使用导入的 Vue 函数编写的,而不是使用我们从 Options API 习惯的 Vue 实例结构。

这就是 Composition API 可以用来编写 Vue 应用程序的方式,该应用程序可以通过按钮减少存储中的打字机数量:

实例

App.vue:

  1. <template>
  2. <h1>Example</h1>
  3. <img src="/img_typewriter.jpeg" alt="Typewriter">
  4. <p>Typewriters left in storage: {{ typeWriters }}</p>
  5. <button @click="remove">Remove one</button>
  6. <p style="font-style: italic;">"{{ storageComment }}"</p>
  7. </template>
  8. <script setup>
  9. import { ref, computed } from 'vue'
  10. const typeWriters = ref(10);
  11. function remove(){
  12. if(typeWriters.value>0){
  13. typeWriters.value--;
  14. }
  15. }
  16. const storageComment = computed(
  17. function(){
  18. if(typeWriters.value > 5) {
  19. return "Many left"
  20. }
  21. else if(typeWriters.value > 0){
  22. return "Very few left"
  23. }
  24. else {
  25. return "No typewriters left"
  26. }
  27. }
  28. )
  29. </script>

第 9 行,setup 属性使使用 Composition API 更加容易。例如,通过使用 setup 属性,可以在 <template> 中直接使用变量和函数。

第 10 行,ref 和 computed 必须导入后才能使用。在 Options API 中,我们不需要导入任何内容来声明反应变量或使用 computed 属性。

第 12 行,ref 用于声明 'typewriters' 属性是响应式的,初始值为 '10'。

将 'typewriters' 属性声明为响应式意味着当 'typewriters' 的属性值发生变化时,<template> 中的行 {{ typewriters }} 将自动重新渲染,以显示更新后的值。使用 Option API,如果应用程序构建时需要响应数据属性,则数据属性将变为响应属性,而无需显式声明为响应属性。

如果实例是在选项 A 中编写的,那么在 第 14 行 声明的 'remove()' 函数将在 Vue 属性 'methods' 下声明。

如果实例是在 Options API 中编写的,则 第 20 行 的 'storageComment' 计算属性将在 Vue 属性 'computed' 下声明。


Options API(选项式 API)

Options API(选项式 API)是本教程其他地方使用的。

本教程选择了 Options API,因为它具有可识别的结构,并且被认为对初学者来说更容易上手。

例如,Options API 中的结构具有数据属性、方法和计算属性,所有这些属性都放置在 Vue 实例的不同部分,并清楚地分开。

下面是上面用 Options API 编写的实例:

实例

App.vue:

  1. <template>
  2. <h1>Example</h1>
  3. <img src="/img_typewriter.jpeg" alt="Typewriter">
  4. <p>Typewriters left in storage: {{ typeWriters }}</p>
  5. <button @click="remove">Remove one</button>
  6. <p style="font-style: italic;">"{{ storageComment }}"</p>
  7. </template>
  8. <script>
  9. export default {
  10. data() {
  11. return {
  12. typeWriters: 10
  13. };
  14. },
  15. methods: {
  16. remove(){
  17. if(this.typeWriters>0){
  18. this.typeWriters--;
  19. }
  20. }
  21. },
  22. computed: {
  23. storageComment(){
  24. if(this.typeWriters > 5) {
  25. return "Many left"
  26. }
  27. else if(this.typeWriters > 0){
  28. return "Very few left"
  29. }
  30. else {
  31. return "No typewriters left"
  32. }
  33. }
  34. }
  35. }
  36. </script>