Element-UI 是一款基于 Vue.js 2.0 的桌面端组件库,广泛应用于后台管理系统的开发。以下是 Element-UI 的快速入门指南:
### 安装
可以通过 npm 或 yarn 安装 Element-UI:
```sh
npm install element-ui --save
# 或者
yarn add element-ui
```
### 引入 Element-UI
在 Vue 项目中引入 Element-UI。这里有两种方式:按需引入和全量引入。
#### 全量引入
在 `main.js` 中引入 Element-UI 及其样式:
```javascript
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
```
#### 按需引入
首先,安装 `babel-plugin-component`:
```sh
npm install babel-plugin-component -D
# 或者
yarn add babel-plugin-component -D
```
然后,配置 `.babelrc` 或 `babel.config.js` 文件:
```json
{
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
```
最后,在 `main.js` 中按需引入组件:
```javascript
import Vue from 'vue'
import { Button, Select } from 'element-ui'
Vue.component(Button.name, Button)
Vue.component(Select.name, Select)
```
### 使用组件
在 Vue 组件中使用 Element-UI 提供的组件。以 Button 和 Select 为例:
```vue
<template>
<div>
<el-button type="primary">主要按钮</el-button>
<el-select v-model="value" placeholder="请选择">
<el-option label="选项一" value="1"></el-option>
<el-option label="选项二" value="2"></el-option>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
value: ''
}
}
}
</script>
```
### 使用主题
Element-UI 提供了多种主题,并允许用户自定义主题。可以使用官方的主题生成工具 [Element Theme](https://element.eleme.io/#/zh-CN/theme)。
#### 修改样式变量
首先,安装主题生成工具:
```sh
npm install element-theme -g
npm install element-theme-chalk -D
```
生成默认的主题变量文件:
```sh
et --init
```
编辑生成的 `element-variables.scss` 文件,修改需要自定义的变量,然后生成主题:
```sh
et
```
在项目中引入自定义主题:
```javascript
import 'path/to/your/custom-theme/index.css'
```
### 示例项目
以下是一个完整的示例项目结构:
```
my-project
├── node_modules
├── public
│ └── index.html
├── src
│ ├── assets
│ ├── components
│ │ └── HelloWorld.vue
│ ├── App.vue
│ ├── main.js
│ └── router.js
├── .babelrc
├── package.json
└── README.md
```
`main.js` 文件内容:
```javascript
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
new Vue({
router,
render: h => h(App)
}).$mount('#app')
```
`App.vue` 文件内容:
```vue
<template>
<div id="app">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
```
`HelloWorld.vue` 文件内容:
```vue
<template>
<div class="hello">
<el-button type="primary">主要按钮</el-button>
<el-select v-model="value" placeholder="请选择">
<el-option label="选项一" value="1"></el-option>
<el-option label="选项二" value="2"></el-option>
</el-select>
</div>
</template>
<script>
export default {
data() {
return {
value: ''
}
}
}
</script>
<style scoped>
.hello {
text-align: center;
}
</style>
```
这样,你就可以快速搭建一个使用 Element-UI 的 Vue 项目。通过阅读 Element-UI 的官方文档,你还可以了解更多高级用法和自定义功能。