Preface
In developing projects using Vue, we usually choose Element-ui because this library is based on Vue and has many ready-made components for us to use. We can directly introduce it into main.js according to the official documentation, but the packaging volume will be too large after the final project development is completed. It is recommended to import it on demand, because there are some components that we will not use.
Import on demand
1. Install babel-plugin-component
the plug-in
yarn add babel-plugin-component -D
- -D: It is the abbreviation of -save, which automatically adds the module and version number to dependencies. (Production environment dependent)
- -S: Yes --save-dev automatically adds the module and version number to devdependencies. (development environment dependent)
2. babel.config.js configuration
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
3. Create element file
src
Create aelement
folder named under the directory, and createelement
a file under the folderindex.js
.
// src/element/index.js
import {
Button, Input, Card } from 'element-ui'
const element = {
install: function (Vue) {
Vue.use(Button)
Vue.use(Card)
}
}
Vue.prototype.$message = message;
export default element
4. main.js configuration
import 'element-ui/lib/theme-chalk/index.css'; // 引入 element 样式
import element from './element/index.js'
Vue.use(element)
5. Use element components
.vue
Usesrc/element/index.js
the imported component directly in the file we created
// src/view/login/index.vue
<template>
<Button />
</template>