vue setup 自定义组件名

147 阅读1分钟

<script setup> 中可使用 defineOptions 宏,以便在 <script setup> 中使用 Options API。 尤其是能够在一个函数中设置 namepropsemitrender 属性。

基本示例

<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
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    	require('unplugin-vue-define-options/webpack')({
        	include: [/\.vue$/, /\.vue\?vue/],
      	})
      ],
}
Vue CLI
// 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'
  },
}