[TOC]

摘要

在单文件组件中引入了一个新的 script 类型。<script setup>,它将所有的顶层绑定暴露在模版中。

基本范例

<script setup>
  // imported components are also directly usable in template
  import Foo from './Foo.vue'
  import { ref } from 'vue'

  // write Composition API code just like in a normal setup()
  // but no need to manually return everything
  const count = ref(0)
  const inc = () => {
    count.value++
  }
</script>

<template>
  <Foo :count="count" @click="inc" />
</template>

编译输出:

import Foo from './Foo.vue'
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(1)
    const inc = () => {
      count.value++
    }

    return function render() {
      return h(Foo, {
        count,
        onClick: inc
      })
    }
  }
}

注意:SFC 编译器也从 <script setup> 中提取绑定元数据,并在模版编译过程中使用它。这就是为什么模版可以在这里使用 Foo 作为一个组件,尽管它是从 setup() 返回的,而不是通过组件选项注册。

声明 Props 和 Emits

<script setup>
  // expects props options
  const props = defineProps({
    foo: String
  })
  // expects emits options
  const emit = defineEmits(['update', 'delete'])
</script>

动机

该提案的主要目标是通过直接向模版暴露