setup

setup 函数是 Vue 3 中组合式 API 的核心,作为 Composition API 的入口,它允许我们将组件的数据、方法、计算属性和监听器等集中管理。

特点
  • 执行时机:setup 函数在组件实例化时自动执行,且在任何生命周期钩子之前。
  • 模版可用性:setup 函数返回的对象中的属性和方法可以直接在模板中使用。
  • this指向:在setup 函数中, this 始终指向 undefined
使用方式

setup 函数返回一个对象时,对象中的属性和方法可以直接在模板中使用。

setup 函数返回一个函数时,可以自定义渲染内容。

1<script lang="ts">
2import {
3  defineComponent,
4  ref
5} from 'vue'
6
7export default defineComponent({
8  setup() {
9    const num = ref(0)
10
11    const increment = () => {
12      num.value++
13    }
14
15    return {
16      num,
17      increment
18    }
19  }
20})
21</script>
22
23<template>
24  <button @click="increment">{{ num }}</button>
25</template>
1<script lang='ts'>
2export default {
3  setup() {
4    return () => 'Hello Vue3'
5  }
6}
7</script>

:::

setup语法糖

<script setup> 是 Vue 3 提供的一种编译时语法糖,它使得使用组合式 API 编写组件更加简洁和直观。

特点
  • 编译时处理:<script setup> 中的代码会被编译成组件的 setup() 函数内容。
  • 实例化执行:与普通的 <script> 只在组件被首次引入的时候执行一次不同,<script setup> 中的代码会在每次组件实例被创建时执行
  • 顶层绑定暴露:在 <script setup> 中声明的顶层变量、函数以及 import 导入的内容都可以直接在模板中使用。
1<script lang="ts" setup>
2import { ref } from 'vue'
3
4const num = ref(0)
5
6const increment = () => {
7  num.value++
8}
9</script>
10
11<template>
12  <button @click="increment">{{ num }}</button>
13</template>

setup 与 Options API

  • Options API 中可以访问 setup 中的属性和方法。
  • setup 中不能访问 Options API 的配置。
  • 冲突时,setup 优先。
1<template>
2  <h2>Options API</h2>
3  <p>{{ a }}</p>
4  <p>{{ b }}</p>
5  <h2>Composition API</h2>
6  <p>{{ x }}</p>
7</template>
8<script lang="ts">
9export default {
10  name: 'App',
11  data() {
12    return {
13      a: 'aaa',
14      b: this.x,
15    }
16  },
17  setup() {
18    const x = 'ccc'
19
20    return {
21      x,
22    }
23  },
24}
25</script>