首页 专题 文章 代码 归档

关于ElementUI按需引入组件无效的采坑

1. 前言

其实也不是什么采坑,只是没把别人的文章读完罢了!

2. 正文

这篇文章也来搜索使用步骤吧:

1、下载包

npm i element-ui -S
npm install babel-plugin-component -D

2、新建.babelrc配置文件

{
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

3、在src目录新建js文件:src/element/index.js

// 导入自己需要的组件
import {Notification, Loading, Message, Dialog} from 'element-ui'

const element = {
    install: function (Vue) {
        Vue.use(Loading.directive);
        Vue.prototype.$notify = Notification;
        Vue.prototype.$message = Message;
        Vue.use(Dialog);
    }
};
export default element

这里面就是填写要引入的具体的组件,问题就出现在这!

4、在main.js中引入这里的上面的第3步js

// css样式还是需要全部引入
import 'element-ui/lib/theme-chalk/index.css'
import element from './element/index';

Vue.use(element);
//导入主题
import "./assets/themes/theme_import.scss";

3. 解决

这里面就是填写要引入的具体的组件,问题就出现在上面的第3步!

很多新手以为就是按照文档所说:

使用Vue.component或者Vue.use就行?

截图-1585739255

错了,文档还没看完!

别人文档这里还有:

截图-1585739299

也即最后几个这里是特殊的:

Vue.use(Loading.directive);

Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;

也就是光引入还不行啊,还得将某些东西挂载到Vue原型上才能使用!!!

4. Element-plus

1、安装

yarn add element-plus -S
yarn add babel-plugin-import -D

2、babel.config.js

module.exports = {
  plugins: [
    [
      "import",
      {
        libraryName: 'element-plus',
        customStyleName: (name) => {
          // 由于 customStyleName 在配置中被声明的原因,`style: true` 会被直接忽略掉,
          // 如果你需要使用 scss 源文件,把文件结尾的扩展名从 `.css` 替换成 `.scss` 就可以了
          return `element-plus/lib/theme-chalk/${name}.css`;
        },
      },
    ],
  ],
};

3、src/plugins/elements.js

import {ElCol, ElInfiniteScroll, ElLoading, ElMessage, ElMessageBox, ElNotification, ElRow} from "element-plus";


const components = [
    ElRow, ElCol,
]
const plugins = [
    ElInfiniteScroll,
    ElLoading,
    ElMessage,
    ElMessageBox,
    ElNotification,
]
const installElement = (app) => {
    components.forEach((component) => {
        app.component(component.name, component)
    })

    plugins.forEach((plugin) => {
        app.use(plugin)
    })
}

export {
    installElement
}

4、main.js

import App from './App.vue'
import {installElement} from "./plugins/elements";


import 'element-plus/lib/theme-chalk/index.css';

const app = createApp(App)
installElement(app)
app.mount('#app')
此文阅读完毕,您可以:分享
二维码图片 扫描关注我们哟