element-plus你可以理解為是element-ui支持Vue 3的版本,element-plus是一套支持Vue 3.0的組件庫,提供的組件涵蓋了絕大部分頁面UI的需求。
在Vue 3的腳手架項目中,首先安裝element-plus的npm包,命令如下所示:
npm install element-plus -S
編輯main.js,引入整個element-plus組件和所需的樣式,由於element-plus組件內部默認使用英語,而我們項目需要使用中文,因此還需要引入中文的語言包。代碼如下所示:
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
import locale from 'element-plus/lib/locale/lang/zh-cn'
createApp(App).use(ElementPlus, { locale }).mount('#app')
如果想按需引入,比如我們項目中只用到了分頁組件,我們不想引入整個element-plus組件庫,則需要藉助babel-plugin-component插件,首先,在終端窗口中執行下面的命令安裝babel-plugin-component。
npm install babel-plugin-component -D
然後編輯項目目錄下的babel.config.js文件,添加如下內容:
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
"plugins": [
[
"component",
{
"libraryName": "element-plus",
"styleLibraryName": "theme-chalk"
}
]
]
}
粗體顯示的是新增的代碼。
接下來,在main.js文件中就可以按需引入分頁組件ElPagination了,代碼如下所示:
import { ElPagination } from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import lang from 'element-plus/lib/locale/lang/zh-cn'
import locale from 'element-plus/lib/locale'
// 使用中文語言
locale.use(lang)
createApp(App).use(ElPagination, { locale }).mount('#app')
element-plus組件庫的詳細用法,可以參看element-plus的官網。對於掌握了element-ui組件庫用法的童鞋,那麼恭喜你,你沒有任何的學習成本,甚至代碼都不需要修改就可以直接運行了。不過要注意的是,element-plus項目目前仍處於開發中,自然可能會出現各種Bug,在Vue 3項目中使用時要慎重。
我是專注於軟體開發和IT教育的孫鑫老師,喜歡我的文章歡迎關注、轉發、評論、點讚和收藏,我會經常與大家分享IT技術、程式語言的文章和教學視頻。目前已發布完整的《Vue.js從入門到實戰》教學視頻,正在發布《Java無難事》教學視頻。