Vue3 组合式API

Vue3组合式API小白指南

Vue3 组合式API知识点汇总

编程小白也能懂的Vue3组合式API详细指南 – 大白话讲解核心概念

setup() 函数

组合式API的入口点,替代了Vue2的data、methods等选项

在组件创建之前执行,此时组件实例尚未创建,无法使用this

接收两个参数:propscontext

// 基本结构
export default {
  setup(props, context) {
    // 在这里声明响应式数据、计算属性、方法等
    return {
      // 返回模板中需要使用的数据和方法
    }
  }
}
💡 小贴士:setup函数中返回的所有内容都可以在模板中直接使用
ref() 和 reactive()

ref()

用于创建基本类型的响应式数据(字符串、数字等)

在JS中使用时需要.value访问,模板中会自动解包

import { ref } from ‘vue’;

const count = ref(0); // 创建一个响应式数字
console.log(count.value); // 0
count.value++; // 修改值

reactive()

用于创建对象类型的响应式数据

不需要.value即可访问属性

import { reactive } from ‘vue’;

const state = reactive({
  name: ‘小明’,
  age: 25
});

state.age = 26; // 直接修改属性
computed() 和 watch()

computed()

创建计算属性,基于响应式数据自动计算

返回一个ref对象,同样需要.value访问

import { computed, ref } from ‘vue’;

const firstName = ref(‘张’);
const lastName = ref(‘三’);

const fullName = computed(() => {
  return firstName.value + lastName.value;
});

console.log(fullName.value); // 张三

watch()

监听响应式数据的变化

可以监听单个或多个数据源

import { watch, ref } from ‘vue’;

const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`计数从${oldValue}变为${newValue}`);
});
生命周期钩子

组件也有自己的生命周期,可以在不同阶段执行特定逻辑

import { onMounted, onUpdated, onUnmounted } from ‘vue’;

setup() {
  onMounted(() => {
    console.log(‘组件挂载完成’);
  });

  onUpdated(() => {
    console.log(‘组件更新了’);
  });

  onUnmounted(() => {
    console.log(‘组件卸载了’);
  });
}

常用生命周期钩子:

  • onBeforeMount – 挂载前
  • onMounted – 挂载完成
  • onBeforeUpdate – 更新前
  • onUpdated – 更新完成
  • onBeforeUnmount – 卸载前
  • onUnmounted – 卸载完成
组件通信

Props

父组件向子组件传递数据

// 子组件
export default {
  props: [‘message’],
  setup(props) {
    console.log(props.message);
  }
}

Emit

子组件向父组件发送事件

// 子组件
setup(props, { emit }) {
  const sendMessage = () => {
    emit(‘message’, ‘你好父组件!’);
  }
}

Provide/Inject

跨层级组件传递数据

// 祖先组件
import { provide, ref } from ‘vue’;

setup() {
  const theme = ref(‘dark’);
  provide(‘theme’, theme);
}

// 后代组件
import { inject } from ‘vue’;

setup() {
  const theme = inject(‘theme’);
}
模板引用 & 自定义Hooks

模板引用 (ref)

获取DOM元素或组件实例

<template>
  <input ref=”inputRef” />
</template>

import { ref, onMounted } from ‘vue’;

setup() {
  const inputRef = ref(null);

  onMounted(() => {
    inputRef.value.focus(); // 挂载后聚焦输入框
  });

  return { inputRef };
}

自定义Hooks

将可复用的逻辑抽离为自定义函数

// useCounter.js
import { ref } from ‘vue’;

export default function useCounter() {
  const count = ref(0);
  const increment = () => count.value++;
  const decrement = () => count.value–;

  return { count, increment, decrement };
}

// 在组件中使用
import useCounter from ‘./useCounter’;

setup() {
  const { count, increment } = useCounter();
  return { count, increment };
}

组合式API实战演示

{{ count }}

这是一个使用组合式API(ref, computed)的计数器

待办事项 (使用reactive, computed)

  • {{ todo.text }}

总任务: {{ totalTodos }}, 已完成: {{ completedTodos }}

Vue3组合式API知识点汇总 | 为编程小白量身定制

通过组合式API,你可以更好地组织和复用代码逻辑,提高代码可读性和可维护性

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部