• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue3+vite+ts自动引入api和组件

武飞扬头像
Gavin7835
帮助1

安装

pnpm install unplugin-auto-import unplugin-vue-components -d

配置

vite.config.ts文件中加入下方代码

  1.  
    // 自动导入composition api 和 生成全局typescript说明
  2.  
    import AutoImport from 'unplugin-auto-import/vite'
  3.  
    import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
  4.  
    // 自动按需导入组件和注册组件
  5.  
    import Components from 'unplugin-vue-components/vite'
  6.  
    export default defineConfig({
  7.  
    plugins: [
  8.  
    vue(),
  9.  
    AutoImport({
  10.  
    imports: [
  11.  
    'vue',
  12.  
    'vue-router',
  13.  
    'pinia',
  14.  
    {
  15.  
    axios: [
  16.  
    ['default', 'axios']
  17.  
    ]
  18.  
    }
  19.  
    ],
  20.  
    // 解析器,例如element-plus的ElementPlusResolver
  21.  
    resolvers: [ElementPlusResolver()],
  22.  
    eslintrc: {
  23.  
    enabled: true,
  24.  
    filepath: './.eslintrc-auto-import.json',
  25.  
    globalsPropValue: true,
  26.  
    },
  27.  
    dts: true
  28.  
    }),
  29.  
    Components({
  30.  
    resolvers: [ElementPlusResolver()] // ElementPlus按需加载
  31.  
    })
  32.  
    ],
  33.  
    })
学新通

使用方式

  1.  
    <template>
  2.  
    <div>{{a}}</div>
  3.  
    <button @click="change">change</button>
  4.  
    <el-button type="primary">ssss</el-button>
  5.  
    </template>
  6.  
     
  7.  
    <script setup lang="ts">
  8.  
    // import { ref } from 'vue' 不需要再引入了
  9.  
    let a = ref('dddd')
  10.  
    console.log(a)
  11.  
    function change(){
  12.  
    a.value = "wuhu~"
  13.  
    }
  14.  
    </script>

效果学新通

 一个小坑

按照上述的配置,在ts项目中使用会有报错

学新通

 只需要在 tsconfig.json 引入 auto-imports.d.ts 类型声明文件

学新通

 完成后

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggheff
系列文章
更多 icon
同类精品
更多 icon
继续加载