element-plus按需引入后ElMessage与ElLoading在页面中如何使用

一、按照官网按需引用element-plus

  1. pnpm install element-plus
  2. pnpm add -D unplugin-vue-components unplugin-auto-import
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

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

二、ElMessage与ElLoading使用问题

<script setup lang="ts">
  const testMessage = () => {
    ElMessage.success('1211')
  }
</script>

<template>
  <div>
    <el-button type="primary" @click="testMessage">Primary</el-button>
  </div>
</template>

此时ElMessage与ElLoading也是可用,当时vscode有会报错提示-----------》找不到名称“ElMessage”。ts(2304),我在tsconfig.json添加了配置依旧报错

三、解决找不到名称“ElMessage”报错

1.手动引入ElMessage

<script setup lang="ts">
  // 手动引入
  import { ElMessage } from 'element-plus'

  const testMessage = () => {
    ElMessage.success('1211')
  }
</script>

<template>
  <div class="bg-light-900 flex justify-center">
    <el-button type="primary" @click="testMessage">Primary</el-button>
    <Test />
  </div>
</template>

2.在main.ts中引入对应样式

// 引入Elmessage和Elloading的css样式文件
import 'element-plus/theme-chalk/el-loading.css'
import 'element-plus/theme-chalk/el-message.css'

3.ElLoading同理

四、虽然在main.ts中引入可以解决,但背离了我们自动导入的初衷,所以推荐下面这种方式

  1. pnpm add vite-plugin-style-import consola -D
// vite.config.ts
import {
  createStyleImportPlugin,
  ElementPlusResolve,
} from 'vite-plugin-style-import'

export default {
  plugins: [
    // ...
    createStyleImportPlugin({
      resolves: [ElementPlusResolve()],
      libs: [
        {
          libraryName: 'element-plus',
          esModule: true,
          resolveStyle: (name: string) => {
            return `element-plus/theme-chalk/${name}.css`
          },
        },
      ]
    }),
  ],
}

这样配置后 我们就不用在mian.js中手动导入ElMessage与ElLoading的样式了

你可能感兴趣的:(vue,elementui,vue.js)