joken-前端工程师

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

自动导入vite配置

  • 需要安装:
npm install -D unplugin-vue-components unplugin-auto-import
  • vite.config.ts配置
// vite.config.ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  // ...
  plugins: [
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
})

综合配置参考:

import { fileURLToPath, URL } from "node:url";
import Components from 'unplugin-vue-components/vite'
import AutoImport from "unplugin-auto-import/vite";

import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import VueDevTools from "vite-plugin-vue-devtools";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    AutoImport({
      // 自动导入 Vue 相关函数,如:ref, reactive, toRef 等
      imports: ["vue", "vue-router"],
      // 生成自动导入的TS声明文件
      dts: "types/auto-import.d.ts", //这个文件会自动生成
    }),
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
    VueDevTools(),
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

  • main.js 导入element plus
// main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')

项目可以直接使用element plus组件,不需要引入

<template>
  <div class="box">
    <div>demo:{{ myStore.my1 }}</div>
    <div>demo2:{{ myStore.my2 }}</div>
    <el-button type="primary" size="default" @click="setMy1()"
      >setMy1</el-button
    >
    <el-button type="primary" size="default" @click="setMy2()"
      >setMy2</el-button
    >
    <div>my1AndMy2:{{ my1AndMy2 }}</div>

    <el-button type="primary" size="default" @click="resetStore"
      >reset store</el-button
    >
  </div>
</template>
<script lang="ts" setup>
// import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { storeToRefs } from "pinia";

import useMyStore from "@/stores/my";
const myStore = useMyStore();

console.log(myStore, "myStore");

const { setMy1, setMy2 } = myStore;

//需要storeToRefs 转化,才能结构出ref特性的值,要不然直接结构会失去响应式ref特性
const { my1, my2, my1AndMy2 } = storeToRefs(myStore);

console.log(my1, "my1");
console.log(my2, "my2");

const resetStore = () => {
  // $reset可以实现重置store,但是需要options api写法,如果是组合式写法,需要main.js 写入对应的重置操作方式,详情见main.js
  myStore.$reset();
};
</script>
<style lang="stylus" scoped></style>

posted on 2024-07-08 00:07  joken1310  阅读(65)  评论(0编辑  收藏  举报