当前位置:  首页>> 技术小册>> TypeScript和Vue从入门到精通(三)

10.3.1 关于setup方法

在Vue 3中,setup函数是Composition API的核心入口点,它提供了一个全新的组件逻辑编写方式,使得状态管理、逻辑复用以及类型推导等方面变得更加灵活和强大。本章节将深入解析setup方法的各个方面,包括其基本概念、用法、生命周期钩子集成、响应式状态管理以及与其他Composition API的协同工作。

10.3.1.1 setup方法基础

setup函数是组件内使用Composition API的起点。它是组件创建过程中最早被调用的函数之一(在beforeCreatecreated生命周期钩子之前),且它是唯一一个在this上下文不是组件实例的函数。这意味着在setup内部,你不能直接通过this来访问组件实例的属性和方法。

setup函数接受两个参数:

  • props:一个包含组件外部传入的所有props的响应式对象。
  • context:一个普通JavaScript对象,包含了attrs(非props的Attributes)、slots(插槽)、emit(触发事件的方法)等。
  1. import { defineComponent } from 'vue';
  2. export default defineComponent({
  3. props: {
  4. title: String
  5. },
  6. setup(props, { attrs, slots, emit }) {
  7. // 使用props, attrs, slots, emit
  8. console.log(props.title);
  9. // 逻辑代码...
  10. return {
  11. // 需要暴露给模板的响应式状态或方法
  12. };
  13. }
  14. });

10.3.1.2 响应式状态管理

setup中,我们通常会使用Composition API中的reactiveref等函数来创建响应式状态。这些状态能够自动地跟踪其依赖,并在变化时通知视图进行更新。

  • ref:用于处理基本数据类型的响应式。
  • reactive:用于处理对象或数组的响应式。
  1. import { defineComponent, ref, reactive } from 'vue';
  2. export default defineComponent({
  3. setup() {
  4. const count = ref(0);
  5. const user = reactive({
  6. name: 'Alice',
  7. age: 30
  8. });
  9. function increment() {
  10. count.value++;
  11. }
  12. function updateName(newName: string) {
  13. user.name = newName;
  14. }
  15. return {
  16. count,
  17. user,
  18. increment,
  19. updateName
  20. };
  21. }
  22. });

10.3.1.3 生命周期钩子在setup中的使用

Vue 3提供了onMountedonUpdatedonUnmounted等Composition API版本的生命周期钩子,允许我们在setup函数内部以函数的形式使用这些钩子。

  1. import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
  2. export default defineComponent({
  3. setup() {
  4. const count = ref(0);
  5. onMounted(() => {
  6. console.log('Component is mounted!');
  7. // 执行一些初始化操作
  8. });
  9. onUnmounted(() => {
  10. console.log('Component is unmounted!');
  11. // 执行清理操作,如移除定时器、取消订阅等
  12. });
  13. return {
  14. count
  15. };
  16. }
  17. });

10.3.1.4 setup中的计算属性与监听器

setup中,我们可以使用computedwatch/watchEffect来创建计算属性和监听器。

  • computed:用于创建计算属性,基于它们的响应式依赖进行缓存。
  • watch/watchEffect:用于监听响应式数据的变化,并执行副作用。
  1. import { defineComponent, ref, computed, watch, watchEffect } from 'vue';
  2. export default defineComponent({
  3. setup() {
  4. const count = ref(0);
  5. const doubleCount = computed(() => count.value * 2);
  6. watchEffect(() => {
  7. console.log(`Count is: ${count.value}`);
  8. // 这段代码会在组件渲染时立即执行,
  9. // 以及`count`变化时重新执行
  10. });
  11. watch(count, (newVal, oldVal) => {
  12. console.log(`Count changed from ${oldVal} to ${newVal}`);
  13. // 这段代码仅在`count`变化时执行
  14. });
  15. return {
  16. count,
  17. doubleCount
  18. };
  19. }
  20. });

10.3.1.5 setup与模板的交互

setup函数返回的对象中的所有属性都将被暴露给模板,这使得我们可以在模板中直接使用这些响应式状态和方法。同时,由于setup中没有this,因此无法通过传统方式访问组件实例上的属性或方法。但可以通过context参数中的attrsslotsemit来与模板进行更高级的交互。

  1. <template>
  2. <div>
  3. <h1>{{ user.name }}</h1>
  4. <button @click="increment">Increment</button>
  5. <slot name="custom-slot"></slot>
  6. </div>
  7. </template>
  8. <script lang="ts">
  9. import { defineComponent, reactive, ref } from 'vue';
  10. export default defineComponent({
  11. setup() {
  12. const user = reactive({ name: 'Alice' });
  13. const count = ref(0);
  14. function increment() {
  15. count.value++;
  16. }
  17. return {
  18. user,
  19. count,
  20. increment
  21. };
  22. }
  23. });
  24. </script>

10.3.1.6 总结

setup方法是Vue 3中Composition API的核心,它提供了一种全新的、更灵活的组件逻辑编写方式。通过setup,我们可以更细粒度地控制组件的响应式状态、生命周期钩子、计算属性、监听器等,同时也使得逻辑复用和类型推导变得更加容易。然而,由于setup的特殊性(如没有this上下文),我们需要适应新的编程模式,包括如何正确地暴露状态和方法给模板,以及如何利用context参数与模板进行交互。通过深入学习和实践setup方法,我们可以更加高效地开发Vue 3应用,提升开发效率和代码质量。


该分类下的相关小册推荐: