Vue3 中新增的 feature 之一是 compositon API, 使用 options API (选项式API) 构建组件是最基本的方式。
composition API 的出现主要是为了解决大型 APP 中可能出现的两个问题:逻辑不能重用,以及组件对象中相关的值与逻辑分散,例如关于某一相同属性的逻辑分散在 data(), computed, methods, watch
各处。
使用 composition API, 就能将data()
, methods
, computed
和 watch
属性组合/合并到一个统一的 setup()
函数中。
使用 composition API,props
,components
,emits
等属性都不受影响,但是生命周期钩子函数例外。
下面的 code, 使用 composition API, 在页面上显示一个userName,3 秒后,改成另一个userName。注释部分是使用 Options API.
<template>
<section class="container">
<h2>{{ userName }}</h2>
</section>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const uName = ref('Maximilian');
setTimeout(() => {
// 不能直接写成 uName = "Max" !!!
uName.value = "Max";
}, 3000);
return {
userName: uName,
};
},
// 使用 Options API
// data() {
// return {
// userName: 'Maximilian',
// };
// },
};
</script>
首先需要 import ref, ref 函数可以在 setup 函数中使用,它创建一个对象,此对象有一个value 属性,ref() 的参数就是value属性的初始值,可以是boolean,string,object,等等。
setup
总是返回一个对象,模板需要的内容,都由此对象提供。在模板里不能使用 .value
, 如果将 ref 传递给模板,Vue会自动读取 value
属性。
上述代码,如果只是单纯显示一个 userName,不一定要使用 ref,但是,使用 ref 能够创建 reactive value 反应值, 即如果 setup() 中 userName 的值发生改变,Vue 将自动更新template 和 DOM。