setup() 函数与 script setup
在 setup() 函数中编写逻辑,或使用 语法糖,将值暴露给模板,并了解组合式 API 中的生命周期钩子。
setup() 函数与 script setup 是 CoddyKit 上的免费 Frontend Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Frontend Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Frontend Academy 课程共包含 4 节课。
setup() 函数
在 Vue 3 的组合式 API 中,setup() 是一个组件选项,用来替代 data、methods、computed 和 watch。它接收 props 和 setup 上下文作为参数,并返回模板所需的内容。
export default {
props: { userId: String },
setup(props, { emit, attrs, slots }) {
const user = ref(null);
onMounted(async () => {
user.value = await fetchUser(props.userId);
});
return { user }; // must return what template uses
}
};<script setup> — 语法糖
<script setup> 是 setup() 的编译时语法糖。顶层声明的所有内容都会自动在模板中可用。无需 return 语句。
<script setup lang="ts">
import { ref, onMounted } from 'vue';
const count = ref(0);
// count is automatically available in template
</script>setup() 中的生命周期钩子
Vue 3 的生命周期钩子是导入的函数:onMounted、onUpdated、onUnmounted、onBeforeMount、onBeforeUpdate 等。您可以多次调用它们,以注册多个处理函数。
<script setup>
import { onMounted, onUnmounted } from 'vue';
let timer: ReturnType<typeof setInterval>;
onMounted(() => {
timer = setInterval(tick, 1000);
console.log('Component mounted');
});
onUnmounted(() => {
clearInterval(timer); // cleanup
});
</script>setup() 中的 props
在 setup() 中,props 具有响应性。不要直接解构它们——请使用 toRefs(props),或通过 props.x 访问,以保持响应性。
const props = defineProps<{ userId: string }>();
// Reactive access:
watch(() => props.userId, (id) => fetchUser(id));
// toRefs for destructuring:
const { userId } = toRefs(props);defineExpose()——向父组件暴露内容
默认情况下,