vue3中ref,reactive等api和自定义组件等每个页面都要引入很麻烦,偷懒是人的天性,故引入自动导入插件,以此记录:
1.vue3的api自动导入
使用前:
<script setup lang="ts"> import { ref, onMounted } from 'vue' const imgUrl = ref("") const canvas = ref() onMounted(() => { ctx = canvas.value.getContext("2d") as CanvasRenderingContext2D } </script>
使用后:
<script setup lang="ts"> const imgUrl = ref("") const canvas = ref() onMounted(() => { ctx = canvas.value.getContext("2d") as CanvasRenderingContext2D } </script>
使用:
安装:
npm i -D unplugin-auto-import
vite.config 配置:
import AutoImport from 'unplugin-auto-import/vite' plugins: [ vue(), AutoImport({ imports: ['vue', 'vue-router'], dts: "src/auto-import.d.ts", eslintrc: { enabled: true } }) ],
2.自定义组件的导入
使用前:
<template> <div> <div @click="showArea">选择省市区(只返回最末级地址,若全选返回第一级):{{ chosedData.name }}</div> <RegionChose :dialogVisible="dialogVisible" :defaultItem="defaultItem" @regionBack="regionBack"></RegionChose> </div> </template> <!-- 组件、api的自动导入 --> <script setup lang="ts"> import RegionChose from '/@/components/RegionChose.vue' </script>
使用后:
<template> <div> <div @click="showArea">选择省市区(只返回最末级地址,若全选返回第一级):{{ chosedData.name }}</div> <RegionChose :dialogVisible="dialogVisible" :defaultItem="defaultItem" @regionBack="regionBack"></RegionChose> </div> </template> <!-- 组件、api的自动导入 --> <script setup lang="ts"> </script>
安装:
npm i -D unplugin-vue-components
// vite.config.js配置
import Components from 'unplugin-vue-components/vite' // 按需加载自定义组件 import { ElementPlusResolver, AntDesignVueResolver} from 'unplugin-vue-components/resolvers' plugins: [ Components({ dts: true, dirs: ['src/components'], // 需自动导入自定义组件文件夹 resolvers: [ ElementPlusResolver(), // ElementPlus按需加载 ] }) ],
elementplus按需导入以后,main.js不再导入ui框架,由于elementplus 自动导入以后,开发时页面切换很慢,故不再按需自动导入
代码地址:https://gitee.com/yuexiayunsheng/vue3learn/blob/master/src/views/AutoImport.vue
标签:vue,导入,unplugin,api,components,vue3,import,ref From: https://www.cnblogs.com/foxing/p/17657694.html