vue2中api我们可以直接使用,到了vue3如果想使用ref、computed、watch...,就需要手动进行import导入了,如何才能不需导入就可以直接使用呢?方法还是有的,我们可以通过unplugin-auto-import实现自动导入,无需import即可在文件里使用Vue的API。
安装
npm i unplugin-auto-import -D
配置
// vite.config.ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({
// dts: 'src/auto-imports.d.ts', // 可以自定义文件生成的位置,默认是根目录下
imports: ['vue']
})
]
})
安装配置完会自动生成auto-imports.d.ts文件。
// auto-imports.d.ts
// Generated by 'unplugin-auto-import'
// We suggest you to commit this file into source control
declare global {
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const effectScope: typeof import('vue')['effectScope']
const EffectScope: typeof import('vue')['EffectScope']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const inject: typeof import('vue')['inject']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
// ...
}
export {}
如果不手动导入,eslit就会报错,可以通过在eslintrc.js安装插件vue-global-api解决。
// 安装依赖
npm i vue-global-api -D
// eslintrc.js
module.exports = {
extends: [
'vue-global-api'
]
}
使用
<script lang="ts" setup name="OrderList">
// 不用import,直接使用ref
const count = ref(0)
onMounted(() => {
console.log('mounted===')
})
</script>