在 Vue 3 中,setup
是一个新的组件选项,它允许你使用 Composition API 来组织你的组件逻辑。setup
函数是一个组件生命周期钩子之前运行的函数,它接收两个参数:props
和 context
。
setup
函数参数
- props: 组件的属性,是一个响应式的对象,与
this.$props
类似。 - context: 一个对象,包含了组件的
attrs
、slots
、emit
等属性。
使用 setup
在 setup
函数中,你可以使用 ref
、reactive
、computed
等函数来创建响应式的数据和方法。
例如:
<template>
<div>
<p>{
{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
// 使用 ref 创建一个响应式的引用
const count = ref(0);
// 定义一个方法来增加计数器的值
const increment = () => {