16-Vue-elementUI

image

什么是elementUI

ElementUI是饿了么前端团队推出的一款基于Vue.js 2.0 的桌面端UI框架
大白话: 和Bootstrap一样对原生的HTML标签进行了封装, 让我们能够专注于业务逻辑而不是UI界面

elementUI的使用

官方文档

1. 安装 elementUI

npm i element-ui -S

2. 导入框架和css文件

在 main.js 中写入以下内容:

import Vue from 'vue'
import App from './App.vue'
// 导入elementUI和elementUI的CSS文件
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

// 告诉Vue, 我们需要在项目中使用elementUI
Vue.use(ElementUI)

new Vue({
  render: h => h(App)
}).$mount('#app')

3. 使用组件

在elementUI官方文档中找到需要的组件,将代码复制到需要的地方
例如:我复制了一段Button按钮和Switch的代码到App.vue组件中
App.vue

<template>
    <div id="app">
      <el-row>
        <el-button>默认按钮</el-button>
        <el-button type="primary">主要按钮</el-button>
        <el-button type="success">成功按钮</el-button>
        <el-button type="info">信息按钮</el-button>
        <el-button type="warning">警告按钮</el-button>
        <el-button type="danger">危险按钮</el-button>
      </el-row>
      <el-switch
        v-model="value"
        active-color="#13ce66"
        inactive-color="#ff4949">
      </el-switch>
    </div>
</template>

运行npm run serve指令后就可以在浏览器看到效果了

image

elementUI 优化

默认情况下无论我们有没有使用到某个组件, 在打包的时候都会将elementUI中所有的组件打包到我们的项目中
这样就导致了我们的项目体积比较大,用户访问比较慢

如何优化

为了解决这个问题,elementUI推出了按需导入,按需打包,也就是只会将我们用到的组件打包到了我们的项目中
没有用到的不会被打包
参考文档

1. 安装 babel-plugin-component

npm install babel-plugin-component -D

2. 修改babel.config.js配置文件

module.exports = {
  presets: [
    ['@vue/cli-plugin-babel/preset', { modules: false }]
  ],
  plugins: [
    [
      'component',
      {
        libraryName: 'element-ui',
        styleLibraryName: 'theme-chalk'
      }
    ]
  ]
}

3. 按需导入组件

比如我只用到了 Button 和 Switch,那么需要在 main.js 中写入以下内容:

import Vue from 'vue'
import App from './App.vue'
// 导入需要的组件
import { Button, Switch } from 'element-ui'

// 告诉Vue, 需要在项目中使用哪些组件
Vue.component(Button.name, Button)
Vue.component(Switch.name, Switch)
/* 或写为
 * Vue.use(Button)
 * Vue.use(Switch)
 */
 
new Vue({
  render: h => h(App)
}).$mount('#app')

运行npm run serve指令后依然可以在浏览器看到效果

image
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。