setup()
函数:Vue 3 组件的核心舞台在Vue 3中,setup()
函数是组件内使用Composition API的入口点,它标志着Vue组件开发方式的一次重大变革。相比Vue 2的Options API,Composition API通过setup()
函数提供了一种更加灵活、逻辑复用的方式来组织组件代码。在本章中,我们将深入探讨setup()
函数的各个方面,包括其基础用法、生命周期钩子、响应式引用、计算属性、侦听器和组件通信等。
setup()
函数基础setup()
函数是组件中所有Composition API调用的起点。它在组件被创建之前被调用,并且是beforeCreate
和created
生命周期钩子之前被调用的唯一生命周期函数。setup()
函数接收两个参数:props
和context
。
attrs
、slots
、emit
等。这允许你在setup()
函数内部访问这些属性和方法。
<template>
<div>{{ count }}</div>
<button @click="increment">Increment</button>
</template>
<script>
import { ref } from 'vue';
export default {
props: {
initialCount: Number
},
setup(props, { emit }) {
const count = ref(props.initialCount);
function increment() {
count.value++;
emit('update:count', count.value);
}
return {
count,
increment
};
}
};
</script>
在上面的例子中,setup()
函数接收了props
并基于initialCount
prop创建了一个响应式的count
引用。然后,定义了一个increment
函数来更新count
的值,并通过emit
方法触发一个自定义事件。最后,通过返回对象,使得count
和increment
在模板中可用。
在setup()
函数中,我们经常使用ref
和reactive
来创建响应式状态。ref
用于基本数据类型,而reactive
用于对象或数组。
ref
创建的响应式数据是一个对象,该对象包含一个.value
属性来存储实际的值。reactive
允许你直接以响应式方式操作对象或数组,无需.value
属性。
import { ref, reactive, computed } from 'vue';
setup() {
const count = ref(0);
const user = reactive({ name: 'Alice', age: 30 });
const fullName = computed(() => {
return `${user.name} ${user.surname || ''}`;
});
return {
count,
user,
fullName
};
}
在上面的代码中,我们还使用了computed
来创建一个计算属性fullName
,它基于user
对象动态生成全名。计算属性是基于它们的依赖进行缓存的,只有当依赖项发生变化时才会重新计算。
在Vue 3中,侦听器通过watch
和watchEffect
函数实现,它们在setup()
函数中广泛使用来观察响应式数据的变化并执行副作用。
import { ref, watch, watchEffect } from 'vue';
setup() {
const count = ref(0);
watchEffect(() => {
console.log(`count is: ${count.value}`);
});
watch(count, (newValue, oldValue) => {
console.log(`count changed from ${oldValue} to ${newValue}`);
}, { immediate: true, deep: false });
return {
count
};
}
虽然setup()
函数替代了Vue 2中的beforeCreate
和created
生命周期钩子,但你仍然可以在setup()
函数内部通过onMounted
、onUpdated
等Composition API提供的生命周期钩子来访问组件的生命周期。
import { onMounted, onUpdated, ref } from 'vue';
setup() {
const count = ref(0);
onMounted(() => {
console.log('Component is mounted!');
});
onUpdated(() => {
console.log('Component updated!');
});
return {
count
};
}
在setup()
函数中,组件间的通信主要通过props
、emit
以及provide
/inject
实现。前面已经展示了如何使用props
和emit
,这里简要介绍provide
/inject
。
// 祖先组件
setup() {
const theme = ref('dark');
provide('theme', theme);
return {};
}
// 后代组件
setup() {
const theme = inject('theme');
return {
theme
};
}
setup()
函数作为Vue 3中Composition API的核心,为开发者提供了一种全新的、更灵活的方式来组织和复用Vue组件的逻辑。通过setup()
函数,我们可以更方便地利用响应式引用、计算属性、侦听器、生命周期钩子和组件通信等特性,从而编写出更加清晰、高效和可维护的Vue组件。掌握setup()
函数及其相关API的使用,是深入学习Vue 3和Composition API的关键。