Vue中Element一般使用、Vue-cli和手工搭建环境中按需使用Element

一、element一般使用:

1、在使用Vue-cli搭建好项目后安装:

cnpm i element-ui -S

2、在 main.js 中引入并注册:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  el: '#app',
  render: h => h(App)
});

3、使用:

在单文件组件中直接从官网中的组件中复制代码即可(无需先引用对应的组件)。

二、Vue-Cli中按需使用:

1、项目目录执行

npm install babel-plugin-component –D

2、修改.babelrc

这是Vue脚手架项目按需引入elementui核心的地方,因为大部分新手不会babel配置。

如果直接复制粘贴官网提供的配置文件肯定会报错,因为你把脚手架默认的配置给覆盖掉了,正确的做法是做整合,babelrc应该修改为:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        }
      }
    ],
    [
      "es2015",
      {
        "modules": false
      }
    ],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime",
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        "env",
        "stage-2"
      ]
    }
  }
}

3、按需引入组件

比如要按需引入button,则为

import Vue from 'vue' 
import App from './App' 
import router from './router'
import 'element-ui/lib/theme-chalk/index.css' 
import { Button } from 'element-ui'

Vue.use(Button)

完整代码:

 main.js:

import Vue from 'vue'
import App from './App'
import router from './router/index'
import {
    Pagination,
    Dialog,
    Autocomplete,
    Dropdown,
    DropdownMenu,
    DropdownItem,
    Menu,
    Submenu,
    MenuItem,
    MenuItemGroup,
    Input,
    InputNumber,
    Radio,
    RadioGroup,
    RadioButton,
    Checkbox,
    CheckboxButton,
    CheckboxGroup,
    Switch,
    Select,
    Option,
    OptionGroup,
    Button,
    ButtonGroup,
    Table,
    TableColumn,
    Popover,
    Tooltip,
    Form,
    FormItem,
    Tag,
    Alert,
    Slider,
    Icon,
    Row,
    Col,
    Progress,
    Card,
    Container,
    Header,
    Aside,
    Main,
    Footer,
    Link,
    Divider,
    Image,
    PageHeader,
    Loading,
    MessageBox,
    Message,
    Notification
} from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(Pagination);
Vue.use(Dialog);
Vue.use(Autocomplete);
Vue.use(Dropdown);
Vue.use(DropdownMenu);
Vue.use(DropdownItem);
Vue.use(Menu);
Vue.use(Submenu);
Vue.use(MenuItem);
Vue.use(MenuItemGroup);
Vue.use(Input);
Vue.use(InputNumber);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(RadioButton);
Vue.use(Checkbox);
Vue.use(CheckboxButton);
Vue.use(CheckboxGroup);
Vue.use(Switch);
Vue.use(Select);
Vue.use(Option);
Vue.use(OptionGroup);
Vue.use(Button);
Vue.use(ButtonGroup);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Popover);
Vue.use(Tooltip);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Tag);
Vue.use(Alert);
Vue.use(Slider);
Vue.use(Icon);
Vue.use(Row);
Vue.use(Col);
Vue.use(Progress);
Vue.use(Card);
Vue.use(Container);
Vue.use(Header);
Vue.use(Aside);
Vue.use(Main);
Vue.use(Footer);
Vue.use(Link);
Vue.use(Divider);
Vue.use(Image);
Vue.use(PageHeader);

// Vue.use(echarts)

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;

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

Test.vue:

<template>
  <div>
    <el-button type='primary'>按钮测试</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: "This is test page!",
    };
  }
};
</script>

 .babelrc:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        }
      }
    ],
    [
      "es2015",
      {
        "modules": false
      }
    ],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime",
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        "env",
        "stage-2"
      ]
    }
  }
}

package.json:

{
  "name": "webpack4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --config ./config/webpack.prod.config.js",
    "dev": "webpack-dev-server --open chrome --port 8080 --config ./config/webpack.dev.config.js",
    "start": "webpack-dev-server --open chrome --port 8080 --config ./config/webpack.dev.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.11.6",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.11.5",
    "autoprefixer": "^9.8.6",
    "babel-loader": "^8.1.0",
    "babel-plugin-component": "^1.1.1",
    "babel-preset-es2015": "^6.0.2",
    "clean-webpack-plugin": "^4.0.0",
    "core-js": "^3.13.0",
    "css-loader": "^4.3.0",
    "eslint": "^7.2.0",
    "eslint-loader": "^4.0.2",
    "file-loader": "^6.2.0",
    "html-loader": "^1.1.0",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.12.2",
    "less-loader": "^7.0.1",
    "mini-css-extract-plugin": "^1.6.0",
    "optimize-css-assets-webpack-plugin": "^6.0.0",
    "postcss-flexbugs-fixes": "^4.2.1",
    "postcss-loader": "^3.0.0",
    "postcss-normalize": "^8.0.1",
    "postcss-preset-env": "^6.7.0",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "vue-loader": "^15.9.8",
    "vue-template-compiler": "^2.6.14",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.11.2",
    "webpack-merge": "^5.8.0"
  },
  "dependencies": {
    "axios": "^0.23.0",
    "echarts": "^4.9.0",
    "element-ui": "^2.15.6",
    "vue": "^2.6.14",
    "vue-router": "^3.0.1",
    "vuex": "^3.6.2"
  }
}

 4、错误处理

1)如果报错:Module build failed: Error: Couldn't find preset "es2015" relative to directory

则执行

npm install babel-preset-es2015 --save-dev

2) 如果是纯手工搭建的Vue环境,则可能报错:Error: Plugin/Preset files are not allowed to export objects, only functions. In D:\work\vue\webpack4\node_modules\_babel-preset-es2015@6.24.1@babel-preset-es2015\lib\index.js

则.babelrc配置文件中“env”改成“@babel/preset-env”

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "modules": false
            }
        ]
    ],
    "plugins": [
        [
            "component",
            {
                "libraryName": "element-ui",
                "styleLibraryName": "theme-chalk"
            }
        ]
    ]
}

 源码:https://gitee.com/duansamve/webpack4-vue.git

 2)报错:These dependencies were not found:deepmerge,resize-observer-polyfill ,throttle-debounce/debounce

则执行

npm install --save deepmerge resize-observer-polyfill throttle-debounce/debounce

三、单独JS文件中按需使用:

import { Message } from 'element-ui'
import axios from 'axios'
import { Message } from 'element-ui'

let HTTP = axios.create({
  baseURL: '/',
  timeout: 10000,
  responseType: 'json',
  // header:{  //自定义请求头
  'custom-header': 'xiao', 
  //   'content-type':'application/x-www-form-urlencoded'  //设置这个,那么经过transformRequest处理之后的数据格式就变为了  miaov=ketang&username=leo,只支持POST请求方式
  // },
  params: {
    //TOKEN: localStorage['TOKEN']
  },
  transformResponse: [function (data) {
    return JSON.parse(data);  //需要return出来
  }]
});

//添加一个请求拦截器:请求之前的拦截
HTTP.interceptors.request.use(function (config) {
  config.headers.TOKEN = localStorage['TOKEN'];
  return config;
}, function (error) {
  return Promise.reject(error);
});

//添加一个请求拦截器:请求之后的拦截
HTTP.interceptors.response.use(res => {
  return res.data;
}, error => {
  Message.error({
    title: "错误",
    message: error.message,
  });
})

export default HTTP;

四、将element按需使用抽离成单独一个文件:

/ src / util / element.js :

import Vue from "vue";
// import ElementUI from 'element-ui'
// import "element-ui/lib/theme-chalk/index.css";
import {
  Button,
  ButtonGroup,
  Container,
  Header,
  Aside,
  Main,
  Menu,
  Submenu,
  MenuItem,
  MenuItemGroup,
  Row,
  Col,
  Radio,
  RadioGroup,
  RadioButton,
  Card,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  Tree,
  Table,
  TableColumn,
  Input,
  Tag,
  Switch,
  Form,
  FormItem,
  Select,
  Option,
  Divider,
  DatePicker,
  Tabs,
  TabPane,
  Popover,
  Alert,
  Empty,
  Dialog,
  Upload,
  Transfer,
  MessageBox,
  Message,
  Steps,
  Step,
  Checkbox,
  CheckboxGroup,
  Descriptions
} from "element-ui";

Vue.use(Button);
Vue.use(Container);
Vue.use(Header);
Vue.use(Aside);
Vue.use(Main);
Vue.use(Menu);
Vue.use(Submenu);
Vue.use(MenuItem);
Vue.use(MenuItemGroup);
Vue.use(Row);
Vue.use(Col);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(RadioButton);
Vue.use(Card);
Vue.use(Dropdown);
Vue.use(DropdownItem);
Vue.use(DropdownMenu);
Vue.use(Tree);
Vue.use(Table);
Vue.use(TableColumn);
Vue.use(Input);
Vue.use(ButtonGroup);
Vue.use(Tag);
Vue.use(Switch);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Select);
Vue.use(Option);
Vue.use(Divider);
Vue.use(DatePicker);
Vue.use(Tabs);
Vue.use(TabPane);
Vue.use(Popover);
Vue.use(Alert);
Vue.use(Empty);
Vue.use(Dialog);
Vue.use(Upload);
Vue.use(Transfer);
Vue.use(Steps);
Vue.use(Step);
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
Vue.use(Descriptions);

Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$message = Message;

/ src / main.js :

// import ElementUI from 'element-ui';
// import 'element-ui/lib/theme-chalk/index.css';
import "./util/element.js";

// Vue.use(ElementUI);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值