在 <script setup>
中可使用 defineOptions
宏,以便在 <script setup>
中使用 Options API。
尤其是能够在一个函数中设置 name
、props
、emit
和 render
属性。
基本示例
<script setup lang="ts">
import { useSlots } from 'vue'
defineOptions({
name: 'Foo',
inheritAttrs: false,
})
const slots = useSlots()
</script>
输出代码
<script lang="ts">
export default {
name: 'Foo',
inheritAttrs: false,
props: {
msg: { type: String, default: 'bar' },
},
emits: ['change', 'update'],
}
</script>
<script setup>
const slots = useSlots()
</script>
在 <script setup>
使用 JSX
<script setup lang="tsx">
defineOptions({
render() {
return <h1>Hello World</h1>
},
})
</script>
输出代码
<script lang="tsx">
export default {
render() {
return <h1>Hello World</h1>
},
}
</script>
安装
npm i unplugin-vue-define-options -D
配置
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-define-options/webpack')({
include: [/\.vue$/, /\.vue\?vue/],
})
],
}
// vue.config.js
module.exports = {
configureWebpack: {
plugins: [
require('unplugin-vue-define-options/webpack')({
include: [/\.vue$/, /\.vue\?vue/],
})
],
},
}
TypeScript 支持
// tsconfig.json
{
"compilerOptions": {
// ...
"types": ["unplugin-vue-define-options/macros-global" /* ... */]
}
}
eslint支持
// .eslintrc.js
module.exports = {
globals: {
defineOptions: 'readonly'
},
}