1、安装element-plus
npm install element-plus --save
2、完整引入
优点:使用方便
缺点:打包后文件会比按需要导入的大
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
createApp(App).use(ElementPlus).use(store).use(router).mount('#app')
使用,在HomeView.vue添加测试代码:
<template>
<div class="home">
<el-row class="mb-4">
<el-button>Default</el-button>
<el-button type="primary">Primary</el-button>
<el-button type="success">Success</el-button>
<el-button type="info">Info</el-button>
<el-button type="warning">Warning</el-button>
<el-button type="danger">Danger</el-button>
<el-button>中文</el-button>
</el-row>
<el-switch v-model="value1" />
<el-switch v-model="value2" class="ml-2" style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'HomeView',
setup() {
const value1 = ref(true)
const value2 = ref(true)
return {
value1, value2
}
}
}
</script>
3、按需自动引入
优点:用到的组件才引入,打包后文件会比按完整导入的小。
缺点:需要额外安装两个自动导入的插件。
按需自动导入要安装unplugin-vue-components 和 unplugin-auto-import这两款插件。
npm install -D unplugin-vue-components unplugin-auto-import
修改vue.config.js配置文件
const { defineConfig } = require('@vue/cli-service')
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: {
plugins: [
AutoImport({
resolvers: [ElementPlusResolver()]
}),
Components({
resolvers: [ElementPlusResolver()]
})
]
}
})
把上面在main.js中所添加的全局导入代码删除掉。然后再运行项目,此时会发现效果出来了: