Skip to content

setup

1.基本概念

setup是所有Composition API(组合API)表演的舞台 ”。

组件中所用到的:数据、方法等等,均要配置在setup中。

使用方法如下:

vue
<template></template>

<script>
    import {ref} from 'vue'
    export default{
        setup(){
			const num = ref(123)
            return {
                num
            }
        }
    }
</script>

setup函数的两种返回值:

  • 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)
  • 若返回一个渲染函数:则可以自定义渲染内容。(了解)

注意

使用此setup语法,任何定义的变量都应return出去,不然在别处使用不了

在Vue3的生命周期中没有created,但setup的执行时机在created之前,所以setup相当于created

2.setup语法糖

2.1 语法

setup语法糖是在Vue3.2x版本更新的,其语法相较于setup()函数要方便许多

vue
<script setup>
    import {ref} from 'vue'

    const num = ref(123)
</script>

当我们使用setup语法糖之后:

  • 直接在<script setup></script>内写js语句
  • 定义的数据不需要再return出去
  • 不需要export导出

2.2 与普通script一起用

<script setup>可以和普通的 <script> 一起使用。普通的 <script> 在有这些需要的情况下或许会被使用到:

  • 声明无法在 <script setup> 中声明的选项,例如 inheritAttrs 或插件的自定义选项 (在 3.3+ 中可以通过 defineOptions 替代)。
  • 声明模块的具名导出 (named exports)。
  • 运行只需要在模块作用域执行一次的副作用,或是创建单例对象。
vue
<script>
// 普通 <script>,在模块作用域下执行 (仅一次)
runSideEffectOnce()

// 声明额外的选项
export default {
  inheritAttrs: false,
  customOptions: {}
}
</script>

<script setup>
// 在 setup() 作用域中执行 (对每个实例皆如此)
</script>

2.3 顶层 await

<script setup> 中可以使用顶层 await。结果代码会被编译成 async setup()

vue
<script setup>
const post = await fetch(`/api/post/1`).then((r) => r.json())
</script>

另外,await 的表达式会自动编译成在 await 之后保留当前组件实例上下文的格式。

注意

async setup() 必须与 Suspense 组合使用,该特性目前仍处于实验阶段。我们计划在未来的版本中完成该特性并编写文档——但如果你现在就感兴趣,可以参考其测试来了解其工作方式。

3.事件

不管是在setup()函数还是在setup语法糖,定义方法只需要和原生js一样定义

vue
<script setup>
const add = () => {
  console.log(1+1)
  console.log(1+1)
}

function print(){
  console.log("hello world")
}
</script>
vue
<script>
    export default {
        setup(){
            const add = () => {
                console.log(1+1)
                console.log(1+1)
            }

            function print(){
                console.log("hello world")
            }
            return {
                add,print
            }
        }
    }
</script>

MIT Licensed