vue自动加载方法(vue3的unplugin-auto-import自动引入)
vue3日常项目中定义变量需要引入ref,reactive等等比较麻烦 ,可以通过unplugin-auto-import给我们自动引入
1 、安装
npm i -D unplugin-auto-import
2 、在vite.config.ts中引入
import AutoImport from unplugin-auto-import/vite
并在plugins中配置:
export default defineConfig({
plugins: [
......
AutoImport({
imports: [vue],
dts: src/auto-import.d.ts,
})
]
})
AutoImport中可以有很多配置项 ,可以到github中看详细配置:
GitHub - antfu/unplugin-auto-import: Auto import APIs on-demand for Vite, Webpack and Rollup
注:dts是帮我们生成的类型声明文件 ,直接使用会找不到
上面配置完毕后会在src目录下生成一个auto-import.d.ts文件 ,里面帮我们自动引入vue相关内容 ,我们可以在项目中直接使用 。
注意:上面配置完毕dts后可能并不会自动生成auto-import.d.ts文件 ,可以重新运行一下项目 ,或者关闭编辑器重新打开运行即可 。
使用如下:
<script setup lang="ts"> // 这里我们不用引入ref直接使用 const msg = ref<string>(Hello Vue3) </script> <template> {{ msg }} </template> <style scoped lang="scss"></style>创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!