1、安装element-plus

  1. npm install element-plus --save

2、完整引入

优点:使用方便
缺点:打包后文件会比按需要导入的大

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import './registerServiceWorker'
  4. import router from './router'
  5. import store from './store'
  6. import ElementPlus from 'element-plus'
  7. import 'element-plus/dist/index.css'
  8. createApp(App).use(ElementPlus).use(store).use(router).mount('#app')

使用,在HomeView.vue添加测试代码:

  1. <template>
  2. <div class="home">
  3. <el-row class="mb-4">
  4. <el-button>Default</el-button>
  5. <el-button type="primary">Primary</el-button>
  6. <el-button type="success">Success</el-button>
  7. <el-button type="info">Info</el-button>
  8. <el-button type="warning">Warning</el-button>
  9. <el-button type="danger">Danger</el-button>
  10. <el-button>中文</el-button>
  11. </el-row>
  12. <el-switch v-model="value1" />
  13. <el-switch v-model="value2" class="ml-2" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
  14. </div>
  15. </template>
  16. <script>
  17. import { ref } from 'vue'
  18. export default {
  19. name: 'HomeView',
  20. setup() {
  21. const value1 = ref(true)
  22. const value2 = ref(true)
  23. return {
  24. value1, value2
  25. }
  26. }
  27. }
  28. </script>

效果:
image.png

3、按需自动引入

优点:用到的组件才引入,打包后文件会比按完整导入的小。
缺点:需要额外安装两个自动导入的插件。
按需自动导入要安装unplugin-vue-components 和 unplugin-auto-import这两款插件。

  1. npm install -D unplugin-vue-components unplugin-auto-import

修改vue.config.js配置文件

  1. const { defineConfig } = require('@vue/cli-service')
  2. const AutoImport = require('unplugin-auto-import/webpack')
  3. const Components = require('unplugin-vue-components/webpack')
  4. const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
  5. module.exports = defineConfig({
  6. transpileDependencies: true,
  7. configureWebpack: {
  8. plugins: [
  9. AutoImport({
  10. resolvers: [ElementPlusResolver()]
  11. }),
  12. Components({
  13. resolvers: [ElementPlusResolver()]
  14. })
  15. ]
  16. }
  17. })

把上面在main.js中所添加的全局导入代码删除掉。然后再运行项目,此时会发现效果出来了:
image.png