Vue 组合式 API
Composition API(组合式 API)是将 Vue 应用程序编写到本教程其他地方使用的 Options API 的替代方法。
在 Composition API 中,我们可以更自由地编写代码,但它需要更深入的理解,并且被认为不那么友好。
Composition API(组合式 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 中,我们不需要导入任何内容来声明反应变量或使用 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:
<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>