①、安装插件 npm install unplugin-vue-define-options -D

②、在vue.config.js中配置插件

//vue.config.js 
configureWebpack: {
    plugins: [
      require('unplugin-vue-define-options/webpack')()
    ]
  }

③、需要ts类型的可在tsconfig中进行如下配置(未使用ts的忽略此步骤)

// tsconfig.json
{
  "compilerOptions": {
    // ...
    "types": ["unplugin-vue-define-options" /* ... */]
  }
}

④、直接在组件中使用

<template lang="">
  <div>
    test
  </div>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'AppPagination'
})
</script>
<style lang="">

</style>

⑤、在组件出口中进行组件自动全局注册

import { App } from 'vue'

const importFn = require.context('./', false, /\.vue$/)

export default {
  install (app:App) {
    // 根据keys批量注册
    importFn.keys().forEach(path => {
      // 导入组件
      const component = importFn(path).default

      // 进行注册
      app.component(component.name, component)
    })
  }
}

注意:此方法用起来不方便,如果仅仅想实现自动注册的话可以用下面的方法

在获取组件name上做了改进,以前是获取组件的name, 现在是获取该组件的名称,

import { App } from 'vue'
const ret = require.context('../', false, /\.vue$/)

export default {
  install (app: App) {
    // 根据keys批量注册
    ret.keys().forEach(path => {
      // 导入组件
      const component = ret(path).default
      // 获取组件名称
      const name = path.split('.')[1].slice(1)
      app.component(name, component)
    })
  }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐