Vue3 使用 element-plus

9,790 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

吃饱饭才有力气写代码~

今天接着摸鱼,想着用一用element-ui,结果百度了一大堆都没有直接解决我的问题,现在把这几个点总结一下,希望可以帮大家少走弯路!

最常见的回答如下(Vue3并不适用)

安装依赖包 npm i element-ui -S
导入 Element-UI 相关资源

// 导入组件库
import ElementUI from 'element-ui';
// 导入组件相关样式
import 'element-ui/lib/theme-chalk/index.css';
// 配置vue插件
Vue.use(ElementUI);

这种方式在旧版本中能用,但是如果版本是Vue3它就会报错:
Uncaught TypeError:Cannot read properties of undefined(reading 'prototype') at eval(types.js) at Object../node_modules/element-ui/lib/utils/types.js......

4d05223052297a9f52207174d9f69da.jpg

Vue3使用element-plus

版本升级原因

由于vue3.0在插件install函数的入参从Vue原型类 改成了app(vue实例)。导致element-ui中Vue.prototype.* 这样的代码已经全都失效了。所以element-ui已经不再兼容了。Vue3.0虽然兼容option api。但实际已经开始完全拥抱Composition API了。然后又发现elementui有个新版本,即element-plus,是为vue3项目特别更新的版本

样式路径也有修改

按照上述写法会报如下错误:
this dependency was not found:'element-plus/lib/theme-chalk/index.css

02b191467ddffa3829643d173496ed2.jpg
去element-plus官网查询,发现其已经将样式路径进行了修改:

element-plus/dist/index.css
//main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import ElementPlus from 'element-plus';//为vue3项目特别更新的版本
import 'element-plus/dist/index.css';

createApp(App).use(store).use(router).use(ElementPlus).mount('#app')

这样就能使用了,用法还和之前一样~