美文网首页
16-Vue-elementUI

16-Vue-elementUI

作者: 仰望_IT | 来源:发表于2020-05-06 15:52 被阅读0次
    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

    相关文章

      网友评论

          本文标题:16-Vue-elementUI

          本文链接:https://www.haomeiwen.com/subject/ynewghtx.html