Vue3

作者:Thomas che3 分钟阅读
浏览量:加载中...
#vue3

Vue3常用

Vue3

vue3

一、响应式核心方法(响应式数据)

1. ref()

作用: 定义基本类型/对象的响应式数据(可用于模板渲染)

1const count = ref(0); // 自动变成响应式 2count.value++; // 修改方式:.value

2. reactive()

作用:定义一个对象的响应式状态(引用类型推荐用这个)

1const user = reactive({ 2 name: '车车', 3 age: 18, 4}); 5user.age++;

3. readonly()

作用:把一个对象变成只读响应式,防止被修改(常用于 props 深层保护)

1const state = reactive({ count: 1 }); 2const readonlyState = readonly(state); 3 4// readonlyState.count = 10 ❌ 报错

4. toRefs()

作用:把 reactive 对象中的属性解构成 ref,用于解构时保留响应性

1const state = reactive({ name: '车车', age: 20 }); 2const { name, age } = toRefs(state); 3 4name.value = '小车'; // ✅ 响应性保留

二、生命周期钩子(组合式 API 中)

钩子含义
onMounted组件挂载后
onUpdated组件更新后
onUnmounted组件卸载前
onBeforeMount挂载前

三、监听器

1. watch()

监听指定变量变化,执行副作用逻辑(比如网络请求)

1watch(count, (newVal, oldVal) => { 2 console.log('count 变了:', newVal); 3});

2. watchEffect()

自动追踪依赖的响应式变量,立即执行一次 依赖项 必须是响应式的(比如 ref, reactive,否则不会追踪)。

watchEffect 会在组件加载时立即执行一次。

如果里面使用了 async 函数,建议用 watch 而不是 watchEffect,避免陷入副作用同步问题

1<template> 2 <div> 3 <input v-model.number="count" type="number" /> 4 <p>总价是:{{ total }}</p> 5 </div> 6</template> 7 8<script setup> 9import { ref, watchEffect } from 'vue' 10 11const count = ref(1) 12const price = ref(100) 13const total = ref(0) 14 15// 自动追踪 count 和 price 16watchEffect(() => { 17 total.value = count.value * price.value 18}) 19</script> 20

四、模板引用与 DOM 操作

ref + onMounted 获取 DOM:

1<template> 2 <input ref="inputRef" /> 3</template> 4 5<script setup lang="ts"> 6const inputRef = ref<HTMLInputElement | null>(null); 7 8onMounted(() => { 9 inputRef.value?.focus(); // 获取 DOM 节点 10}); 11</script> 12

五、计算属性 computed()

1const count = ref(2); 2const double = computed(() => count.value * 2);

会自动缓存和依赖追踪

只在依赖变更时重新计算

六、异步逻辑控制(组合)

用 async + onMounted:

1onMounted(async () => { 2 const res = await fetch('/api/user'); 3 const data = await res.json(); 4});

七、defineProps / defineEmits(组件通信专用)

1const props = defineProps<{ name: string }>(); 2 3const emit = defineEmits<{ 4 (e: 'change', payload: string): void; 5}>();

八、provide / inject(跨组件共享)

1// 父组件 2provide('theme', ref('dark')); 3 4// 子组件 5const theme = inject<Ref<string>>('theme');

🧠 推荐组合使用思维

场景推荐组合
数据响应式ref / reactive / computed
生命周期逻辑onMounted / onUnmounted
表单与 DOM 交互ref + onMounted
组件通信defineProps + emit
父子状态共享provide / inject
本地状态 + API 联动watchEffect / watch