- Start Date: 2022-02-13
- Target Major Version: 3.x
- Reference Issues: vuejs/core#5218
- Implementation PR: vuejs/core#5738
Introduce a macro in script setup, defineOptions
, to use Options API in script setup
, specifically to be able to set name
, inheritAttrs
and render
in script setup
.
<script setup lang="ts">
import { useSlots } from 'vue'
defineOptions({
name: 'Foo',
inheritAttrs: false
})
// Setup code...
const slots = useSlots()
</script>
Compiled Output
const __default__ = {
name: 'Foo',
inheritAttrs: false
}
const setup = () => {
const slots = useSlots()
return { slots }
}
export default Object.assign(__default__, {
setup
})
<script setup lang="tsx">
defineOptions({
render() {
return <h1>Hello World</h1>
}
})
</script>
Compiled Output
With Babel plugin.
const __default__ = {
render() {
return h('h1', {}, () => 'Hello World')
}
}
const setup = () => {}
export default Object.assign(__default__, {
setup
})
This proposal is mainly to set the Options API using only script setup
.
We already have <script setup>
, but some options still need to be set in normal script tags (such as name
and inheritAttrs
). The goal of this proposal is to allow users to avoid script tag at all.
The behavior of defineOptions
is basically the same as defineProps
.
defineOptions
is compiler macros only usable inside<script setup>
. They do not need to be imported, and are compiled away when<script setup>
is processed.- The options passed to
defineOptions
will be hoisted out of setup into module scope. Therefore, the options cannot reference local variables declared in setup scope. Doing so will result in a compile error. However, it can reference imported bindings since they are in the module scope as well. - The options passed to
defineOptions
cannot containprops
,emits
andexpose
options.
This feature is opt-in. Existing SFC usage is unaffected.
I made a very prototype plugin unplugin-vue-define-options.
It supports Vite, Rollup, Webpack, Vue CLI and esbuild powered by unplugin.