This commit is contained in:
Ivan
2021-06-07 11:56:04 +08:00
commit c3c9fee2fb
1071 changed files with 195655 additions and 0 deletions

View File

@@ -0,0 +1,242 @@
## Alert
Displays important alert messages.
### Basic usage
Alert components are non-overlay elements in the page that does not disappear automatically.
:::demo Alert provides 4 types of themes defined by `type`, whose default value is `info`.
```html
<template>
<el-alert
title="success alert"
type="success">
</el-alert>
<el-alert
title="info alert"
type="info">
</el-alert>
<el-alert
title="warning alert"
type="warning">
</el-alert>
<el-alert
title="error alert"
type="error">
</el-alert>
</template>
```
:::
### Theme
Alert provide two different themes, `light` and `dark`.
:::demo Set `effect` to change theme, default is `light`.
```html
<template>
<el-alert
title="success alert"
type="success"
effect="dark">
</el-alert>
<el-alert
title="info alert"
type="info"
effect="dark">
</el-alert>
<el-alert
title="warning alert"
type="warning"
effect="dark">
</el-alert>
<el-alert
title="error alert"
type="error"
effect="dark">
</el-alert>
</template>
```
:::
### Customizable close button
Customize the close button as texts or other symbols.
:::demo Alert allows you to configure if it's closable. The close button text and closing callbacks are also customizable. `closable` attribute decides if the component can be closed or not. It accepts `boolean`, and the default is `true`. You can set `close-text` attribute to replace the default cross symbol as the close button. Be careful that `close-text` must be a string. `close` event fires when the component is closed.
```html
<template>
<el-alert
title="unclosable alert"
type="success"
:closable="false">
</el-alert>
<el-alert
title="customized close-text"
type="info"
close-text="Gotcha">
</el-alert>
<el-alert
title="alert with callback"
type="warning"
@close="hello">
</el-alert>
</template>
<script>
export default {
methods: {
hello() {
alert('Hello World!');
}
}
}
</script>
```
:::
### With icon
Displaying an icon improves readability.
:::demo Setting the `show-icon` attribute displays an icon that corresponds with the current Alert type.
```html
<template>
<el-alert
title="success alert"
type="success"
show-icon>
</el-alert>
<el-alert
title="info alert"
type="info"
show-icon>
</el-alert>
<el-alert
title="warning alert"
type="warning"
show-icon>
</el-alert>
<el-alert
title="error alert"
type="error"
show-icon>
</el-alert>
</template>
```
:::
## Centered text
Use the `center` attribute to center the text.
:::demo
```html
<template>
<el-alert
title="success alert"
type="success"
center
show-icon>
</el-alert>
<el-alert
title="info alert"
type="info"
center
show-icon>
</el-alert>
<el-alert
title="warning alert"
type="warning"
center
show-icon>
</el-alert>
<el-alert
title="error alert"
type="error"
center
show-icon>
</el-alert>
</template>
```
:::
### With description
Description includes a message with more detailed information.
:::demo Besides the required `title` attribute, you can add a `description` attribute to help you describe the alert with more details. Description can only store text string, and it will word wrap automatically.
```html
<template>
<el-alert
title="with description"
type="success"
description="This is a description.">
</el-alert>
</template>
```
:::
### With icon and description
:::demo At last, this is an example with both icon and description.
```html
<template>
<el-alert
title="success alert"
type="success"
description="more text description"
show-icon>
</el-alert>
<el-alert
title="info alert"
type="info"
description="more text description"
show-icon>
</el-alert>
<el-alert
title="warning alert"
type="warning"
description="more text description"
show-icon>
</el-alert>
<el-alert
title="error alert"
type="error"
description="more text description"
show-icon>
</el-alert>
</template>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| title | title | string | — | — |
| type | Component type | string | success/warning/info/error | info |
| description | Descriptive text. Can also be passed with the default slot | string | — | — |
| closable | If closable or not | boolean | — | true |
| center | Whether to center the text | boolean | — | false |
| close-text | Customized close button text | string | — | — |
| show-icon | If a type icon is displayed | boolean | — | false |
| effect | Choose theme | string | light/dark | light |
### Slot
| Name | Description |
|------|--------|
| — | description |
| title | content of the Alert title |
### Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| close | fires when alert is closed | — |

View File

@@ -0,0 +1,145 @@
## Avatar avatar
Avatars can be used to represent people or objects. It supports images, Icons, or characters.
### Basic
use `shape` and `size` prop to set avatar's shape and size
:::demo
```html
<template>
<el-row class="demo-avatar demo-basic">
<el-col :span="12">
<div class="sub-title">circle</div>
<div class="demo-basic--circle">
<div class="block"><el-avatar :size="50" :src="circleUrl"></el-avatar></div>
<div class="block" v-for="size in sizeList" :key="size">
<el-avatar :size="size" :src="circleUrl"></el-avatar>
</div>
</div>
</el-col>
<el-col :span="12">
<div class="sub-title">square</div>
<div class="demo-basic--circle">
<div class="block"><el-avatar shape="square" :size="50" :src="squareUrl"></el-avatar></div>
<div class="block" v-for="size in sizeList" :key="size">
<el-avatar shape="square" :size="size" :src="squareUrl"></el-avatar>
</div>
</div>
</el-col>
</el-row>
</template>
<script>
export default {
data () {
return {
circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
sizeList: ["large", "medium", "small"]
}
}
}
</script>
```
:::
### Types
It supports images, Icons, or characters
:::demo
```html
<template>
<div class="demo-type">
<div>
<el-avatar icon="el-icon-user-solid"></el-avatar>
</div>
<div>
<el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
</div>
<div>
<el-avatar> user </el-avatar>
</div>
</div>
</template>
```
:::
### Fallback when image load error
fallback when image load error
:::demo
```html
<template>
<div class="demo-type">
<el-avatar :size="60" src="https://empty" @error="errorHandler">
<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
</el-avatar>
</div>
</template>
<script>
export default {
methods: {
errorHandler() {
return true
}
}
}
</script>
```
:::
### How the image fit its container
Set how the image fit its container for an image avatar, same as [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit).
:::demo
```html
<template>
<div class="demo-fit">
<div class="block" v-for="fit in fits" :key="fit">
<span class="title">{{ fit }}</span>
<el-avatar shape="square" :size="100" :fit="fit" :src="url"></el-avatar>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
| ----------------- | -------------------------------- | --------------- | ------ | ------ |
| icon | set representation type to Icon, more info on Icon Component | string | | |
| size | set avatar size | number/string | number / large / medium / small | large |
| shape | set avatar shape | string | circle / square | circle |
| src | the address of the image for an image avatar | string | | |
| srcSet | A list of one or more strings separated by commas indicating a set of possible image sources for the user agent to use | string | | |
| alt | This attribute defines an alternative text description of the image | string | | |
| fit | set how the image fit its container for an image avatar | string | fill / contain / cover / none / scale-down | cover |
### Events
| Event Name | Description | Parameters |
| ------ | ------------------ | -------- |
| error | handler when img load error, return false to prevent default fallback behavior |(e: Event) |
### Slot
| Slot Name | Description |
| default | customize avatar content |

View File

@@ -0,0 +1,60 @@
## Backtop
A button to back to top
### Basic usage
Scroll down to see the bottom-right button.
:::demo
```html
<template>
Scroll down to see the bottom-right button.
<el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop>
</template>
```
:::
### Customizations
Display area is 40px \* 40px.
:::demo
```html
<template>
Scroll down to see the bottom-right button.
<el-backtop target=".page-component__scroll .el-scrollbar__wrap" :bottom="100">
<div
style="{
height: 100%;
width: 100%;
background-color: #f2f5f6;
box-shadow: 0 0 6px rgba(0,0,0, .12);
text-align: center;
line-height: 40px;
color: #1989fa;
}"
>
UP
</div>
</el-backtop>
</template>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
| ----------------- | ------------------------------------------------------------------- | --------------- | --------------- | ------- |
| target | the target to trigger scroll | string | | |
| visibility-height | the button will not show until the scroll height reaches this value | number | | 200 |
| right | right distance | number | | 40 |
| bottom | bottom distance | number | | 40 |
### Events
| Event Name | Description | Parameters |
| ---------- | ------------------- | ----------- |
| click | triggers when click | click event |

View File

@@ -0,0 +1,124 @@
## Badge
A number or status mark on buttons and icons.
### Basic usage
Displays the amount of new messages.
:::demo The amount is defined with `value` which accepts `Number` or `String`.
```html
<el-badge :value="12" class="item">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge :value="3" class="item">
<el-button size="small">replies</el-button>
</el-badge>
<el-badge :value="1" class="item" type="primary">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge :value="2" class="item" type="warning">
<el-button size="small">replies</el-button>
</el-badge>
<el-dropdown trigger="click">
<span class="el-dropdown-link">
Click Me<i class="el-icon-caret-bottom el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item class="clearfix">
comments
<el-badge class="mark" :value="12" />
</el-dropdown-item>
<el-dropdown-item class="clearfix">
replies
<el-badge class="mark" :value="3" />
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Max value
You can customize the max value.
:::demo The max value is defined by property `max` which is a `Number`. Note that it only works when `value` is also a `Number`.
```html
<el-badge :value="200" :max="99" class="item">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge :value="100" :max="10" class="item">
<el-button size="small">replies</el-button>
</el-badge>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Customizations
Displays text content other than numbers.
:::demo When `value` is a `String`, it can display customized text.
```html
<el-badge value="new" class="item">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge value="hot" class="item">
<el-button size="small">replies</el-button>
</el-badge>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Little red dot
Use a red dot to mark content that needs to be noticed.
:::demo Use the attribute `is-dot`. It is a `Boolean`.
```html
<el-badge is-dot class="item">query</el-badge>
<el-badge is-dot class="item">
<el-button class="share-button" icon="el-icon-share" type="primary"></el-button>
</el-badge>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|------------- |---------------- |---------------- |---------------------- |-------- |
| value | display value | string, number | — | — |
| max | maximum value, shows '{max}+' when exceeded. Only works if `value` is a `Number` | number | — | — |
| is-dot | if a little dot is displayed | boolean | — | false |
| hidden | hidden badge | boolean | — | false |
| type | button type | string | primary / success / warning / danger / info | — |

View File

@@ -0,0 +1,135 @@
<script>
import bus from '../../bus';
import { ACTION_USER_CONFIG_UPDATE } from '../../components/theme/constant.js';
const varMap = {
'$--box-shadow-light': 'boxShadowLight',
'$--box-shadow-base': 'boxShadowBase',
'$--border-radius-base': 'borderRadiusBase',
'$--border-radius-small': 'borderRadiusSmall'
};
const original = {
boxShadowLight: '0 2px 12px 0 rgba(0, 0, 0, 0.1)',
boxShadowBase: '0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)',
borderRadiusBase: '4px',
borderRadiusSmall: '2px'
}
export default {
created() {
bus.$on(ACTION_USER_CONFIG_UPDATE, this.setGlobal);
},
mounted() {
this.setGlobal();
},
methods: {
setGlobal() {
if (window.userThemeConfig) {
this.global = window.userThemeConfig.global;
}
}
},
data() {
return {
global: {},
boxShadowLight: '',
boxShadowBase: '',
borderRadiusBase: '',
borderRadiusSmall: ''
}
},
watch: {
global: {
immediate: true,
handler(value) {
Object.keys(varMap).forEach((c) => {
if (value[c]) {
this[varMap[c]] = value[c]
} else {
this[varMap[c]] = original[varMap[c]]
}
});
}
}
}
}
</script>
## Border
We standardize the borders that can be used in buttons, cards, pop-ups and other components.
### Border
There are few border styles to choose.
<table class="demo-border">
<tbody>
<tr>
<td class="text">Name</td>
<td class="text">Thickness</td>
<td class="line">Demo</td>
</tr>
<tr>
<td class="text">Solid</td>
<td class="text">1px</td>
<td class="line">
<div></div>
</td>
</tr>
<tr>
<td class="text">Dashed</td>
<td class="text">2px</td>
<td class="line">
<div class="dashed"></div>
</td>
</tr>
</tbody>
</table>
### Radius
There are few radius styles to choose.
<el-row :gutter="12" class="demo-radius">
<el-col :span="6" :xs="{span: 12}">
<div class="title">No Radius</div>
<div class="value">border-radius: 0px</div>
<div class="radius"></div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="title">Small Radius</div>
<div class="value">border-radius: {{borderRadiusSmall}}</div>
<div
class="radius"
:style="{ borderRadius: borderRadiusSmall }"
></div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="title">Large Radius</div>
<div class="value">border-radius: {{borderRadiusBase}}</div>
<div
class="radius"
:style="{ borderRadius: borderRadiusBase }"
></div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="title">Round Radius</div>
<div class="value">border-radius: 30px</div>
<div class="radius radius-30"></div>
</el-col>
</el-row>
### Shadow
There are few shadow styles to choose.
<div
class="demo-shadow"
:style="{ boxShadow: boxShadowBase }"
></div>
<span class="demo-shadow-text">Basic Shadow box-shadow: {{boxShadowBase}}</span>
<div
class="demo-shadow"
:style="{ boxShadow: boxShadowLight }"
></div>
<span class="demo-shadow-text">Light Shadow box-shadow: {{boxShadowLight}}</span>

View File

@@ -0,0 +1,49 @@
## Breadcrumb
Displays the location of the current page, making it easier to browser back.
### Basic usage
:::demo In `el-breadcrumb`, each `el-breadcrumb-item` is a tag that stands for every level starting from homepage. This component has a `String` attribute `separator`, and it determines the separator. Its default value is '/'.
```html
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item>
<el-breadcrumb-item><a href="/">promotion management</a></el-breadcrumb-item>
<el-breadcrumb-item>promotion list</el-breadcrumb-item>
<el-breadcrumb-item>promotion detail</el-breadcrumb-item>
</el-breadcrumb>
```
:::
### Icon separator
:::demo Set `separator-class` to use `iconfont` as the separatorit will cover `separator`
```html
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item>
<el-breadcrumb-item>promotion management</el-breadcrumb-item>
<el-breadcrumb-item>promotion list</el-breadcrumb-item>
<el-breadcrumb-item>promotion detail</el-breadcrumb-item>
</el-breadcrumb>
```
:::
### Breadcrumb Attributes
| Attribute | Description | Type | Accepted Values | Default|
|---------- |-------------- |---------- |-------------------------------- |-------- |
| separator | separator character | string | — | / |
| separator-class | class name of icon separator | string | — | - |
### Breadcrumb Item Attributes
| Attribute | Description | Type | Accepted Values | Default|
|---------- |-------------- |---------- |-------------------------------- |-------- |
| to | target route of the link, same as `to` of `vue-router` | string/object | — | — |
| replace | if `true`, the navigation will not leave a history record | boolean | — | false |

View File

@@ -0,0 +1,165 @@
## Button
Commonly used button.
### Basic usage
:::demo Use `type`, `plain`, `round` and `circle` to define Button's style.
```html
<el-row>
<el-button>Default</el-button>
<el-button type="primary">Primary</el-button>
<el-button type="success">Success</el-button>
<el-button type="info">Info</el-button>
<el-button type="warning">Warning</el-button>
<el-button type="danger">Danger</el-button>
</el-row>
<el-row>
<el-button plain>Plain</el-button>
<el-button type="primary" plain>Primary</el-button>
<el-button type="success" plain>Success</el-button>
<el-button type="info" plain>Info</el-button>
<el-button type="warning" plain>Warning</el-button>
<el-button type="danger" plain>Danger</el-button>
</el-row>
<el-row>
<el-button round>Round</el-button>
<el-button type="primary" round>Primary</el-button>
<el-button type="success" round>Success</el-button>
<el-button type="info" round>Info</el-button>
<el-button type="warning" round>Warning</el-button>
<el-button type="danger" round>Danger</el-button>
</el-row>
<el-row>
<el-button icon="el-icon-search" circle></el-button>
<el-button type="primary" icon="el-icon-edit" circle></el-button>
<el-button type="success" icon="el-icon-check" circle></el-button>
<el-button type="info" icon="el-icon-message" circle></el-button>
<el-button type="warning" icon="el-icon-star-off" circle></el-button>
<el-button type="danger" icon="el-icon-delete" circle></el-button>
</el-row>
```
:::
### Disabled Button
The `disabled` attribute determines if the button is disabled.
:::demo Use `disabled` attribute to determine whether a button is disabled. It accepts a `Boolean` value.
```html
<el-row>
<el-button disabled>Default</el-button>
<el-button type="primary" disabled>Primary</el-button>
<el-button type="success" disabled>Success</el-button>
<el-button type="info" disabled>Info</el-button>
<el-button type="warning" disabled>Warning</el-button>
<el-button type="danger" disabled>Danger</el-button>
</el-row>
<el-row>
<el-button plain disabled>Plain</el-button>
<el-button type="primary" plain disabled>Primary</el-button>
<el-button type="success" plain disabled>Success</el-button>
<el-button type="info" plain disabled>Info</el-button>
<el-button type="warning" plain disabled>Warning</el-button>
<el-button type="danger" plain disabled>Danger</el-button>
</el-row>
```
:::
### Text Button
Buttons without border and background.
:::demo
```html
<el-button type="text">Text Button</el-button>
<el-button type="text" disabled>Text Button</el-button>
```
:::
### Icon Button
Use icons to add more meaning to Button. You can use icon alone to save some space, or use it with text.
:::demo Use the `icon` attribute to add icon. You can find the icon list in Element icon component. Adding icons to the right side of the text is achievable with an `<i>` tag. Custom icons can be used as well.
```html
<el-button type="primary" icon="el-icon-edit"></el-button>
<el-button type="primary" icon="el-icon-share"></el-button>
<el-button type="primary" icon="el-icon-delete"></el-button>
<el-button type="primary" icon="el-icon-search">Search</el-button>
<el-button type="primary">Upload<i class="el-icon-upload el-icon-right"></i></el-button>
```
:::
### Button Group
Displayed as a button group, can be used to group a series of similar operations.
:::demo Use tag `<el-button-group>` to group your buttons.
```html
<el-button-group>
<el-button type="primary" icon="el-icon-arrow-left">Previous Page</el-button>
<el-button type="primary">Next Page<i class="el-icon-arrow-right el-icon-right"></i></el-button>
</el-button-group>
<el-button-group>
<el-button type="primary" icon="el-icon-edit"></el-button>
<el-button type="primary" icon="el-icon-share"></el-button>
<el-button type="primary" icon="el-icon-delete"></el-button>
</el-button-group>
```
:::
### Loading Button
Click the button to load data, then the button displays a loading state.
:::demo Set `loading` attribute to `true` to display loading state.
```html
<el-button type="primary" :loading="true">Loading</el-button>
```
:::
### Sizes
Besides default size, Button component provides three additional sizes for you to choose among different scenarios.
:::demo Use attribute `size` to set additional sizes with `medium`, `small` or `mini`.
```html
<el-row>
<el-button>Default</el-button>
<el-button size="medium">Medium</el-button>
<el-button size="small">Small</el-button>
<el-button size="mini">Mini</el-button>
</el-row>
<el-row>
<el-button round>Default</el-button>
<el-button size="medium" round>Medium</el-button>
<el-button size="small" round>Small</el-button>
<el-button size="mini" round>Mini</el-button>
</el-row>
```
:::
### Attributes
| Attribute | Description | Type | Accepted values | Default |
|---------- |-------- |---------- |------------- |-------- |
| size | button size | string | medium / small / mini | — |
| type | button type | string | primary / success / warning / danger / info / text | — |
| plain | determine whether it's a plain button | boolean | — | false |
| round | determine whether it's a round button | boolean | — | false |
| circle | determine whether it's a circle button | boolean | — | false |
| loading | determine whether it's loading | boolean | — | false |
| disabled | disable the button | boolean | — | false |
| icon | icon class name | string | — | — |
| autofocus | same as native button's `autofocus` | boolean | — | false |
| native-type | same as native button's `type` | string | button / submit / reset | button |

View File

@@ -0,0 +1,66 @@
## Calendar
Display date.
### Basic
:::demo Set `value` to specify the currently displayed month. If `value` is not specified, current month is displayed. `value` supports two-way binding.
```html
<el-calendar v-model="value">
</el-calendar>
<script>
export default {
data() {
return {
value: new Date()
}
}
}
</script>
```
:::
### Custom Content
:::demo Customize what is displayed in the calendar cell by setting `scoped-slot` named `dateCell`. In `scoped-slot` you can get the date (the date of the current cell), data (including the type, isSelected, day attribute). For details, please refer to the API documentation below.
```html
<el-calendar>
<!-- Use 2.5 slot syntax. If you use Vue 2.6, please use new slot syntax-->
<template
slot="dateCell"
slot-scope="{date, data}">
<p :class="data.isSelected ? 'is-selected' : ''">
{{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}
</p>
</template>
</el-calendar>
<style>
.is-selected {
color: #1989FA;
}
</style>
```
:::
### Range
:::demo Set the `range` attribute to specify the display range of the calendar. Start time must be Monday, end time must be Sunday, and the time span cannot exceed two months.
```html
<el-calendar :range="['2019-03-04', '2019-03-24']">
</el-calendar>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|-----------------|------------------- |---------- |---------------------- |--------- |
| value / v-model | binding value | Date/string/number | — | — |
| range | time range, including start time and end time. Start time must be start day of week, end time must be end day of week, the time span cannot exceed two months. | Array | — | — |
| first-day-of-week | fisrt day of week| Number | 1 to 7 | 1 |
### dateCell Scoped Slot Parameters
| Attribute | Description | Type | Accepted Values | Default |
|-----------------|-------------- |---------- |---------------------- |--------- |
| date | date the cell represents | Date | — | — |
| data | { type, isSelected, day}. The `type` property indicates which month the date belongs, optional values are `prev-month`, `current-month`, `next-month`. The `isSelected` property indicates whether the date is selected. The `day` property is the formatted date in the format yyyy-MM-dd | Object | — | — |

169
examples/docs/en-US/card.md Normal file
View File

@@ -0,0 +1,169 @@
## Card
Integrate information in a card container.
### Basic usage
Card includes title, content and operations.
:::demo Card is made up of `header` and `body`. `header` is optional, and its content distribution depends on a named slot.
```html
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>Card name</span>
<el-button style="float: right; padding: 3px 0" type="text">Operation button</el-button>
</div>
<div v-for="o in 4" :key="o" class="text item">
{{'List item ' + o }}
</div>
</el-card>
<style>
.text {
font-size: 14px;
}
.item {
margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
display: table;
content: "";
}
.clearfix:after {
clear: both
}
.box-card {
width: 480px;
}
</style>
```
:::
### Simple card
The header part can be omitted.
:::demo
```html
<el-card class="box-card">
<div v-for="o in 4" :key="o" class="text item">
{{'List item ' + o }}
</div>
</el-card>
<style>
.text {
font-size: 14px;
}
.item {
padding: 18px 0;
}
.box-card {
width: 480px;
}
</style>
```
:::
### With images
Display richer content by adding some configs.
:::demo The `body-style` attribute defines CSS style of custom `body`. This example also uses `el-col` for layout.
```html
<el-row>
<el-col :span="8" v-for="(o, index) in 2" :key="o" :offset="index > 0 ? 2 : 0">
<el-card :body-style="{ padding: '0px' }">
<img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">
<div style="padding: 14px;">
<span>Yummy hamburger</span>
<div class="bottom clearfix">
<time class="time">{{ currentDate }}</time>
<el-button type="text" class="button">Operating</el-button>
</div>
</div>
</el-card>
</el-col>
</el-row>
<style>
.time {
font-size: 13px;
color: #999;
}
.bottom {
margin-top: 13px;
line-height: 12px;
}
.button {
padding: 0;
float: right;
}
.image {
width: 100%;
display: block;
}
.clearfix:before,
.clearfix:after {
display: table;
content: "";
}
.clearfix:after {
clear: both
}
</style>
<script>
export default {
data() {
return {
currentDate: new Date()
};
}
}
</script>
```
:::
### Shadow
You can define when to show the card shadows
:::demo The `shadow` attribute determines when the card shadows are displayed. It can be `always`, `hover` or `never`.
```html
<el-row :gutter="12">
<el-col :span="8">
<el-card shadow="always">
Always
</el-card>
</el-col>
<el-col :span="8">
<el-card shadow="hover">
Hover
</el-card>
</el-col>
<el-col :span="8">
<el-card shadow="never">
Never
</el-card>
</el-col>
</el-row>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| header | title of the card. Also accepts a DOM passed by `slot#header` | string| — | — |
| body-style | CSS style of body | object| — | { padding: '20px' } |
| shadow | when to show card shadows | string | always / hover / never | always |

View File

@@ -0,0 +1,212 @@
## Carousel
Loop a series of images or texts in a limited space
### Basic usage
:::demo Combine `el-carousel` with `el-carousel-item`, and you'll get a carousel. Content of each slide is completely customizable, and you just need to place it inside `el-carousel-item` tag. By default the carousel switches when mouse hovers over an indicator. Set `trigger` to `click`, and the carousel switches only when an indicator is clicked.
```html
<template>
<div class="block">
<span class="demonstration">Switch when indicator is hovered (default)</span>
<el-carousel height="150px">
<el-carousel-item v-for="item in 4" :key="item">
<h3 class="small">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</div>
<div class="block">
<span class="demonstration">Switch when indicator is clicked</span>
<el-carousel trigger="click" height="150px">
<el-carousel-item v-for="item in 4" :key="item">
<h3 class="small">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</div>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 150px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Indicators
Indicators can be displayed outside the carousel
:::demo The `indicator-position` attribute determines where the indicators are located. By default they are inside the carousel, and setting `indicator-position` to `outside` moves them outside; setting `indicator-position` to `none` hides the indicators.
```html
<template>
<el-carousel indicator-position="outside">
<el-carousel-item v-for="item in 4" :key="item">
<h3>{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 18px;
opacity: 0.75;
line-height: 300px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Arrows
You can define when arrows are displayed
:::demo The `arrow` attribute determines when arrows are displayed. By default they appear when mouse hovers over the carousel. Setting `arrow` to `always` or `never` shows/hides the arrows permanently.
```html
<template>
<el-carousel :interval="5000" arrow="always">
<el-carousel-item v-for="item in 4" :key="item">
<h3>{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 18px;
opacity: 0.75;
line-height: 300px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Card mode
When a page is wide enough but has limited height, you can activate card mode for carousels
:::demo Setting `type` to `card` activates the card mode. Apart from the appearance, the biggest difference between card mode and common mode is that clicking the slides at both sides directly switches the carousel in card mode.
```html
<template>
<el-carousel :interval="4000" type="card" height="200px">
<el-carousel-item v-for="item in 6" :key="item">
<h3 class="medium">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 200px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
By default, `direction` is `horizontal`. Let carousel be displayed in the vertical direction by setting `direction` to `vertical`.
:::demo
```html
<template>
<el-carousel height="200px" direction="vertical" :autoplay="false">
<el-carousel-item v-for="item in 4" :key="item">
<h3 class="medium">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 200px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Carousel Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| height | height of the carousel | string | — | — |
| initial-index | index of the initially active slide (starting from 0) | number | — | 0 |
| trigger | how indicators are triggered | string | hover/click | hover |
| autoplay | whether automatically loop the slides | boolean | — | true |
| interval | interval of the auto loop, in milliseconds | number | — | 3000 |
| indicator-position | position of the indicators | string | outside/none | — |
| arrow | when arrows are shown | string | always/hover/never | hover |
| type | type of the Carousel | string | card | — |
| loop | display the items in loop | boolean | - | true |
| direction | display direction | string | horizontal/vertical | horizontal |
### Carousel Events
| Event Name | Description | Parameters |
|---------|---------|---------|
| change | triggers when the active slide switches | index of the new active slide, index of the old active slide |
### Carousel Methods
| Method | Description | Parameters |
|---------- |-------------- | -- |
| setActiveItem | manually switch slide | index of the slide to be switched to, starting from 0; or the `name` of corresponding `el-carousel-item` |
| prev | switch to the previous slide | — |
| next | switch to the next slide | — |
### Carousel-Item Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| name | name of the item, can be used in `setActiveItem` | string | — | — |
| label | text content for the corresponding indicator | string | — | — |

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,284 @@
## Checkbox
A group of options for multiple choices.
### Basic usage
Checkbox can be used alone to switch between two states.
:::demo Define `v-model`(bind variable) in `el-checkbox`. The default value is a `Boolean` for single `checkbox`, and it becomes `true` when selected. Content inside the `el-checkbox` tag will become the description following the button of the checkbox.
```html
<template>
<!-- `checked` should be true or false -->
<el-checkbox v-model="checked">Option</el-checkbox>
</template>
<script>
export default {
data() {
return {
checked: true
};
}
};
</script>
```
:::
### Disabled State
Disabled state for checkbox.
:::demo Set the `disabled` attribute.
```html
<template>
<el-checkbox v-model="checked1" disabled>Option</el-checkbox>
<el-checkbox v-model="checked2" disabled>Option</el-checkbox>
</template>
<script>
export default {
data() {
return {
checked1: false,
checked2: true
};
}
};
</script>
```
:::
### Checkbox group
It is used for multiple checkboxes which are bound in one group, and indicates whether one option is selected by checking if it is checked.
:::demo `checkbox-group` element can manage multiple checkboxes in one group by using `v-model` which is bound as an `Array`. Inside the `el-checkbox` element, `label` is the value of the checkbox. If no content is nested in that tag, `label` will be rendered as the description following the button of the checkbox. `label` also corresponds with the element values in the array. It is selected if the specified value exists in the array, and vice versa.
```html
<template>
<el-checkbox-group v-model="checkList">
<el-checkbox label="Option A"></el-checkbox>
<el-checkbox label="Option B"></el-checkbox>
<el-checkbox label="Option C"></el-checkbox>
<el-checkbox label="disabled" disabled></el-checkbox>
<el-checkbox label="selected and disabled" disabled></el-checkbox>
</el-checkbox-group>
</template>
<script>
export default {
data () {
return {
checkList: ['selected and disabled','Option A']
};
}
};
</script>
```
:::
### Indeterminate
The `indeterminate` property can help you to achieve a 'check all' effect.
:::demo
```html
<template>
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">Check all</el-checkbox>
<div style="margin: 15px 0;"></div>
<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
<el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
</el-checkbox-group>
</template>
<script>
const cityOptions = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'];
export default {
data() {
return {
checkAll: false,
checkedCities: ['Shanghai', 'Beijing'],
cities: cityOptions,
isIndeterminate: true
};
},
methods: {
handleCheckAllChange(val) {
this.checkedCities = val ? cityOptions : [];
this.isIndeterminate = false;
},
handleCheckedCitiesChange(value) {
let checkedCount = value.length;
this.checkAll = checkedCount === this.cities.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
}
}
};
</script>
```
:::
### Minimum / Maximum items checked
The `min` and `max` properties can help you to limit the number of checked items.
:::demo
```html
<template>
<el-checkbox-group
v-model="checkedCities"
:min="1"
:max="2">
<el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
</el-checkbox-group>
</template>
<script>
const cityOptions = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'];
export default {
data() {
return {
checkedCities: ['Shanghai', 'Beijing'],
cities: cityOptions
};
}
};
</script>
```
:::
### Button style
Checkbox with button styles.
:::demo You just need to change `el-checkbox` element into `el-checkbox-button` element. We also provide `size` attribute.
```html
<template>
<div>
<el-checkbox-group v-model="checkboxGroup1">
<el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup2" size="medium">
<el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup3" size="small">
<el-checkbox-button v-for="city in cities" :label="city" :disabled="city === 'Beijing'" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup4" size="mini" disabled>
<el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
</template>
<script>
const cityOptions = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'];
export default {
data () {
return {
checkboxGroup1: ['Shanghai'],
checkboxGroup2: ['Shanghai'],
checkboxGroup3: ['Shanghai'],
checkboxGroup4: ['Shanghai'],
cities: cityOptions
};
}
}
</script>
```
:::
### With borders
:::demo The `border` attribute adds a border to Checkboxes.
```html
<template>
<div>
<el-checkbox v-model="checked1" label="Option1" border></el-checkbox>
<el-checkbox v-model="checked2" label="Option2" border></el-checkbox>
</div>
<div style="margin-top: 20px">
<el-checkbox v-model="checked3" label="Option1" border size="medium"></el-checkbox>
<el-checkbox v-model="checked4" label="Option2" border size="medium"></el-checkbox>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup1" size="small">
<el-checkbox label="Option1" border></el-checkbox>
<el-checkbox label="Option2" border disabled></el-checkbox>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup2" size="mini" disabled>
<el-checkbox label="Option1" border></el-checkbox>
<el-checkbox label="Option2" border></el-checkbox>
</el-checkbox-group>
</div>
</template>
<script>
export default {
data () {
return {
checked1: true,
checked2: false,
checked3: false,
checked4: true,
checkboxGroup1: [],
checkboxGroup2: []
};
}
}
</script>
```
:::
### Checkbox Attributes
| Attribute | Description | Type | Options | Default|
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | binding value | string / number / boolean | — | — |
| label | value of the Checkbox when used inside a `checkbox-group` | string / number / boolean | — | — |
| true-label | value of the Checkbox if it's checked | string / number | — | — |
| false-label | value of the Checkbox if it's not checked | string / number | — | — |
| disabled | whether the Checkbox is disabled | boolean | — | false |
| border | whether to add a border around Checkbox | boolean | — | false |
| size | size of the Checkbox, only works when `border` is true | string | medium / small / mini | — |
| name | native 'name' attribute | string | — | — |
| checked | if the Checkbox is checked | boolean | — | false |
| indeterminate | same as `indeterminate` in native checkbox | boolean | — | false |
### Checkbox Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| change | triggers when the binding value changes | the updated value |
### Checkbox-group Attributes
| Attribute | Description | Type | Options | Default|
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | binding value | array | — | — |
|size | size of checkbox buttons or bordered checkboxes | string | medium / small / mini | — |
| disabled | whether the nesting checkboxes are disabled | boolean | — | false |
| min | minimum number of checkbox checked | number | — | — |
| max | maximum number of checkbox checked | number | — | — |
|text-color | font color when button is active | string | — | #ffffff |
|fill | border and background color when button is active | string | — | #409EFF |
### Checkbox-group Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| change | triggers when the binding value changes | the updated value |
### Checkbox-button Attributes
| Attribute | Description | Type | Options | Default|
|---------- |-------- |---------- |------------- |-------- |
| label | value of the checkbox when used inside a `checkbox-group` | string / number / boolean | — | — |
| true-label | value of the checkbox if it's checked | string / number | — | — |
| false-label | value of the checkbox if it's not checked | string / number | — | — |
| disabled | whether the checkbox is disabled | boolean | — | false |
| name | native 'name' attribute | string | — | — |
| checked | if the checkbox is checked | boolean | — | false |

View File

@@ -0,0 +1,131 @@
## Collapse
Use Collapse to store contents.
### Basic usage
You can expand multiple panels
:::demo
```html
<el-collapse v-model="activeNames" @change="handleChange">
<el-collapse-item title="Consistency" name="1">
<div>Consistent with real life: in line with the process and logic of real life, and comply with languages and habits that the users are used to;</div>
<div>Consistent within interface: all elements should be consistent, such as: design style, icons and texts, position of elements, etc.</div>
</el-collapse-item>
<el-collapse-item title="Feedback" name="2">
<div>Operation feedback: enable the users to clearly perceive their operations by style updates and interactive effects;</div>
<div>Visual feedback: reflect current state by updating or rearranging elements of the page.</div>
</el-collapse-item>
<el-collapse-item title="Efficiency" name="3">
<div>Simplify the process: keep operating process simple and intuitive;</div>
<div>Definite and clear: enunciate your intentions clearly so that the users can quickly understand and make decisions;</div>
<div>Easy to identify: the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.</div>
</el-collapse-item>
<el-collapse-item title="Controllability" name="4">
<div>Decision making: giving advices about operations is acceptable, but do not make decisions for the users;</div>
<div>Controlled consequences: users should be granted the freedom to operate, including canceling, aborting or terminating current operation.</div>
</el-collapse-item>
</el-collapse>
<script>
export default {
data() {
return {
activeNames: ['1']
};
},
methods: {
handleChange(val) {
console.log(val);
}
}
}
</script>
```
:::
### Accordion
In accordion mode, only one panel can be expanded at once
:::demo Activate accordion mode using the `accordion` attribute.
```html
<el-collapse v-model="activeName" accordion>
<el-collapse-item title="Consistency" name="1">
<div>Consistent with real life: in line with the process and logic of real life, and comply with languages and habits that the users are used to;</div>
<div>Consistent within interface: all elements should be consistent, such as: design style, icons and texts, position of elements, etc.</div>
</el-collapse-item>
<el-collapse-item title="Feedback" name="2">
<div>Operation feedback: enable the users to clearly perceive their operations by style updates and interactive effects;</div>
<div>Visual feedback: reflect current state by updating or rearranging elements of the page.</div>
</el-collapse-item>
<el-collapse-item title="Efficiency" name="3">
<div>Simplify the process: keep operating process simple and intuitive;</div>
<div>Definite and clear: enunciate your intentions clearly so that the users can quickly understand and make decisions;</div>
<div>Easy to identify: the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.</div>
</el-collapse-item>
<el-collapse-item title="Controllability" name="4">
<div>Decision making: giving advices about operations is acceptable, but do not make decisions for the users;</div>
<div>Controlled consequences: users should be granted the freedom to operate, including canceling, aborting or terminating current operation.</div>
</el-collapse-item>
</el-collapse>
<script>
export default {
data() {
return {
activeName: '1'
};
}
}
</script>
```
:::
### Custom title
Besides using the `title` attribute, you can customize panel title with named slots, which makes adding custom content, e.g. icons, possible.
:::demo
```html
<el-collapse accordion>
<el-collapse-item name="1">
<template slot="title">
Consistency<i class="header-icon el-icon-info"></i>
</template>
<div>Consistent with real life: in line with the process and logic of real life, and comply with languages and habits that the users are used to;</div>
<div>Consistent within interface: all elements should be consistent, such as: design style, icons and texts, position of elements, etc.</div>
</el-collapse-item>
<el-collapse-item title="Feedback" name="2">
<div>Operation feedback: enable the users to clearly perceive their operations by style updates and interactive effects;</div>
<div>Visual feedback: reflect current state by updating or rearranging elements of the page.</div>
</el-collapse-item>
<el-collapse-item title="Efficiency" name="3">
<div>Simplify the process: keep operating process simple and intuitive;</div>
<div>Definite and clear: enunciate your intentions clearly so that the users can quickly understand and make decisions;</div>
<div>Easy to identify: the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.</div>
</el-collapse-item>
<el-collapse-item title="Controllability" name="4">
<div>Decision making: giving advices about operations is acceptable, but do not make decisions for the users;</div>
<div>Controlled consequences: users should be granted the freedom to operate, including canceling, aborting or terminating current operation.</div>
</el-collapse-item>
</el-collapse>
```
:::
### Collapse Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value / v-model | currently active panel | string (accordion mode) / array (non-accordion mode) | — | — |
| accordion | whether to activate accordion mode | boolean | — | false |
### Collapse Events
| Event Name | Description | Parameters |
|---------|---------|---------|
| change | triggers when active panels change | (activeNames: array (non-accordion mode) / string (accordion mode)) |
### Collapse Item Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| name | unique identification of the panel | string/number | — | — |
| title | title of the panel | string | — | — |
| disabled | disable the collapse item | boolean | — | — |

View File

@@ -0,0 +1,124 @@
## ColorPicker
ColorPicker is a color selector supporting multiple color formats.
### Basic usage
:::demo ColorPicker requires a string typed variable to be bound to v-model.
```html
<div class="block">
<span class="demonstration">With default value</span>
<el-color-picker v-model="color1"></el-color-picker>
</div>
<div class="block">
<span class="demonstration">With no default value</span>
<el-color-picker v-model="color2"></el-color-picker>
</div>
<script>
export default {
data() {
return {
color1: '#409EFF',
color2: null
}
}
};
</script>
```
:::
### Alpha
:::demo ColorPicker supports alpha channel selecting. To activate alpha selecting, just add the `show-alpha` attribute.
```html
<el-color-picker v-model="color" show-alpha></el-color-picker>
<script>
export default {
data() {
return {
color: 'rgba(19, 206, 102, 0.8)'
}
}
};
</script>
```
:::
### Predefined colors
:::demo ColorPicker supports predefined color options
```html
<el-color-picker
v-model="color"
show-alpha
:predefine="predefineColors">
</el-color-picker>
<script>
export default {
data() {
return {
color: 'rgba(255, 69, 0, 0.68)',
predefineColors: [
'#ff4500',
'#ff8c00',
'#ffd700',
'#90ee90',
'#00ced1',
'#1e90ff',
'#c71585',
'rgba(255, 69, 0, 0.68)',
'rgb(255, 120, 0)',
'hsv(51, 100, 98)',
'hsva(120, 40, 94, 0.5)',
'hsl(181, 100%, 37%)',
'hsla(209, 100%, 56%, 0.73)',
'#c7158577'
]
}
}
};
</script>
```
:::
### Sizes
:::demo
```html
<el-color-picker v-model="color"></el-color-picker>
<el-color-picker v-model="color" size="medium"></el-color-picker>
<el-color-picker v-model="color" size="small"></el-color-picker>
<el-color-picker v-model="color" size="mini"></el-color-picker>
<script>
export default {
data() {
return {
color: '#409EFF'
}
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | binding value | string | — | — |
| disabled | whether to disable the ColorPicker | boolean | — | false |
| size | size of ColorPicker | string | — | medium / small / mini |
| show-alpha | whether to display the alpha slider | boolean | — | false |
| color-format | color format of v-model | string | hsl / hsv / hex / rgb | hex (when show-alpha is false)/ rgb (when show-alpha is true) |
| popper-class | custom class name for ColorPicker's dropdown | string | — | — |
| predefine | predefined color options | array | — | — |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| change | triggers when input value changes | color value |
| active-change | triggers when the current active color changes | active color value |

View File

@@ -0,0 +1,251 @@
<script>
import bus from '../../bus';
import { tintColor } from '../../color.js';
import { ACTION_USER_CONFIG_UPDATE } from '../../components/theme/constant.js';
const varMap = {
'primary': '$--color-primary',
'success': '$--color-success',
'warning': '$--color-warning',
'danger': '$--color-danger',
'info': '$--color-info',
'white': '$--color-white',
'black': '$--color-black',
'textPrimary': '$--color-text-primary',
'textRegular': '$--color-text-regular',
'textSecondary': '$--color-text-secondary',
'textPlaceholder': '$--color-text-placeholder',
'borderBase': '$--border-color-base',
'borderLight': '$--border-color-light',
'borderLighter': '$--border-color-lighter',
'borderExtraLight': '$--border-color-extra-light'
};
const original = {
primary: '#409EFF',
success: '#67C23A',
warning: '#E6A23C',
danger: '#F56C6C',
info: '#909399',
white: '#FFFFFF',
black: '#000000',
textPrimary: '#303133',
textRegular: '#606266',
textSecondary: '#909399',
textPlaceholder: '#C0C4CC',
borderBase: '#DCDFE6',
borderLight: '#E4E7ED',
borderLighter: '#EBEEF5',
borderExtraLight: '#F2F6FC'
}
export default {
created() {
bus.$on(ACTION_USER_CONFIG_UPDATE, this.setGlobal);
},
mounted() {
this.setGlobal();
},
methods: {
tintColor(color, tint) {
return tintColor(color, tint);
},
setGlobal() {
if (window.userThemeConfig) {
this.global = window.userThemeConfig.global;
}
}
},
data() {
return {
global: {},
primary: '',
success: '',
warning: '',
danger: '',
info: '',
white: '',
black: '',
textPrimary: '',
textRegular: '',
textSecondary: '',
textPlaceholder: '',
borderBase: '',
borderLight: '',
borderLighter: '',
borderExtraLight: ''
}
},
watch: {
global: {
immediate: true,
handler(value) {
Object.keys(original).forEach((o) => {
if (value[varMap[o]]) {
this[o] = value[varMap[o]]
} else {
this[o] = original[o]
}
});
}
}
},
}
</script>
## Color
Element uses a specific set of palettes to specify colors to provide a consistent look and feel for the products you build.
### Main Color
The main color of Element is bright and friendly blue.
<el-row :gutter="12">
<el-col :span="10" :xs="{span: 12}">
<div
class="demo-color-box"
:style="{ background: primary }"
>
Brand Color<div class="value">#409EFF</div>
<div
class="bg-color-sub"
:style="{ background: tintColor(primary, 0.9) }"
>
<div
class="bg-blue-sub-item"
v-for="(item, key) in Array(8)"
:key="key"
:style="{ background: tintColor(primary, (key + 1) / 10) }"
>
</div>
</div>
</div>
</el-col>
</el-row>
### Secondary Color
Besides the main color, you need to use different scene colors in different scenarios (for example, dangerous color indicates dangerous operation)
<el-row :gutter="12">
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: success }"
>Success<div class="value">#67C23A</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(success, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: warning }"
>Warning<div class="value">#E6A23C</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(warning, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: danger }"
>Danger<div class="value">#F56C6C</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(danger, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: info }"
>Info<div class="value">#909399</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(info, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
</el-row>
### Neutral Color
Neutral colors are for text, background and border colors. You can use different neutral colors to represent the hierarchical structure.
<el-row :gutter="12">
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box-group">
<div class="demo-color-box demo-color-box-other"
:style="{ background: textPrimary }"
>Primary Text<div class="value">{{textPrimary}}</div></div>
<div class="demo-color-box demo-color-box-other"
:style="{ background: textRegular }"
>
Regular Text<div class="value">{{textRegular}}</div></div>
<div class="demo-color-box demo-color-box-other"
:style="{ background: textSecondary }"
>Secondary Text<div class="value">{{textSecondary}}</div></div>
<div class="demo-color-box demo-color-box-other"
:style="{ background: textPlaceholder }"
>Placeholder Text<div class="value">{{textPlaceholder}}</div></div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box-group">
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderBase }"
>Base Border<div class="value">{{borderBase}}</div></div>
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderLight }"
>Light Border<div class="value">{{borderLight}}</div></div>
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderLighter }"
>Lighter Border<div class="value">{{borderLighter}}</div></div>
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderExtraLight }"
>Extra Light Border<div class="value">{{borderExtraLight}}</div></div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box-group">
<div
class="demo-color-box demo-color-box-other"
:style="{ background: black }"
>Basic Black<div class="value">{{black}}</div></div>
<div
class="demo-color-box demo-color-box-other"
:style="{ background: white, color: '#303133', border: '1px solid #eee' }"
>Basic White<div class="value">{{white}}</div></div>
<div class="demo-color-box demo-color-box-other bg-transparent">Transparent<div class="value">Transparent</div>
</div>
</div>
</el-col>
</el-row>

View File

@@ -0,0 +1,240 @@
## Container
Container components for scaffolding basic structure of the page:
`<el-container>`: wrapper container. When nested with a `<el-header>` or `<el-footer>`, all its child elements will be vertically arranged. Otherwise horizontally.
`<el-header>`: container for headers.
`<el-aside>`: container for side sections (usually a side nav).
`<el-main>`: container for main sections.
`<el-footer>`: container for footers.
:::tip
These components use flex for layout, so please make sure your browser supports it. Besides, `<el-container>`'s direct child elements have to be one or more of the latter four components. And father element of the latter four components must be a `<el-container>`.
:::
### Common layouts
:::demo
```html
<el-container>
<el-header>Header</el-header>
<el-main>Main</el-main>
</el-container>
<el-container>
<el-header>Header</el-header>
<el-main>Main</el-main>
<el-footer>Footer</el-footer>
</el-container>
<el-container>
<el-aside width="200px">Aside</el-aside>
<el-main>Main</el-main>
</el-container>
<el-container>
<el-header>Header</el-header>
<el-container>
<el-aside width="200px">Aside</el-aside>
<el-main>Main</el-main>
</el-container>
</el-container>
<el-container>
<el-header>Header</el-header>
<el-container>
<el-aside width="200px">Aside</el-aside>
<el-container>
<el-main>Main</el-main>
<el-footer>Footer</el-footer>
</el-container>
</el-container>
</el-container>
<el-container>
<el-aside width="200px">Aside</el-aside>
<el-container>
<el-header>Header</el-header>
<el-main>Main</el-main>
</el-container>
</el-container>
<el-container>
<el-aside width="200px">Aside</el-aside>
<el-container>
<el-header>Header</el-header>
<el-main>Main</el-main>
<el-footer>Footer</el-footer>
</el-container>
</el-container>
<style>
.el-header, .el-footer {
background-color: #B3C0D1;
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: #D3DCE6;
color: #333;
text-align: center;
line-height: 200px;
}
.el-main {
background-color: #E9EEF3;
color: #333;
text-align: center;
line-height: 160px;
}
body > .el-container {
margin-bottom: 40px;
}
.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
line-height: 260px;
}
.el-container:nth-child(7) .el-aside {
line-height: 320px;
}
</style>
```
:::
### Example
:::demo
```html
<el-container style="height: 500px; border: 1px solid #eee">
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="['1', '3']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-message"></i>Navigator One</template>
<el-menu-item-group>
<template slot="title">Group 1</template>
<el-menu-item index="1-1">Option 1</el-menu-item>
<el-menu-item index="1-2">Option 2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group 2">
<el-menu-item index="1-3">Option 3</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">Option4</template>
<el-menu-item index="1-4-1">Option 4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="2">
<template slot="title"><i class="el-icon-menu"></i>Navigator Two</template>
<el-menu-item-group>
<template slot="title">Group 1</template>
<el-menu-item index="2-1">Option 1</el-menu-item>
<el-menu-item index="2-2">Option 2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group 2">
<el-menu-item index="2-3">Option 3</el-menu-item>
</el-menu-item-group>
<el-submenu index="2-4">
<template slot="title">Option 4</template>
<el-menu-item index="2-4-1">Option 4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="3">
<template slot="title"><i class="el-icon-setting"></i>Navigator Three</template>
<el-menu-item-group>
<template slot="title">Group 1</template>
<el-menu-item index="3-1">Option 1</el-menu-item>
<el-menu-item index="3-2">Option 2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group 2">
<el-menu-item index="3-3">Option 3</el-menu-item>
</el-menu-item-group>
<el-submenu index="3-4">
<template slot="title">Option 4</template>
<el-menu-item index="3-4-1">Option 4-1</el-menu-item>
</el-submenu>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="text-align: right; font-size: 12px">
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>View</el-dropdown-item>
<el-dropdown-item>Add</el-dropdown-item>
<el-dropdown-item>Delete</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span>Tom</span>
</el-header>
<el-main>
<el-table :data="tableData">
<el-table-column prop="date" label="Date" width="140">
</el-table-column>
<el-table-column prop="name" label="Name" width="120">
</el-table-column>
<el-table-column prop="address" label="Address">
</el-table-column>
</el-table>
</el-main>
</el-container>
</el-container>
<style>
.el-header {
background-color: #B3C0D1;
color: #333;
line-height: 60px;
}
.el-aside {
color: #333;
}
</style>
<script>
export default {
data() {
const item = {
date: '2016-05-02',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles'
};
return {
tableData: Array(20).fill(item)
}
}
};
</script>
```
:::
### Container Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| direction | layout direction for child elements | string | horizontal / vertical | vertical when nested with `el-header` or `el-footer`; horizontal otherwise |
### Header Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| height | height of the header | string | — | 60px |
### Aside Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| width | width of the side section | string | — | 300px |
### Footer Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| height | height of the footer | string | — | 60px |

View File

@@ -0,0 +1,132 @@
## Custom theme
Element uses BEM-styled CSS so that you can override styles easily. But if you need to replace styles at a large scale, e.g. change the theme color from blue to orange or green, maybe overriding them one by one is not a good idea. We provide four ways to change the style variables.
### Theme Roller
Use [Online Theme Roller](./#/en-US/theme) to customize all Design Tokens of global variables and componentsand preview the new theme in real-time.and it can generate a complete style package based on the new theme for you to download directly (to import new style files in your project, please refer to the 'Import custom theme' part of this section).
Also, use [Theme Roller Chrome Extension](https://chrome.google.com/webstore/detail/element-theme-roller/lifkjlojflekabbmlddfccdkphlelmim)to customize theme and preview in real-time on any website developed by Element.
<img src="https://shadow.elemecdn.com/app/sns-client/element-theme-editor2.e16c6a01-806d-11e9-bc23-21435c54c509.png" style="width: 100%;margin: 30px auto 0;display: block;">
### Changing theme color
If you just want to change the theme color of Element, the [theme preview website](https://elementui.github.io/theme-chalk-preview/#/en-US) is recommended. The theme color of Element is bright and friendly blue. By changing it, you can make Element more visually connected to specific projects.
The above website enables you to preview theme of a new theme color in real-time, and it can generate a complete style package based on the new theme color for you to download directly (to import new style files in your project, please refer to the 'Import custom theme' or 'Import component theme on demand' part of this section).
### Update SCSS variables in your project
`theme-chalk` is written in SCSS. If your project also uses SCSS, you can directly change Element style variables. Create a new style file, e.g. `element-variables.scss`:
```html
/* theme color */
$--color-primary: teal;
/* icon font path, required */
$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import "~element-ui/packages/theme-chalk/src/index";
```
Then in the entry file of your project, import this style file instead of Element's built CSS:
```JS
import Vue from 'vue'
import Element from 'element-ui'
import './element-variables.scss'
Vue.use(Element)
```
:::tip
Note that it is required to override icon font path to the relative path of Element's font files.
:::
### CLI theme tool
If you project doesn't use SCSS, you can customize themes with our CLI theme tool:
#### <strong>Install</strong>
First install the theme generator globally or locally. Local install is recommended because in this way, when others clone your project, npm will automatically install it for them.
```shell
npm i element-theme -g
```
Then install the chalk theme from npm or GitHub.
```shell
# from npm
npm i element-theme-chalk -D
# from GitHub
npm i https://github.com/ElementUI/theme-chalk -D
```
#### <strong>Initialize variable file</strong>
After successfully installing the above packages, a command named `et` is available in CLI (if the packages are installed locally, use `node_modules/.bin/et` instead). Run `-i` to initialize the variable file which outputs to `element-variables.scss` by default. And you can specify its output directory as you will.
```shell
et -i [custom output file]
> ✔ Generator variables file
```
In `element-variables.scss` you can find all the variables we used to style Element and they are defined in SCSS format. Here's a snippet:
```css
$--color-primary: #409EFF !default;
$--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */
$--color-primary-light-2: mix($--color-white, $--color-primary, 20%) !default; /* 66b1ff */
$--color-primary-light-3: mix($--color-white, $--color-primary, 30%) !default; /* 79bbff */
$--color-primary-light-4: mix($--color-white, $--color-primary, 40%) !default; /* 8cc5ff */
$--color-primary-light-5: mix($--color-white, $--color-primary, 50%) !default; /* a0cfff */
$--color-primary-light-6: mix($--color-white, $--color-primary, 60%) !default; /* b3d8ff */
$--color-primary-light-7: mix($--color-white, $--color-primary, 70%) !default; /* c6e2ff */
$--color-primary-light-8: mix($--color-white, $--color-primary, 80%) !default; /* d9ecff */
$--color-primary-light-9: mix($--color-white, $--color-primary, 90%) !default; /* ecf5ff */
$--color-success: #67c23a !default;
$--color-warning: #e6a23c !default;
$--color-danger: #f56c6c !default;
$--color-info: #909399 !default;
...
```
#### <strong>Modify variables</strong>
Just edit `element-variables.scss`, e.g. changing the theme color to red:
```CSS
$--color-primary: red;
```
#### <strong>Build theme</strong>
After saving the variable file, use `et` to build your theme. You can activate `watch` mode by adding a parameter `-w`. And if you customized the variable file's output, you need to add a parameter `-c` and variable file's name. By default the build theme file is placed inside `./theme`. You can specify its output directory with parameter `-o`.
```shell
et
> ✔ build theme font
> ✔ build element theme
```
### Use custom theme
#### <strong>Import custom theme</strong>
Importing your own theme is just like importing the default theme, only this time you import the file built from "Online Theme Roller" or "CLI tool":
```javascript
import '../theme/index.css'
import ElementUI from 'element-ui'
import Vue from 'vue'
Vue.use(ElementUI)
```
#### <strong>Import component theme on demand</strong>
If you are using `babel-plugin-component` for on-demand import, just modify `.babelrc` and specify `styleLibraryName` to the path where your custom theme is located relative to `.babelrc`. Note that `~` is required:
```json
{
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "~theme"
}
]
]
}
```
If you are unfamiliar with `babel-plugin-component`, please refer to <a href="./#/en-US/component/quickstart">Quick Start</a>. For more details, check out the [project repository](https://github.com/ElementUI/element-theme) of `element-theme`.

View File

@@ -0,0 +1,491 @@
## DatePicker
Use Date Picker for date input.
### Enter Date
Basic date picker measured by 'day'.
:::demo The measurement is determined by the `type` attribute. You can enable quick options by creating a `picker-options` object with `shortcuts` property. The disabled date is set by `disabledDate`, which is a function.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="date"
placeholder="Pick a day">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Picker with quick options</span>
<el-date-picker
v-model="value2"
type="date"
placeholder="Pick a day"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
disabledDate(time) {
return time.getTime() > Date.now();
},
shortcuts: [{
text: 'Today',
onClick(picker) {
picker.$emit('pick', new Date());
}
}, {
text: 'Yesterday',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24);
picker.$emit('pick', date);
}
}, {
text: 'A week ago',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', date);
}
}]
},
value1: '',
value2: '',
};
}
};
</script>
```
:::
### Other measurements
You can choose week, month, year or multiple dates by extending the standard date picker component.
:::demo
```html
<div class="container">
<div class="block">
<span class="demonstration">Week</span>
<el-date-picker
v-model="value1"
type="week"
format="Week WW"
placeholder="Pick a week">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Month</span>
<el-date-picker
v-model="value2"
type="month"
placeholder="Pick a month">
</el-date-picker>
</div>
</div>
<div class="container">
<div class="block">
<span class="demonstration">Year</span>
<el-date-picker
v-model="value3"
type="year"
placeholder="Pick a year">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Dates</span>
<el-date-picker
type="dates"
v-model="value4"
placeholder="Pick one or more dates">
</el-date-picker>
</div>
</div>
<script>
export default {
data() {
return {
value1: '',
value2: '',
value3: '',
value4: ''
};
}
};
</script>
```
:::
### Date Range
Picking a date range is supported.
:::demo When in range mode, the left and right panels are linked by default. If you want the two panels to switch current months independently, you can use the `unlink-panels` attribute.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="daterange"
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With quick options</span>
<el-date-picker
v-model="value2"
type="daterange"
align="right"
unlink-panels
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'Last week',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last month',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last 3 months',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
},
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Month Range
Picking a month range is supported.
:::demo When in range mode, the left and right panels are linked by default. If you want the two panels to switch current years independently, you can use the `unlink-panels` attribute.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="monthrange"
range-separator="To"
start-placeholder="Start month"
end-placeholder="End month">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With quick options</span>
<el-date-picker
v-model="value2"
type="monthrange"
align="right"
unlink-panels
range-separator="To"
start-placeholder="Start month"
end-placeholder="End month"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'This month',
onClick(picker) {
picker.$emit('pick', [new Date(), new Date()]);
}
}, {
text: 'This year',
onClick(picker) {
const end = new Date();
const start = new Date(new Date().getFullYear(), 0);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last 6 months',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setMonth(start.getMonth() - 6);
picker.$emit('pick', [start, end]);
}
}]
},
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Default Value
If user hasn't picked a date, shows today's calendar by default. You can use `default-value` to set another date. Its value should be parsable by `new Date()`.
If type is `daterange`, `default-value` sets the left side calendar.
:::demo
```html
<template>
<div class="block">
<span class="demonstration">date</span>
<el-date-picker
v-model="value1"
type="date"
placeholder="Pick a date"
default-value="2010-10-01">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">daterange</span>
<el-date-picker
v-model="value2"
type="daterange"
align="right"
start-placeholder="Start Date"
end-placeholder="End Date"
default-value="2010-10-01">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Date Formats
Use `format` to control displayed text's format in the input box. Use `value-format` to control binding value's format.
By default, the component accepts and emits a `Date` object. Below are supported format strings, using UTC 2017-01-02 03:04:05 as an example:
:::warning
Pay attention to capitalization
:::
| format | meaning | note | example |
|------|------|------|------|------|
| `yyyy` | year | | 2017 |
| `M` | month | no leading 0 | 1 |
| `MM` | month | | 01 |
| `MMM` | month | | Jan |
| `MMMM` | month | | January |
| `W` | week | only for week picker's `format`; no leading 0 | 1 |
| `WW` | week | only for week picker's `format`| 01 |
| `d` | day | no leading 0 | 2 |
| `dd` | day | | 02 |
| `H` | hour | 24-hour clock; no leading 0 | 3 |
| `HH` | hour | 24-hour clock | 03 |
| `h` | hour | 12-hour clock; must be used with `A` or `a`; no leading 0 | 3 |
| `hh` | hour | 12-hour clock; must be used with `A` or `a` | 03 |
| `m` | minute | no leading 0 | 4 |
| `mm` | minute | | 04 |
| `s` | second | no leading 0 | 5 |
| `ss` | second | | 05 |
| `A` | AM/PM | only for `format`, uppercased | AM |
| `a` | am/pm | only for `format`, lowercased | am |
| `timestamp` | JS timestamp | only for `value-format`; binding value will be a `number` | 1483326245000 |
| `[MM]` | No escape characters | To escape characters, wrap them in square brackets (e.g. [A] [MM]) | MM |
:::demo
```html
<template>
<div class="block">
<span class="demonstration">Emits Date object</span>
<div class="demonstration">Value: {{ value1 }}</div>
<el-date-picker
v-model="value1"
type="date"
placeholder="Pick a Date"
format="yyyy/MM/dd">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Use value-format</span>
<div class="demonstration">Value: {{ value2 }}</div>
<el-date-picker
v-model="value2"
type="date"
placeholder="Pick a Date"
format="yyyy/MM/dd"
value-format="yyyy-MM-dd">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Timestamp</span>
<div class="demonstration">Value{{ value3 }}</div>
<el-date-picker
v-model="value3"
type="date"
placeholder="Pick a Date"
format="yyyy/MM/dd"
value-format="timestamp">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value1: '',
value2: '',
value3: ''
};
}
};
</script>
```
:::
### Default time for start date and end date
When picking a date range, you can assign the time part for start date and end date.
:::demo By default, the time part of start date and end date are both `00:00:00`. Setting `default-time` can change their time respectively. It accepts an array of up to two strings with the format of `12:00:00`. The first string sets the time for the start date, and the second for the end date.
```html
<template>
<div class="block">
<p>Component value{{ value }}</p>
<el-date-picker
v-model="value"
type="daterange"
start-placeholder="Start date"
end-placeholder="End date"
:default-time="['00:00:00', '23:59:59']">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value: ''
};
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value / v-model | binding value | date(DatePicker) / array(DateRangePicker) | — | — |
| readonly | whether DatePicker is read only | boolean | — | false |
| disabled | whether DatePicker is disabled | boolean | — | false |
| size | size of Input | string | large/small/mini | — |
| editable | whether the input is editable | boolean | — | true |
| clearable | whether to show clear button | boolean | — | true |
| placeholder | placeholder in non-range mode | string | — | — |
| start-placeholder | placeholder for the start date in range mode | string | — | — |
| end-placeholder | placeholder for the end date in range mode | string | — | — |
| type | type of the picker | string | year/month/date/dates/datetime/ week/datetimerange/daterange/ monthrange | date |
| format | format of the displayed value in the input box | string | see [date formats](#/en-US/component/date-picker#date-formats) | yyyy-MM-dd |
| align | alignment | left/center/right | left |
| popper-class | custom class name for DatePicker's dropdown | string | — | — |
| picker-options | additional options, check the table below | object | — | {} |
| range-separator | range separator | string | — | '-' |
| default-value | optional, default date of the calendar | Date | anything accepted by `new Date()` | — |
| default-time | optional, the time value to use when selecting date range | string[] | Array with length 2, each item is a string like `12:00:00`. The first item for the start date and then second item for the end date | — |
| value-format | optional, format of binding value. If not specified, the binding value will be a Date object | string | see [date formats](#/en-US/component/date-picker#date-formats) | — |
| name | same as `name` in native input | string | — | — |
| unlink-panels | unlink two date-panels in range-picker | boolean | — | false |
| prefix-icon | Custom prefix icon class | string | — | el-icon-date |
| clear-icon | Custom clear icon class | string | — | el-icon-circle-close |
| validate-event | whether to trigger form validation | boolean | - | true |
### Picker Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| shortcuts | a { text, onClick } object array to set shortcut options, check the table below | object[] | — | — |
| disabledDate | a function determining if a date is disabled with that date as its parameter. Should return a Boolean | function | — | — |
| cellClassName | set custom className | Function(Date) | — | — |
| firstDayOfWeek | first day of week | Number | 1 to 7 | 7 |
| onPick | a callback that triggers when the selected date is changed. Only for `daterange` and `datetimerange`. | Function({ maxDate, minDate }) | - | - |
### shortcuts
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| text | title of the shortcut | string | — | — |
| onClick | callback function, triggers when the shortcut is clicked, with the `vm` as its parameter. You can change the picker value by emitting the `pick` event. Example: `vm.$emit('pick', new Date())`| function | — | — |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| change | triggers when user confirms the value | component's binding value |
| blur | triggers when Input blurs | component instance |
| focus | triggers when Input focuses | component instance |
### Methods
| Method | Description | Parameters |
|------|--------|-------|
| focus | focus the Input component | — |
### Slots
| Name | Description |
|---------|-------------|
| range-separator | custom range separator content |

View File

@@ -0,0 +1,241 @@
## DateTimePicker
Select date and time in one picker.
:::tip
DateTimePicker is derived from DatePicker and TimePicker. For a more detailed explanation on `pickerOptions` and other attributes, you can refer to DatePicker and TimePicker.
:::
### Date and time
:::demo You can select date and time in one picker at the same time by setting `type` to `datetime`. The way to use shortcuts is the same as Date Picker.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="datetime"
placeholder="Select date and time">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With shortcuts</span>
<el-date-picker
v-model="value2"
type="datetime"
placeholder="Select date and time"
:picker-options="pickerOptions">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With default time</span>
<el-date-picker
v-model="value3"
type="datetime"
placeholder="Select date and time"
default-time="12:00:00">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'Today',
onClick(picker) {
picker.$emit('pick', new Date());
}
}, {
text: 'Yesterday',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24);
picker.$emit('pick', date);
}
}, {
text: 'A week ago',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', date);
}
}]
},
value1: '',
value2: '',
value3: ''
};
}
};
</script>
```
:::
### Date and time range
:::demo You can select date and time range by setting `type` to `datetimerange`.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="datetimerange"
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With shortcuts</span>
<el-date-picker
v-model="value2"
type="datetimerange"
:picker-options="pickerOptions"
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date"
align="right">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'Last week',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last month',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last 3 months',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
},
value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
value2: ''
};
}
};
</script>
```
:::
### Default time value for start date and end date
:::demo When picking date range on the date panel with type `datetimerange`, `00:00:00` will be used as the default time value for start and end date. We can control it with the `default-time` attribute. `default-time` accepts an array of up to two strings. The first item controls time value of the start date and the second item controls time value of the end date.
```html
<template>
<div class="block">
<span class="demonstration">Start date time 12:00:00</span>
<el-date-picker
v-model="value1"
type="datetimerange"
start-placeholder="Start Date"
end-placeholder="End Date"
:default-time="['12:00:00']">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Start date time 12:00:00, end date time 08:00:00</span>
<el-date-picker
v-model="value2"
type="datetimerange"
align="right"
start-placeholder="Start Date"
end-placeholder="End Date"
:default-time="['12:00:00', '08:00:00']">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value / v-model | binding value | date(DateTimePicker) / array(DateTimeRangePicker) | — | — |
| readonly | whether DatePicker is read only | boolean | — | false |
| disabled | whether DatePicker is disabled | boolean | — | false |
| editable | whether the input is editable | boolean | — | true |
| clearable | whether to show clear button | boolean | — | true |
|size | size of Input | string | large/small/mini | — |
| placeholder | placeholder in non-range mode | string | — | — |
| start-placeholder | placeholder for the start date in range mode | string | — | — |
| end-placeholder | placeholder for the end date in range mode | string | — | — |
| time-arrow-control | whether to pick time using arrow buttons | boolean | — | false |
| type | type of the picker | string | year/month/date/datetime/ week/datetimerange/daterange | date |
| format | format of the displayed value in the input box | string | see [date formats](#/en-US/component/date-picker#date-formats) | yyyy-MM-dd HH:mm:ss |
| align | alignment | left/center/right | left |
| popper-class | custom class name for DateTimePicker's dropdown | string | — | — |
| picker-options | additional options, check the table below | object | — | {} |
| range-separator | range separator | string | - | '-' |
| default-value | optional, default date of the calendar | Date | anything accepted by `new Date()` | — |
| default-time | the default time value after picking a date | non-range: string / range: string[] | non-range: a string like `12:00:00`, range: array of two strings, and the first item is for the start date and second for the end date. `00:00:00` will be used if not specified | — |
| value-format | optional, format of binding value. If not specified, the binding value will be a Date object | string | see [date formats](#/en-US/component/date-picker#date-formats) | — |
| name | same as `name` in native input | string | — | — |
| unlink-panels | unllink two date-panels in range-picker | boolean | — | false |
| prefix-icon | Custom prefix icon class | string | — | el-icon-date |
| clear-icon | Custom clear icon class | string | — | el-icon-circle-close |
### Picker Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| shortcuts | a { text, onClick } object array to set shortcut options, check the table below | object[] | — | — |
| disabledDate | a function determining if a date is disabled with that date as its parameter. Should return a Boolean | function | — | — |
| cellClassName | set custom className | Function(Date) | — | — |
| firstDayOfWeek | first day of week | Number | 1 to 7 | 7 |
### shortcuts
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| text | title of the shortcut | string | — | — |
| onClick | callback function, triggers when the shortcut is clicked, with the `vm` as its parameter. You can change the picker value by emitting the `pick` event. Example: `vm.$emit('pick', new Date())`| function | — | — |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| change | triggers when user confirms the value | component's binding value |
| blur | triggers when Input blurs | component instance |
| focus | triggers when Input focuses | component instance |
### Methods
| Method | Description | Parameters |
|------|--------|-------|
| focus | focus the Input component | — |

View File

@@ -0,0 +1,240 @@
## Dialog
Informs users while preserving the current page state.
### Basic usage
Dialog pops up a dialog box, and it's quite customizable.
:::demo Set the `visible` attribute with a `Boolean`, and Dialog shows when it is `true`. The Dialog has two parts: `body` and `footer`, and the latter requires a `slot` named `footer`. The optional `title` attribute (empty by default) is for defining a title. Finally, this example demonstrates how `before-close` is used.
```html
<el-button type="text" @click="dialogVisible = true">click to open the Dialog</el-button>
<el-dialog
title="Tips"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<span>This is a message</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">Cancel</el-button>
<el-button type="primary" @click="dialogVisible = false">Confirm</el-button>
</span>
</el-dialog>
<script>
export default {
data() {
return {
dialogVisible: false
};
},
methods: {
handleClose(done) {
this.$confirm('Are you sure to close this dialog?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
```
:::
:::tip
`before-close` only works when user clicks the close icon or the backdrop. If you have buttons that close the Dialog in the `footer` named slot, you can add what you would do with `before-close` in the buttons' click event handler.
:::
### Customizations
The content of Dialog can be anything, even a table or a form. This example shows how to use Element Table and Form with Dialog。
:::demo
```html
<!-- Table -->
<el-button type="text" @click="dialogTableVisible = true">open a Table nested Dialog</el-button>
<el-dialog title="Shipping address" :visible.sync="dialogTableVisible">
<el-table :data="gridData">
<el-table-column property="date" label="Date" width="150"></el-table-column>
<el-table-column property="name" label="Name" width="200"></el-table-column>
<el-table-column property="address" label="Address"></el-table-column>
</el-table>
</el-dialog>
<!-- Form -->
<el-button type="text" @click="dialogFormVisible = true">open a Form nested Dialog</el-button>
<el-dialog title="Shipping address" :visible.sync="dialogFormVisible">
<el-form :model="form">
<el-form-item label="Promotion name" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Zones" :label-width="formLabelWidth">
<el-select v-model="form.region" placeholder="Please select a zone">
<el-option label="Zone No.1" value="shanghai"></el-option>
<el-option label="Zone No.2" value="beijing"></el-option>
</el-select>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">Cancel</el-button>
<el-button type="primary" @click="dialogFormVisible = false">Confirm</el-button>
</span>
</el-dialog>
<script>
export default {
data() {
return {
gridData: [{
date: '2016-05-02',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-04',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-01',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-03',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}],
dialogTableVisible: false,
dialogFormVisible: false,
form: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
formLabelWidth: '120px'
};
}
};
</script>
```
:::
### Nested Dialog
If a Dialog is nested in another Dialog, `append-to-body` is required.
:::demo Normally we do not recommend using nested Dialog. If you need multiple Dialogs rendered on the page, you can simply flat them so that they're siblings to each other. If you must nest a Dialog inside another Dialog, set `append-to-body` of the nested Dialog to true, and it will append to body instead of its parent node, so both Dialogs can be correctly rendered.
```html
<template>
<el-button type="text" @click="outerVisible = true">open the outer Dialog</el-button>
<el-dialog title="Outer Dialog" :visible.sync="outerVisible">
<el-dialog
width="30%"
title="Inner Dialog"
:visible.sync="innerVisible"
append-to-body>
</el-dialog>
<div slot="footer" class="dialog-footer">
<el-button @click="outerVisible = false">Cancel</el-button>
<el-button type="primary" @click="innerVisible = true">open the inner Dialog</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
data() {
return {
outerVisible: false,
innerVisible: false
};
}
}
</script>
```
:::
### Centered content
Dialog's content can be centered.
:::demo Setting `center` to `true` will center dialog's header and footer horizontally. `center` only affects Dialog's header and footer. The body of Dialog can be anything, so sometimes it may not look good when centered. You need to write some CSS if you wish to center the body as well.
```html
<el-button type="text" @click="centerDialogVisible = true">Click to open the Dialog</el-button>
<el-dialog
title="Warning"
:visible.sync="centerDialogVisible"
width="30%"
center>
<span>It should be noted that the content will not be aligned in center by default</span>
<span slot="footer" class="dialog-footer">
<el-button @click="centerDialogVisible = false">Cancel</el-button>
<el-button type="primary" @click="centerDialogVisible = false">Confirm</el-button>
</span>
</el-dialog>
<script>
export default {
data() {
return {
centerDialogVisible: false
};
}
};
</script>
```
:::
:::tip
The content of Dialog is lazily rendered, which means the default slot is not rendered onto the DOM until it is firstly opened. Therefore, if you need to perform a DOM manipulation or access a component using `ref`, do it in the `open` event callback.
:::
:::tip
If the variable bound to `visible` is managed in Vuex store, the `.sync` can not work properly. In this case, please remove the `.sync` modifier, listen to `open` and `close` events of Dialog, and commit Vuex mutations to update the value of that variable in the event handlers.
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| visible | visibility of Dialog, supports the .sync modifier | boolean | — | false |
| title | title of Dialog. Can also be passed with a named slot (see the following table) | string | — | — |
| width | width of Dialog | string | — | 50% |
| fullscreen | whether the Dialog takes up full screen | boolean | — | false |
| top | value for `margin-top` of Dialog CSS | string | — | 15vh |
| modal | whether a mask is displayed | boolean | — | true |
| modal-append-to-body | whether to append modal to body element. If false, the modal will be appended to Dialog's parent element | boolean | — | true |
| append-to-body | whether to append Dialog itself to body. A nested Dialog should have this attribute set to `true` | boolean | — | false |
| lock-scroll | whether scroll of body is disabled while Dialog is displayed | boolean | — | true |
| custom-class | custom class names for Dialog | string | — | — |
| close-on-click-modal | whether the Dialog can be closed by clicking the mask | boolean | — | true |
| close-on-press-escape | whether the Dialog can be closed by pressing ESC | boolean | — | true |
| show-close | whether to show a close button | boolean | — | true |
| before-close | callback before Dialog closes, and it will prevent Dialog from closing | function(done)done is used to close the Dialog | — | — |
| center | whether to align the header and footer in center | boolean | — | false |
| destroy-on-close | Destroy elements in Dialog when closed | boolean | — | false |
### Slot
| Name | Description |
|------|--------|
| — | content of Dialog |
| title | content of the Dialog title |
| footer | content of the Dialog footer |
### Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| open | triggers when the Dialog opens | — |
| opened | triggers when the Dialog opening animation ends | — |
| close | triggers when the Dialog closes | — |
| closed | triggers when the Dialog closing animation ends | — |

View File

@@ -0,0 +1,61 @@
## Divider
The dividing line that separates the content.
### Basic usage
Divide the text of different paragraphs.
:::demo
```html
<template>
<div>
<span>I sit at my window this morning where the world like a passer-by stops for a moment, nods to me and goes.</span>
<el-divider></el-divider>
<span>There little thoughts are the rustle of leaves; they have their whisper of joy in my mind.</span>
</div>
</template>
```
:::
### Custom content
You can customize the content on the divider line.
:::demo
```html
<template>
<div>
<span>What you are you do not see, what you see is your shadow. </span>
<el-divider content-position="left">Rabindranath Tagore</el-divider>
<span>I cannot choose the best. The best chooses me.</span>
<el-divider><i class="el-icon-star-on"></i></el-divider>
<span>My wishes are fools, they shout across thy song, my Master. Let me but listen.</span>
<el-divider content-position="right">Rabindranath Tagore</el-divider>
</div>
</template>
```
:::
### Vertical divider
:::demo
```html
<template>
<div>
<span>Rain</span>
<el-divider direction="vertical"></el-divider>
<span>Home</span>
<el-divider direction="vertical"></el-divider>
<span>Grass</span>
</div>
</template>
```
:::
### Divider Attributes
| Attribute | Description | Type | Accepted Values | Default |
|------------- |---------------- |---------------- |---------------------- |-------- |
| direction | Set divider's direction | string | horizontal / vertical | horizontal |
| content-position | customize the content on the divider line | String | left / right / center | center |

View File

@@ -0,0 +1,305 @@
## Drawer
Sometimes, `Dialog` does not always satisfy our requirements, let's say you have a massive form, or you need space to display something like `terms & conditions`, `Drawer` has almost identical API with `Dialog`, but it introduces different user experience.
### Basic Usage
Callout a temporary drawer, from multiple direction
:::demo You must set `visible` for `Drawer` like `Dialog` does to control the visibility of `Drawer` itself, it's `boolean` type. `Drawer` has to parts: `title` & `body`, the `title` is a named slot, you can also set the title through attribute named `title`, default to an empty string, the `body` part is the main area of `Drawer`, which contains user defined content. When opening, `Drawer` expand itself from the **right corner to left** which size is **30%** of the browser window by default. You can change that default behavior by setting `direction` and `size` attribute. This show case also demonstrated how to use the `before-close` API, check the Attribute section for more detail
```html
<el-radio-group v-model="direction">
<el-radio label="ltr">left to right</el-radio>
<el-radio label="rtl">right to left</el-radio>
<el-radio label="ttb">top to bottom</el-radio>
<el-radio label="btt">bottom to top</el-radio>
</el-radio-group>
<el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
open
</el-button>
<el-drawer
title="I am the title"
:visible.sync="drawer"
:direction="direction"
:before-close="handleClose">
<span>Hi, there!</span>
</el-drawer>
<script>
export default {
data() {
return {
drawer: false,
direction: 'rtl',
};
},
methods: {
handleClose(done) {
this.$confirm('Are you sure you want to close this?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
```
:::
### No Title
When you no longer need a title, you can remove title from drawer.
:::demo Set the `withHeader` attribute to **false**, you can remove the title from drawer, thus your drawer can have more space on screen. If you want to be accessible, make sure to set the `title` attribute.
```html
<el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
open
</el-button>
<el-drawer
title="I am the title"
:visible.sync="drawer"
:with-header="false">
<span>Hi there!</span>
</el-drawer>
<script>
export default {
data() {
return {
drawer: false,
};
}
};
</script>
```
:::
### Customization Content
Like `Dialog`, `Drawer` can do many diverse interaction as you wanted.
:::demo
```html
<el-button type="text" @click="table = true">Open Drawer with nested table</el-button>
<el-button type="text" @click="dialog = true">Open Drawer with nested form</el-button>
<el-drawer
title="I have a nested table inside!"
:visible.sync="table"
direction="rtl"
size="50%">
<el-table :data="gridData">
<el-table-column property="date" label="Date" width="150"></el-table-column>
<el-table-column property="name" label="Name" width="200"></el-table-column>
<el-table-column property="address" label="Address"></el-table-column>
</el-table>
</el-drawer>
<el-drawer
title="I have a nested form inside!"
:before-close="handleClose"
:visible.sync="dialog"
direction="ltr"
custom-class="demo-drawer"
ref="drawer"
>
<div class="demo-drawer__content">
<el-form :model="form">
<el-form-item label="Name" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Area" :label-width="formLabelWidth">
<el-select v-model="form.region" placeholder="Please select activity area">
<el-option label="Area1" value="shanghai"></el-option>
<el-option label="Area2" value="beijing"></el-option>
</el-select>
</el-form-item>
</el-form>
<div class="demo-drawer__footer">
<el-button @click="cancelForm">Cancel</el-button>
<el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading">{{ loading ? 'Submitting ...' : 'Submit' }}</el-button>
</div>
</div>
</el-drawer>
<script>
export default {
data() {
return {
table: false,
dialog: false,
loading: false,
gridData: [{
date: '2016-05-02',
name: 'Peter Parker',
address: 'Queens, New York City'
}, {
date: '2016-05-04',
name: 'Peter Parker',
address: 'Queens, New York City'
}, {
date: '2016-05-01',
name: 'Peter Parker',
address: 'Queens, New York City'
}, {
date: '2016-05-03',
name: 'Peter Parker',
address: 'Queens, New York City'
}],
form: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
formLabelWidth: '80px',
timer: null,
};
},
methods: {
handleClose(done) {
if (this.loading) {
return;
}
this.$confirm('Do you want to submit?')
.then(_ => {
this.loading = true;
this.timer = setTimeout(() => {
done();
// animation takes time
setTimeout(() => {
this.loading = false;
}, 400);
}, 2000);
})
.catch(_ => {});
},
cancelForm() {
this.loading = false;
this.dialog = false;
clearTimeout(this.timer);
}
}
}
</script>
```
:::
### Nested Drawer
You can also have multiple layer of `Drawer` just like `Dialog`.
:::demo If you need multiple Drawer in different layer, you must set the `append-to-body` attribute to **true**
```html
<el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
open
</el-button>
<el-drawer
title="I'm outer Drawer"
:visible.sync="drawer"
size="50%">
<div>
<el-button @click="innerDrawer = true">Click me!</el-button>
<el-drawer
title="I'm inner Drawer"
:append-to-body="true"
:before-close="handleClose"
:visible.sync="innerDrawer">
<p>_(:зゝ∠)_</p>
</el-drawer>
</div>
</el-drawer>
<script>
export default {
data() {
return {
drawer: false,
innerDrawer: false,
};
},
methods: {
handleClose(done) {
this.$confirm('You still have unsaved data, proceed?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
```
:::
:::tip
The content inside Drawer should be lazy rendered, which means that the content inside Drawer will not impact the initial render performance, therefore any DOM operation should be performed through `ref` or after `open` event emitted.
:::
:::tip
Drawer provides an API called `destroyOnClose`, which is a flag variable that indicates should destroy the children content inside Drawer after Drawer was closed. You can use this API when you need your `mounted` life cycle to be called every time the Drawer opens.
:::
:::tip
If the variable bound to `visible` is managed in Vuex store, the `.sync` can not work properly. In this case, please remove the `.sync` modifier, listen to `open` and `close` events of Dialog, and commit Vuex mutations to update the value of that variable in the event handlers.
:::
### Drawer Attributes
| Parameter| Description | Type | Acceptable Values | Defaults |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| append-to-body | Controls should Drawer be inserted to DocumentBody Element, nested Drawer must assign this param to **true**| boolean | — | false |
| before-close | If set, closing procedure will be halted | function(done), done is function type that accepts a boolean as parameter, calling done with true or without parameter will abort the close procedure | — | — |
| close-on-press-escape | Indicates whether Drawer can be closed by pressing ESC | boolean | — | true |
| custom-class | Extra class names for Drawer | string | — | — |
| destroy-on-close | Indicates whether children should be destroyed after Drawer closed | boolean | - | false |
| modal | Should show shadowing layer | boolean | — | true |
| modal-append-to-body | Indicates should shadowing layer be insert into DocumentBody element | boolean | — | true |
| direction | Drawer's opening direction | Direction | rtl / ltr / ttb / btt | rtl |
| show-close | Should show close button at the top right of Drawer | boolean | — | true |
| size | Drawer's size, if Drawer is horizontal mode, it effects the width property, otherwise it effects the height property, when size is `number` type, it describes the size by unit of pixels; when size is `string` type, it should be used with `x%` notation, other wise it will be interpreted to pixel unit | number / string | - | '30%' |
| title | Drawer's title, can also be set by named slot, detailed descriptions can be found in the slot form | string | — | — |
| visible | Should Drawer be displayed, also support the `.sync` notation | boolean | — | false |
| wrapperClosable | Indicates whether user can close Drawer by clicking the shadowing layer. | boolean | - | true |
| withHeader | Flag that controls the header section's existance, default to true, when withHeader set to false, both `title attribute` and `title slot` won't work | boolean | - | true |
### Drawer Slot
| Name | Description |
|------|--------|
| — | Drawer's Content |
| title | Drawer Title Section |
### Drawer Methods
| Name | Description |
| ---- | --- |
| closeDrawer | In order to close Drawer, this method will call `before-close`. |
### Drawer Events
| Event Name | Description | Parameter |
|---------- |-------- |---------- |
| open | Triggered before Drawer opening animation begins | — |
| opened | Triggered after Drawer opening animation ended | — |
| close | Triggered before Drawer closing animation begins | — |
| closed | Triggered after Drawer closing animation ended | — |

View File

@@ -0,0 +1,303 @@
## Dropdown
Toggleable menu for displaying lists of links and actions.
### Basic usage
Hover on the dropdown menu to unfold it for more actions.
:::demo The triggering element is rendered by the default `slot`, and the dropdown part is rendered by the `slot` named `dropdown`. By default, dropdown list shows when you hover on the triggering element without having to click it.
```html
<el-dropdown>
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item disabled>Action 4</el-dropdown-item>
<el-dropdown-item divided>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
```
:::
### Triggering element
Use the button to trigger the dropdown list.
:::demo Use `split-button` to split the triggering element into a button group with the left button being a normal button and right one the actual triggering target. If you wanna insert a separator line between item three and item four, just add a class `divider` to item four.
```html
<el-dropdown>
<el-button type="primary">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</el-button>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
<el-dropdown-item>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown split-button type="primary" @click="handleClick">
Dropdown List
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
<el-dropdown-item>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown {
vertical-align: top;
}
.el-dropdown + .el-dropdown {
margin-left: 15px;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
<script>
export default {
methods: {
handleClick() {
alert('button click');
}
}
}
</script>
```
:::
### How to trigger
Click the triggering element or hover on it.
:::demo Use the attribute `trigger`. By default, it is `hover`.
```html
<el-row class="block-col-2">
<el-col :span="12">
<span class="demonstration">hover to trigger</span>
<el-dropdown>
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item icon="el-icon-plus">Action 1</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus">Action 2</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus-outline">Action 3</el-dropdown-item>
<el-dropdown-item icon="el-icon-check">Action 4</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-check">Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-col>
<el-col :span="12">
<span class="demonstration">click to trigger</span>
<el-dropdown trigger="click">
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item icon="el-icon-plus">Action 1</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus">Action 2</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus-outline">Action 3</el-dropdown-item>
<el-dropdown-item icon="el-icon-check">Action 4</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-check">Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-col>
</el-row>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
.demonstration {
display: block;
color: #8492a6;
font-size: 14px;
margin-bottom: 20px;
}
</style>
```
:::
### Menu hiding behavior
Use `hide-on-click` to define if menu closes on clicking.
:::demo By default menu will close when you click on menu items, and it can be turned off by setting hide-on-click to false.
```html
<el-dropdown :hide-on-click="false">
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item disabled>Action 4</el-dropdown-item>
<el-dropdown-item divided>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
```
:::
### Command event
Clicking each dropdown item fires an event whose parameter is assigned by each item.
:::demo
```html
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="a">Action 1</el-dropdown-item>
<el-dropdown-item command="b">Action 2</el-dropdown-item>
<el-dropdown-item command="c">Action 3</el-dropdown-item>
<el-dropdown-item command="d" disabled>Action 4</el-dropdown-item>
<el-dropdown-item command="e" divided>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
<script>
export default {
methods: {
handleCommand(command) {
this.$message('click on item ' + command);
}
}
}
</script>
```
:::
### Sizes
Besides default size, Dropdown component provides three additional sizes for you to choose among different scenarios.
:::demo Use attribute `size` to set additional sizes with `medium`, `small` or `mini`.
```html
<el-dropdown split-button type="primary">
Default
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown size="medium" split-button type="primary">
Medium
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown size="small" split-button type="primary">
Small
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown size="mini" split-button type="primary">
Mini
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
```
:::
### Dropdown Attributes
| Attribute | Description | Type | Accepted Values | Default |
|------------- |---------------- |---------------- |---------------------- |-------- |
| type | menu button type, refer to `Button` Component, only works when `split-button` is true | string | — | — |
| size | menu size, also works on the split button | string | medium / small / mini | — |
| split-button | whether a button group is displayed | boolean | — | false |
| placement | placement of pop menu | string | top/top-start/top-end/bottom/bottom-start/bottom-end | bottom-end |
| trigger | how to trigger | string | hover/click | hover |
| hide-on-click | whether to hide menu after clicking menu-item | boolean | — | true |
| show-timeout | Delay time before show a dropdown (only works when trigger is `hover`) | number | — | 250 |
| hide-timeout | Delay time before hide a dropdown (only works when trigger is `hover`) | number | — | 150 |
| tabindex | [tabindex](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) of Dropdown | number | — | 0 |
### Dropdown Slots
| Name | Description |
|------|--------|
| — | content of Dropdown. Notice: Must be a valid html dom element (ex. `<span>, <button> etc.`) or `el-component`, to attach the trigger listener |
| dropdown | content of the Dropdown Menu, usually a `<el-dropdown-menu>` element |
### Dropdown Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| click | if `split-button` is `true`, triggers when left button is clicked | — |
| command | triggers when a dropdown item is clicked | the command dispatched from the dropdown item |
| visible-change | triggers when the dropdown appears/disappears | true when it appears, and false otherwise |
### Dropdown Menu Item Attributes
| Attribute | Description | Type | Accepted Values | Default |
|------------- |---------------- |---------------- |---------------------- |-------- |
| command | a command to be dispatched to Dropdown's `command` callback | string/number/object | — | — |
| disabled | whether the item is disabled | boolean | — | false |
| divided | whether a divider is displayed | boolean | — | false |
| icon | icon class name | string | — | — |

650
examples/docs/en-US/form.md Normal file
View File

@@ -0,0 +1,650 @@
## Form
Form consists of `input`, `radio`, `select`, `checkbox` and so on. With form, you can collect, verify and submit data.
### Basic form
It includes all kinds of input items, such as `input`, `select`, `radio` and `checkbox`.
:::demo In each `form` component, you need a `form-item` field to be the container of your input item.
```html
<el-form ref="form" :model="form" label-width="120px">
<el-form-item label="Activity name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="form.region" placeholder="please select your zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Activity time">
<el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="form.date1" style="width: 100%;"></el-date-picker>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="form.date2" style="width: 100%;"></el-time-picker>
</el-col>
</el-form-item>
<el-form-item label="Instant delivery">
<el-switch v-model="form.delivery"></el-switch>
</el-form-item>
<el-form-item label="Activity type">
<el-checkbox-group v-model="form.type">
<el-checkbox label="Online activities" name="type"></el-checkbox>
<el-checkbox label="Promotion activities" name="type"></el-checkbox>
<el-checkbox label="Offline activities" name="type"></el-checkbox>
<el-checkbox label="Simple brand exposure" name="type"></el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item label="Resources">
<el-radio-group v-model="form.resource">
<el-radio label="Sponsor"></el-radio>
<el-radio label="Venue"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="Activity form">
<el-input type="textarea" v-model="form.desc"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">Create</el-button>
<el-button>Cancel</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
form: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
}
}
},
methods: {
onSubmit() {
console.log('submit!');
}
}
}
</script>
```
:::
:::tip
[W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) regulates that
> <i>When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.</i>
To prevent this behavior, you can add `@submit.native.prevent` on `<el-form>`.
:::
### Inline form
When the vertical space is limited and the form is relatively simple, you can put it in one line.
:::demo Set the `inline` attribute to `true` and the form will be inline.
```html
<el-form :inline="true" :model="formInline" class="demo-form-inline">
<el-form-item label="Approved by">
<el-input v-model="formInline.user" placeholder="Approved by"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="formInline.region" placeholder="Activity zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">Query</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
formInline: {
user: '',
region: ''
}
}
},
methods: {
onSubmit() {
console.log('submit!');
}
}
}
</script>
```
:::
### Alignment
Depending on your design, there are several different ways to align your label element.
:::demo The `label-position` attribute decides how labels align, it can be `top` or `left`. When set to `top`, labels will be placed at the top of the form field.
```html
<el-radio-group v-model="labelPosition" size="small">
<el-radio-button label="left">Left</el-radio-button>
<el-radio-button label="right">Right</el-radio-button>
<el-radio-button label="top">Top</el-radio-button>
</el-radio-group>
<div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign">
<el-form-item label="Name">
<el-input v-model="formLabelAlign.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-input v-model="formLabelAlign.region"></el-input>
</el-form-item>
<el-form-item label="Activity form">
<el-input v-model="formLabelAlign.type"></el-input>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
labelPosition: 'right',
formLabelAlign: {
name: '',
region: '',
type: ''
}
};
}
}
</script>
```
:::
### Validation
Form component allows you to verify your data, helping you find and correct errors.
:::demo Just add the `rules` attribute for `Form` component, pass validation rules, and set `prop` attribute for `Form-Item` as a specific key that needs to be validated. See more information at [async-validator](https://github.com/yiminghe/async-validator).
```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
<el-form-item label="Activity name" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone" prop="region">
<el-select v-model="ruleForm.region" placeholder="Activity zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Activity time" required>
<el-col :span="11">
<el-form-item prop="date1">
<el-date-picker type="date" placeholder="Pick a date" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
</el-form-item>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-form-item prop="date2">
<el-time-picker placeholder="Pick a time" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
</el-form-item>
</el-col>
</el-form-item>
<el-form-item label="Instant delivery" prop="delivery">
<el-switch v-model="ruleForm.delivery"></el-switch>
</el-form-item>
<el-form-item label="Activity type" prop="type">
<el-checkbox-group v-model="ruleForm.type">
<el-checkbox label="Online activities" name="type"></el-checkbox>
<el-checkbox label="Promotion activities" name="type"></el-checkbox>
<el-checkbox label="Offline activities" name="type"></el-checkbox>
<el-checkbox label="Simple brand exposure" name="type"></el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item label="Resources" prop="resource">
<el-radio-group v-model="ruleForm.resource">
<el-radio label="Sponsorship"></el-radio>
<el-radio label="Venue"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="Activity form" prop="desc">
<el-input type="textarea" v-model="ruleForm.desc"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">Create</el-button>
<el-button @click="resetForm('ruleForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
ruleForm: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
rules: {
name: [
{ required: true, message: 'Please input Activity name', trigger: 'blur' },
{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' }
],
region: [
{ required: true, message: 'Please select Activity zone', trigger: 'change' }
],
date1: [
{ type: 'date', required: true, message: 'Please pick a date', trigger: 'change' }
],
date2: [
{ type: 'date', required: true, message: 'Please pick a time', trigger: 'change' }
],
type: [
{ type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' }
],
resource: [
{ required: true, message: 'Please select activity resource', trigger: 'change' }
],
desc: [
{ required: true, message: 'Please input activity form', trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
```
:::
### Custom validation rules
This example shows how to customize your own validation rules to finish a two-factor password verification.
:::demo Here we use `status-icon` to reflect validation result as an icon.
```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
<el-form-item label="Password" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Confirm" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Age" prop="age">
<el-input v-model.number="ruleForm.age"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">Submit</el-button>
<el-button @click="resetForm('ruleForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
var checkAge = (rule, value, callback) => {
if (!value) {
return callback(new Error('Please input the age'));
}
setTimeout(() => {
if (!Number.isInteger(value)) {
callback(new Error('Please input digits'));
} else {
if (value < 18) {
callback(new Error('Age must be greater than 18'));
} else {
callback();
}
}
}, 1000);
};
var validatePass = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password'));
} else {
if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass');
}
callback();
}
};
var validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password again'));
} else if (value !== this.ruleForm.pass) {
callback(new Error('Two inputs don\'t match!'));
} else {
callback();
}
};
return {
ruleForm: {
pass: '',
checkPass: '',
age: ''
},
rules: {
pass: [
{ validator: validatePass, trigger: 'blur' }
],
checkPass: [
{ validator: validatePass2, trigger: 'blur' }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
```
:::
:::tip
Custom validate callback function must be called. See more advanced usage at [async-validator](https://github.com/yiminghe/async-validator).
:::
### Delete or add form items dynamically
:::demo In addition to passing all validation rules at once on the form component, you can also pass the validation rules or delete rules on a single form field dynamically.
```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="120px" class="demo-dynamic">
<el-form-item
prop="email"
label="Email"
:rules="[
{ required: true, message: 'Please input email address', trigger: 'blur' },
{ type: 'email', message: 'Please input correct email address', trigger: ['blur', 'change'] }
]"
>
<el-input v-model="dynamicValidateForm.email"></el-input>
</el-form-item>
<el-form-item
v-for="(domain, index) in dynamicValidateForm.domains"
:label="'Domain' + index"
:key="domain.key"
:prop="'domains.' + index + '.value'"
:rules="{
required: true, message: 'domain can not be null', trigger: 'blur'
}"
>
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">Submit</el-button>
<el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('dynamicValidateForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
dynamicValidateForm: {
domains: [{
key: 1,
value: ''
}],
email: ''
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item);
if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1);
}
},
addDomain() {
this.dynamicValidateForm.domains.push({
key: Date.now(),
value: ''
});
}
}
}
</script>
```
:::
### Number Validate
:::demo Number Validate need a `.number` modifier added on the input `v-model` bindingit's used to transform the string value to the number which is provided by Vuejs.
```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
<el-form-item
label="age"
prop="age"
:rules="[
{ required: true, message: 'age is required'},
{ type: 'number', message: 'age must be a number'}
]"
>
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">Submit</el-button>
<el-button @click="resetForm('numberValidateForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
numberValidateForm: {
age: ''
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
```
:::
:::tip
When an `el-form-item` is nested in another `el-form-item`, its label width will be `0`. You can set `label-width` on that `el-form-item` if needed.
:::
### Size control
All components in a Form inherit their `size` attribute from that Form. Similarly, FormItem also has a `size` attribute.
:::demo Still you can fine tune each component's `size` if you don't want that component to inherit its size from From or FormIten.
```html
<el-form ref="form" :model="sizeForm" label-width="120px" size="mini">
<el-form-item label="Activity name">
<el-input v-model="sizeForm.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="sizeForm.region" placeholder="please select your zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Activity time">
<el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker>
</el-col>
</el-form-item>
<el-form-item label="Activity type">
<el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="Online activities" name="type"></el-checkbox-button>
<el-checkbox-button label="Promotion activities" name="type"></el-checkbox-button>
</el-checkbox-group>
</el-form-item>
<el-form-item label="Resources">
<el-radio-group v-model="sizeForm.resource" size="medium">
<el-radio border label="Sponsor"></el-radio>
<el-radio border label="Venue"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item size="large">
<el-button type="primary" @click="onSubmit">Create</el-button>
<el-button>Cancel</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
sizeForm: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
}
};
},
methods: {
onSubmit() {
console.log('submit!');
}
}
};
</script>
```
:::
### Form Attributes
| Attribute | Description | Type | Accepted Values | Default |
| ---- | ----| ---- | ---- | ---- |
| model| data of form component | object | — | — |
| rules | validation rules of form | object | — | — |
| inline | whether the form is inline | boolean | — | false |
| label-position | position of label. If set to 'left' or 'right', `label-width` prop is also required | string | left / right / top | right |
| label-width | width of label, e.g. '50px'. All its direct child form items will inherit this value. Width `auto` is supported. | string | — | — |
| label-suffix | suffix of the label | string | — | — |
| hide-required-asterisk | whether required fields should have a red asterisk (star) beside their labels | boolean | — | false |
| show-message | whether to show the error message | boolean | — | true |
| inline-message | whether to display the error message inline with the form item | boolean | — | false |
| status-icon | whether to display an icon indicating the validation result | boolean | — | false |
| validate-on-rule-change | whether to trigger validation when the `rules` prop is changed | boolean | — | true |
| size | control the size of components in this form | string | medium / small / mini | — |
| disabled | whether to disabled all components in this form. If set to true, it cannot be overridden by its inner components' `disabled` prop | boolean | — | false |
### Form Methods
| Method | Description | Parameters |
| ---- | ---- | ---- |
| validate | validate the whole form. Takes a callback as a param. After validation, the callback will be executed with two params: a boolean indicating if the validation has passed, and an object containing all fields that fail the validation. Returns a promise if callback is omitted | Function(callback: Function(boolean, object)) |
| validateField | validate one or several form items | Function(props: string \| array, callback: Function(errorMessage: string)) |
| resetFields | reset all the fields and remove validation result | — |
| clearValidate | clear validation message for certain fields. The parameter is prop name or an array of prop names of the form items whose validation messages will be removed. When omitted, all fields' validation messages will be cleared | Function(props: string \| array) |
### Form Events
| Event Name | Description | Parameters |
|----------- |------------ |----------- |
| validate | triggers after a form item is validated | prop name of the form item being validated, whether validation is passed and the error message if not |
### Form-Item Attributes
| Attribute | Description | Type | Accepted Values | Default |
| ---- | ----| ---- | ---- | ---- |
| prop | a key of `model`. In the use of validate and resetFields method, the attribute is required | string | keys of model that passed to `form` |
| label | label | string | — | — |
| label-width | width of label, e.g. '50px'. Width `auto` is supported. | string | — | — |
| required | whether the field is required or not, will be determined by validation rules if omitted | boolean | — | false |
| rules | validation rules of form | object | — | — |
| error | field error message, set its value and the field will validate error and show this message immediately | string | — | — |
| show-message | whether to show the error message | boolean | — | true |
| inline-message | inline style validate message | boolean | — | false |
| size | control the size of components in this form-item | string | medium / small / mini | - |
### Form-Item Slot
| Name | Description |
|------|--------|
| — | content of Form Item |
| label | content of label |
### Form-Item Scoped Slot
| Name | Description |
|---------------|-------------|
| error | Custom content to display validation message. The scope parameter is { error } |
### Form-Item Methods
| Method | Description | Parameters |
| ---- | ---- | ---- |
| resetField | reset current field and remove validation result | — |
| clearValidate | remove validation status of the field | - |

226
examples/docs/en-US/i18n.md Normal file
View File

@@ -0,0 +1,226 @@
## Internationalization
The default language of Element is Chinese. If you wish to use another language, you'll need to do some i18n configuration. In your entry file, if you are importing Element entirely:
```javascript
import Vue from 'vue'
import ElementUI from 'element-ui'
import locale from 'element-ui/lib/locale/lang/en'
Vue.use(ElementUI, { locale })
```
Or if you are importing Element on demand:
```javascript
import Vue from 'vue'
import { Button, Select } from 'element-ui'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'
// configure language
locale.use(lang)
// import components
Vue.component(Button.name, Button)
Vue.component(Select.name, Select)
```
The Chinese language pack is imported by default, even if you're using another language. But with `NormalModuleReplacementPlugin` provided by webpack you can replace default locale:
webpack.config.js
```javascript
{
plugins: [
new webpack.NormalModuleReplacementPlugin(/element-ui[\/\\]lib[\/\\]locale[\/\\]lang[\/\\]zh-CN/, 'element-ui/lib/locale/lang/en')
]
}
```
## Compatible with `vue-i18n@5.x`
Element is compatible with [vue-i18n@5.x](https://github.com/kazupon/vue-i18n), which makes multilingual switching even easier.
```javascript
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Element from 'element-ui'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
Vue.use(Element)
Vue.config.lang = 'zh-cn'
Vue.locale('zh-cn', zhLocale)
Vue.locale('en', enLocale)
```
## Compatible with other i18n plugins
Element may not be compatible with i18n plugins other than vue-i18n, but you can customize how Element processes i18n.
```javascript
import Vue from 'vue'
import Element from 'element-ui'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(Element, {
i18n: function (path, options) {
// ...
}
})
```
## Compatible with `vue-i18n@6.x`
You need to manually handle it for compatibility with `6.x`.
```javascript
import Vue from 'vue'
import Element from 'element-ui'
import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
const messages = {
en: {
message: 'hello',
...enLocale // Or use `Object.assign({ message: 'hello' }, enLocale)`
},
zh: {
message: '你好',
...zhLocale // Or use `Object.assign({ message: '你好' }, zhLocale)`
}
}
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: 'en', // set locale
messages, // set locale messages
})
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value)
})
new Vue({ i18n }).$mount('#app')
```
## Custom i18n in on-demand components
```js
import Vue from 'vue'
import DatePicker from 'element/lib/date-picker'
import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import ElementLocale from 'element-ui/lib/locale'
Vue.use(VueI18n)
Vue.use(DatePicker)
const messages = {
en: {
message: 'hello',
...enLocale
},
zh: {
message: '你好',
...zhLocale
}
}
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: 'en', // set locale
messages, // set locale messages
})
ElementLocale.i18n((key, value) => i18n.t(key, value))
```
## Import via CDN
```html
<script src="//unpkg.com/vue"></script>
<script src="//unpkg.com/element-ui"></script>
<script src="//unpkg.com/element-ui/lib/umd/locale/en.js"></script>
<script>
ELEMENT.locale(ELEMENT.lang.en)
</script>
```
Compatible with `vue-i18n`
```html
<script src="//unpkg.com/vue"></script>
<script src="//unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
<script src="//unpkg.com/element-ui"></script>
<script src="//unpkg.com/element-ui/lib/umd/locale/zh-CN.js"></script>
<script src="//unpkg.com/element-ui/lib/umd/locale/en.js"></script>
<script>
Vue.locale('en', ELEMENT.lang.en)
Vue.locale('zh-cn', ELEMENT.lang.zhCN)
</script>
```
Currently Element ships with the following languages:
<ul class="language-list">
<li>Simplified Chinese (zh-CN)</li>
<li>English (en)</li>
<li>German (de)</li>
<li>Portuguese (pt)</li>
<li>Spanish (es)</li>
<li>Danish (da)</li>
<li>French (fr)</li>
<li>Norwegian (nb-NO)</li>
<li>Traditional Chinese (zh-TW)</li>
<li>Italian (it)</li>
<li>Korean (ko)</li>
<li>Japanese (ja)</li>
<li>Dutch (nl)</li>
<li>Vietnamese (vi)</li>
<li>Russian (ru-RU)</li>
<li>Turkish (tr-TR)</li>
<li>Brazilian Portuguese (pt-br)</li>
<li>Farsi (fa)</li>
<li>Thai (th)</li>
<li>Indonesian (id)</li>
<li>Bulgarian (bg)</li>
<li>Polish (pl)</li>
<li>Finnish (fi)</li>
<li>Swedish (sv-SE)</li>
<li>Greek (el)</li>
<li>Slovak (sk)</li>
<li>Catalunya (ca)</li>
<li>Czech (cs-CZ)</li>
<li>Ukrainian (ua)</li>
<li>Turkmen (tk)</li>
<li>Tamil (ta)</li>
<li>Latvian (lv)</li>
<li>Afrikaans (af-ZA)</li>
<li>Estonian (ee)</li>
<li>Slovenian (sl)</li>
<li>Arabic (ar)</li>
<li>Hebrew (he)</li>
<li>Lithuanian (lt)</li>
<li>Mongolian (mn)</li>
<li>Kazakh (kz)</li>
<li>Hungarian (hu)</li>
<li>Romanian (ro)</li>
<li>Kurdish (ku)</li>
<li>Uighur (ug-CN)</li>
<li>Khmer (km)</li>
<li>Serbian (sr)</li>
<li>Basque (eu)</li>
<li>Kyrgyz (kg)</li>
<li>Armenian (hy)</li>
<li>Croatian (hr)</li>
<li>Esperanto (eo)</li>
</ul>
If your target language is not included, you are more than welcome to contribute: just add another language config [here](https://github.com/ElemeFE/element/tree/dev/src/locale/lang) and create a pull request.

View File

@@ -0,0 +1,29 @@
## Icon
Element provides a set of common icons.
### Basic usage
Just assign the class name to `el-icon-iconName`.
:::demo
```html
<i class="el-icon-edit"></i>
<i class="el-icon-share"></i>
<i class="el-icon-delete"></i>
<el-button type="primary" icon="el-icon-search">Search</el-button>
```
:::
### Icons
<ul class="icon-list">
<li v-for="name in $icon" :key="name">
<span>
<i :class="'el-icon-' + name"></i>
<span class="icon-name">{{'el-icon-' + name}}</span>
</span>
</li>
</ul>

View File

@@ -0,0 +1,163 @@
## Image
Besides the native features of img, support lazy load, custom placeholder and load failure, etc.
### Basic Usage
:::demo Indicate how the image should be resized to fit its container by `fit`, same as native [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit)。
```html
<div class="demo-image">
<div class="block" v-for="fit in fits" :key="fit">
<span class="demonstration">{{ fit }}</span>
<el-image
style="width: 100px; height: 100px"
:src="url"
:fit="fit"></el-image>
</div>
</div>
<script>
export default {
data() {
return {
fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
}
}
}
</script>
```
:::
### Placeholder
:::demo Custom placeholder content when image hasn't loaded yet by `slot = placeholder`
```html
<div class="demo-image__placeholder">
<div class="block">
<span class="demonstration">Default</span>
<el-image :src="src"></el-image>
</div>
<div class="block">
<span class="demonstration">Custom</span>
<el-image :src="src">
<div slot="placeholder" class="image-slot">
Loading<span class="dot">...</span>
</div>
</el-image>
</div>
</div>
<script>
export default {
data() {
return {
src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
}
}
}
</script>
```
:::
### Load Failed
:::demo Custom failed content when error occurs to image load by `slot = error`
```html
<div class="demo-image__error">
<div class="block">
<span class="demonstration">Default</span>
<el-image></el-image>
</div>
<div class="block">
<span class="demonstration">Custom</span>
<el-image>
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
</div>
</div>
```
:::
### Lazy Load
:::demo Use lazy load by `lazy = true`. Image will load until scroll into view when set. You can indicate scroll container that adds scroll listener to by `scroll-container`. If undefined, will be the nearest parent container whose overflow property is auto or scroll.
```html
<div class="demo-image__lazy">
<el-image v-for="url in urls" :key="url" :src="url" lazy></el-image>
</div>
<script>
export default {
data() {
return {
urls: [
'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
]
}
}
}
</script>
```
:::
### Image Preview
:::demo allow big image preview by setting `previewSrcList` prop.
```html
<div class="demo-image__preview">
<el-image
style="width: 100px; height: 100px"
:src="url"
:preview-src-list="srcList">
</el-image>
</div>
<script>
export default {
data() {
return {
url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
srcList: [
'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
]
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted values | Default |
|---------- |-------- |---------- |------------- |-------- |
| src | Image source, same as native | string | — | - |
| fit | Indicate how the image should be resized to fit its container, same as [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) | string | fill / contain / cover / none / scale-down | - |
| alt | Native alt | string | - | - |
| referrer-policy | Native referrerPolicy | string | - | - |
| lazy | Whether to use lazy load | boolean | — | false |
| scroll-container | The container to add scroll listener when using lazy load | string / HTMLElement | — | The nearest parent container whose overflow property is auto or scroll |
| preview-src-list | allow big image preview | Array | — | - |
| z-index | set image preview z-index | Number | — | 2000 |
### Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| load | Same as native load | (e: Event) |
| error | Same as native error | (e: Error) |
### Slots
| Slot Name | Description |
|---------|-------------|
| placeholder | Triggers when image load |
| error | Triggers when image load failed |

View File

@@ -0,0 +1,87 @@
## InfiniteScroll
Load more data while reach bottom of the page
### Basic usage
Add `v-infinite-scroll` to the list to automatically execute loading method when scrolling to the bottom.
:::demo
```html
<template>
<ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
<li v-for="i in count" class="infinite-list-item">{{ i }}</li>
</ul>
</template>
<script>
export default {
data () {
return {
count: 0
}
},
methods: {
load () {
this.count += 2
}
}
}
</script>
```
:::
### Disable Loading
:::demo
```html
<template>
<div class="infinite-list-wrapper" style="overflow:auto">
<ul
class="list"
v-infinite-scroll="load"
infinite-scroll-disabled="disabled">
<li v-for="i in count" class="list-item">{{ i }}</li>
</ul>
<p v-if="loading">Loading...</p>
<p v-if="noMore">No more</p>
</div>
</template>
<script>
export default {
data () {
return {
count: 10,
loading: false
}
},
computed: {
noMore () {
return this.count >= 20
},
disabled () {
return this.loading || this.noMore
}
},
methods: {
load () {
this.loading = true
setTimeout(() => {
this.count += 2
this.loading = false
}, 2000)
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted values | Default |
| -------------- | ------------------------------ | --------- | ------------------------------------ | ------- |
| infinite-scroll-disabled | is disabled | boolean | - |false |
| infinite-scroll-delay | throttle delay (ms) | number | - |200 |
| infinite-scroll-distance| trigger distance (px) | number |- |0 |
| infinite-scroll-immediate |Whether to execute the loading method immediately, in case the content cannot be filled up in the initial state. | boolean | - |true |

View File

@@ -0,0 +1,200 @@
## InputNumber
Input numerical values with a customizable range.
### Basic usage
:::demo Bind a variable to `v-model` in `<el-input-number>` element and you are set.
```html
<template>
<el-input-number v-model="num" @change="handleChange" :min="1" :max="10"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
};
},
methods: {
handleChange(value) {
console.log(value)
}
}
};
</script>
```
:::
### Disabled
:::demo The `disabled` attribute accepts a `boolean`, and if the value is `true`, the component is disabled. If you just need to control the value within a range, you can add `min` attribute to set the minimum value and `max` to set the maximum value. By default, the minimum value is `0`.
```html
<template>
<el-input-number v-model="num" :disabled="true"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
}
}
};
</script>
```
:::
### Steps
Allows you to define incremental steps.
:::demo Add `step` attribute to set the step.
```html
<template>
<el-input-number v-model="num" :step="2"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 5
}
}
};
</script>
```
:::
### Step strictly
:::demo The `step-strictly` attribute accepts a `boolean`. if this attribute is `true`, input value can only be multiple of step.
```html
<template>
<el-input-number v-model="num" :step="2" step-strictly></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 2
}
}
};
</script>
```
:::
### Precision
:::demo Add `precision` attribute to set the precision of input value.
```html
<template>
<el-input-number v-model="num" :precision="2" :step="0.1" :max="10"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
}
}
};
</script>
```
:::
:::tip
The value of `precision` must be a non negative integer and should not be less than the decimal places of `step`.
:::
### Size
Use attribute `size` to set additional sizes with `medium`, `small` or `mini`.
:::demo
```html
<template>
<el-input-number v-model="num1"></el-input-number>
<el-input-number size="medium" v-model="num2"></el-input-number>
<el-input-number size="small" v-model="num3"></el-input-number>
<el-input-number size="mini" v-model="num4"></el-input-number>
</template>
<script>
export default {
data() {
return {
num1: 1,
num2: 1,
num3: 1,
num4: 1
}
}
};
</script>
```
:::
### Controls Position
:::demo Set `controls-position` to decide the position of control buttons.
```html
<template>
<el-input-number v-model="num" controls-position="right" @change="handleChange" :min="1" :max="10"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|----| ----| ---| ----| -----|
|value / v-model | binding value| number | — | 0 |
|min | the minimum allowed value | number | — | `-Infinity` |
|max | the maximum allowed value | number | — | `Infinity` |
|step | incremental step | number | — | 1 |
|step-strictly | whether input value can only be multiple of step | boolean | — | false |
|precision | precision of input value | number | — | — |
|size | size of the component | string | large/small| — |
|disabled| whether the component is disabled | boolean | — | false |
|controls| whether to enable the control buttons | boolean | — | true |
|controls-position | position of the control buttons | string | right | - |
|name | same as `name` in native input | string | — | — |
|label | label text | string | — | — |
|placeholder | placeholder in input | string | - | - |
### Events
| Event Name | Description | Parameters |
|----| ---- | -----|
|change | triggers when the value changes | currentValue, oldValue |
| blur | triggers when Input blurs | (event: Event) |
| focus | triggers when Input focuses | (event: Event) |
### Methods
| Method | Description | Parameters |
|------|--------|-------|
| focus | focus the Input component | - |
| select | select the text in input element | — |

View File

@@ -0,0 +1,668 @@
## Input
Input data using mouse or keyboard.
:::warning
Input is a controlled component, it **always shows Vue binding value**.
Under normal circumstances, `input` event should be handled. Its handler should update component's binding value (or use `v-model`). Otherwise, input box's value will not change.
Do not support `v-model` modifiers.
:::
### Basic usage
:::demo
```html
<el-input placeholder="Please input" v-model="input"></el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Disabled
:::demo Disable the Input with the `disabled` attribute.
```html
<el-input
placeholder="Please input"
v-model="input"
:disabled="true">
</el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Clearable
:::demo Make the Input clearable with the `clearable` attribute.
```html
<el-input
placeholder="Please input"
v-model="input"
clearable>
</el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Password box
:::demo Make a toggleable password Input with the `show-password` attribute.
```html
<el-input placeholder="Please input password" v-model="input" show-password></el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Input with icon
Add an icon to indicate input type.
:::demo To add icons in Input, you can simply use `prefix-icon` and `suffix-icon` attributes. Also, the `prefix` and `suffix` named slots works as well.
```html
<div class="demo-input-suffix">
<span class="demo-input-label">Using attributes</span>
<el-input
placeholder="Pick a date"
suffix-icon="el-icon-date"
v-model="input1">
</el-input>
<el-input
placeholder="Type something"
prefix-icon="el-icon-search"
v-model="input2">
</el-input>
</div>
<div class="demo-input-suffix">
<span class="demo-input-label">Using slots</span>
<el-input
placeholder="Pick a date"
v-model="input3">
<i slot="suffix" class="el-input__icon el-icon-date"></i>
</el-input>
<el-input
placeholder="Type something"
v-model="input4">
<i slot="prefix" class="el-input__icon el-icon-search"></i>
</el-input>
</div>
<style>
.demo-input-label {
display: inline-block;
width: 130px;
}
</style>
<script>
export default {
data() {
return {
input1: '',
input2: '',
input3: '',
input4: ''
}
}
}
</script>
```
:::
### Textarea
Resizable for entering multiple lines of text information. Add attribute `type="textarea"` to change `input` into native `textarea`.
:::demo Control the height by setting the `rows` prop.
```html
<el-input
type="textarea"
:rows="2"
placeholder="Please input"
v-model="textarea">
</el-input>
<script>
export default {
data() {
return {
textarea: ''
}
}
}
</script>
```
:::
### Autosize Textarea
Setting the `autosize` prop for a textarea type of Input makes the height to automatically adjust based on the content. An options object can be provided to `autosize` to specify the minimum and maximum number of lines the textarea can automatically adjust.
:::demo
```html
<el-input
type="textarea"
autosize
placeholder="Please input"
v-model="textarea1">
</el-input>
<div style="margin: 20px 0;"></div>
<el-input
type="textarea"
:autosize="{ minRows: 2, maxRows: 4}"
placeholder="Please input"
v-model="textarea2">
</el-input>
<script>
export default {
data() {
return {
textarea1: '',
textarea2: ''
}
}
}
</script>
```
:::
### Mixed input
Prepend or append an element, generally a label or a button.
:::demo Use `slot` to distribute elements that prepend or append to Input.
```html
<div>
<el-input placeholder="Please input" v-model="input1">
<template slot="prepend">Http://</template>
</el-input>
</div>
<div style="margin-top: 15px;">
<el-input placeholder="Please input" v-model="input2">
<template slot="append">.com</template>
</el-input>
</div>
<div style="margin-top: 15px;">
<el-input placeholder="Please input" v-model="input3" class="input-with-select">
<el-select v-model="select" slot="prepend" placeholder="Select">
<el-option label="Restaurant" value="1"></el-option>
<el-option label="Order No." value="2"></el-option>
<el-option label="Tel" value="3"></el-option>
</el-select>
<el-button slot="append" icon="el-icon-search"></el-button>
</el-input>
</div>
<style>
.el-select .el-input {
width: 110px;
}
.input-with-select .el-input-group__prepend {
background-color: #fff;
}
</style>
<script>
export default {
data() {
return {
input1: '',
input2: '',
input3: '',
select: ''
}
}
}
</script>
```
:::
### Sizes
:::demo Add `size` attribute to change the size of Input. In addition to the default size, there are three other options: `large`, `small` and `mini`.
```html
<div class="demo-input-size">
<el-input
placeholder="Please Input"
v-model="input1">
</el-input>
<el-input
size="medium"
placeholder="Please Input"
v-model="input2">
</el-input>
<el-input
size="small"
placeholder="Please Input"
v-model="input3">
</el-input>
<el-input
size="mini"
placeholder="Please Input"
v-model="input4">
</el-input>
</div>
<script>
export default {
data() {
return {
input1: '',
input2: '',
input3: '',
input4: ''
}
}
}
</script>
```
:::
### Autocomplete
You can get some recommended tips based on the current input.
:::demo Autocomplete component provides input suggestions. The `fetch-suggestions` attribute is a method that returns suggested input. In this example, `querySearch(queryString, cb)` returns suggestions to Autocomplete via `cb(data)` when suggestions are ready.
```html
<el-row class="demo-autocomplete">
<el-col :span="12">
<div class="sub-title">list suggestions when activated</div>
<el-autocomplete
class="inline-input"
v-model="state1"
:fetch-suggestions="querySearch"
placeholder="Please Input"
@select="handleSelect"
></el-autocomplete>
</el-col>
<el-col :span="12">
<div class="sub-title">list suggestions on input</div>
<el-autocomplete
class="inline-input"
v-model="state2"
:fetch-suggestions="querySearch"
placeholder="Please Input"
:trigger-on-focus="false"
@select="handleSelect"
></el-autocomplete>
</el-col>
</el-row>
<script>
export default {
data() {
return {
links: [],
state1: '',
state2: ''
};
},
methods: {
querySearch(queryString, cb) {
var links = this.links;
var results = queryString ? links.filter(this.createFilter(queryString)) : links;
// call callback function to return suggestions
cb(results);
},
createFilter(queryString) {
return (link) => {
return (link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
};
},
loadAll() {
return [
{ "value": "vue", "link": "https://github.com/vuejs/vue" },
{ "value": "element", "link": "https://github.com/ElemeFE/element" },
{ "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
{ "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
{ "value": "vuex", "link": "https://github.com/vuejs/vuex" },
{ "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
{ "value": "babel", "link": "https://github.com/babel/babel" }
];
},
handleSelect(item) {
console.log(item);
}
},
mounted() {
this.links = this.loadAll();
}
}
</script>
```
:::
### Custom template
Customize how suggestions are displayed.
:::demo Use `scoped slot` to customize suggestion items. In the scope, you can access the suggestion object via the `item` key.
```html
<el-autocomplete
popper-class="my-autocomplete"
v-model="state"
:fetch-suggestions="querySearch"
placeholder="Please input"
@select="handleSelect">
<i
class="el-icon-edit el-input__icon"
slot="suffix"
@click="handleIconClick">
</i>
<template slot-scope="{ item }">
<div class="value">{{ item.value }}</div>
<span class="link">{{ item.link }}</span>
</template>
</el-autocomplete>
<style>
.my-autocomplete {
li {
line-height: normal;
padding: 7px;
.value {
text-overflow: ellipsis;
overflow: hidden;
}
.link {
font-size: 12px;
color: #b4b4b4;
}
}
}
</style>
<script>
export default {
data() {
return {
links: [],
state: ''
};
},
methods: {
querySearch(queryString, cb) {
var links = this.links;
var results = queryString ? links.filter(this.createFilter(queryString)) : links;
// call callback function to return suggestion objects
cb(results);
},
createFilter(queryString) {
return (link) => {
return (link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
};
},
loadAll() {
return [
{ "value": "vue", "link": "https://github.com/vuejs/vue" },
{ "value": "element", "link": "https://github.com/ElemeFE/element" },
{ "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
{ "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
{ "value": "vuex", "link": "https://github.com/vuejs/vuex" },
{ "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
{ "value": "babel", "link": "https://github.com/babel/babel" }
];
},
handleSelect(item) {
console.log(item);
},
handleIconClick(ev) {
console.log(ev);
}
},
mounted() {
this.links = this.loadAll();
}
}
</script>
```
:::
### Remote search
Search data from server-side.
:::demo
```html
<el-autocomplete
v-model="state"
:fetch-suggestions="querySearchAsync"
placeholder="Please input"
@select="handleSelect"
></el-autocomplete>
<script>
export default {
data() {
return {
links: [],
state: '',
timeout: null
};
},
methods: {
loadAll() {
return [
{ "value": "vue", "link": "https://github.com/vuejs/vue" },
{ "value": "element", "link": "https://github.com/ElemeFE/element" },
{ "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
{ "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
{ "value": "vuex", "link": "https://github.com/vuejs/vuex" },
{ "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
{ "value": "babel", "link": "https://github.com/babel/babel" }
];
},
querySearchAsync(queryString, cb) {
var links = this.links;
var results = queryString ? links.filter(this.createFilter(queryString)) : links;
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
cb(results);
}, 3000 * Math.random());
},
createFilter(queryString) {
return (link) => {
return (link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
};
},
handleSelect(item) {
console.log(item);
}
},
mounted() {
this.links = this.loadAll();
}
};
</script>
```
:::
### Limit length
:::demo `maxlength` and `minlength` are attributes of native input, they declare a limit on the number of characters a user can input. The "number of characters" is measured using JavaScript string length.Setting the `maxlength` prop for a text or textarea type of Input can limit the length of input value, allows you to show word count by setting `show-word-limit` to `true` at the same time.
```html
<el-input
type="text"
placeholder="Please input"
v-model="text"
maxlength="10"
show-word-limit
>
</el-input>
<div style="margin: 20px 0;"></div>
<el-input
type="textarea"
placeholder="Please input"
v-model="textarea"
maxlength="30"
show-word-limit
>
</el-input>
<script>
export default {
data() {
return {
text: '',
textarea: ''
}
}
}
</script>
```
:::
### Input Attributes
| Attribute | Description | Type | Accepted Values | Default |
| ----| ----| ----| ---- | ----- |
|type| type of input | string | text, textarea and other [native input types](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types) | text |
|value / v-model| binding value | string / number| — | — |
|maxlength| same as `maxlength` in native input | number| — | — |
|minlength| same as `minlength` in native input | number | — | — |
|show-word-limit | whether show word countonly works when `type` is 'text' or 'textarea' | boolean | — | false |
|placeholder| placeholder of Input| string | — | — |
| clearable | whether to show clear button | boolean | — | false |
| show-password | whether to show toggleable password input| boolean | — | false |
|disabled | whether Input is disabled | boolean | — | false |
|size | size of Input, works when `type` is not 'textarea' | string | medium / small / mini | — |
| prefix-icon | prefix icon class | string | — | — |
| suffix-icon | suffix icon class | string | — | — |
|rows | number of rows of textarea, only works when `type` is 'textarea' | number | — | 2 |
|autosize | whether textarea has an adaptive height, only works when `type` is 'textarea'. Can accept an object, e.g. { minRows: 2, maxRows: 6 } | boolean / object | — | false |
|autocomplete | same as `autocomplete` in native input | string | on/off | off |
|auto-complete | @DEPRECATED in next major version | string | on/off | off |
|name | same as `name` in native input | string | — | — |
| readonly | same as `readonly` in native input | boolean | — | false |
|max | same as `max` in native input | — | — | — |
|min | same as `min` in native input | — | — | — |
|step| same as `step` in native input | — | — | — |
|resize| control the resizability | string | none, both, horizontal, vertical | — |
|autofocus | same as `autofocus` in native input | boolean | — | false |
|form | same as `form` in native input | string | — | — |
| label | label text | string | — | — |
| tabindex | input tabindex | string | - | - |
| validate-event | whether to trigger form validation | boolean | - | true |
### Input slots
| Name | Description |
|------|--------|
| prefix | content as Input prefix, only works when `type` is 'text' |
| suffix | content as Input suffix, only works when `type` is 'text' |
| prepend | content to prepend before Input, only works when `type` is 'text' |
| append | content to append after Input, only works when `type` is 'text' |
### Input Events
| Event Name | Description | Parameters |
|----| ----| ----|
| blur | triggers when Input blurs | (event: Event) |
| focus | triggers when Input focuses | (event: Event) |
| change | triggers only when the input box loses focus or the user presses Enter | (value: string \| number) |
| input | triggers when the Input value change | (value: string \| number) |
| clear | triggers when the Input is cleared by clicking the clear button | — |
### Input Methods
| Method | Description | Parameters |
|------|--------|-------|
| focus | focus the input element | — |
| blur | blur the input element | — |
| select | select the text in input element | — |
### Autocomplete Attributes
Attribute | Description | Type | Options | Default
|----| ----| ----| ---- | -----|
|placeholder| the placeholder of Autocomplete| string | — | — |
| clearable | whether to show clear button | boolean | — | false |
|disabled | whether Autocomplete is disabled | boolean | — | false|
| value-key | key name of the input suggestion object for display | string | — | value |
|icon | icon name | string | — | — |
|value | binding value | string | — | — |
| debounce | debounce delay when typing, in milliseconds | number | — | 300 |
| placement | placement of the popup menu | string | top / top-start / top-end / bottom / bottom-start / bottom-end | bottom-start |
|fetch-suggestions | a method to fetch input suggestions. When suggestions are ready, invoke `callback(data:[])` to return them to Autocomplete | Function(queryString, callback) | — | — |
| popper-class | custom class name for autocomplete's dropdown | string | — | — |
| trigger-on-focus | whether show suggestions when input focus | boolean | — | true |
| name | same as `name` in native input | string | — | — |
| select-when-unmatched | whether to emit a `select` event on enter when there is no autocomplete match | boolean | — | false |
| label | label text | string | — | — |
| prefix-icon | prefix icon class | string | — | — |
| suffix-icon | suffix icon class | string | — | — |
| hide-loading | whether to hide the loading icon in remote search | boolean | — | false |
| popper-append-to-body | whether to append the dropdown to body. If the positioning of the dropdown is wrong, you can try to set this prop to false | boolean | - | true |
| highlight-first-item | whether to highlight first item in remote search suggestions by default | boolean | — | false |
### Autocomplete Slots
| Name | Description |
|------|--------|
| prefix | content as Input prefix |
| suffix | content as Input suffix |
| prepend | content to prepend before Input |
| append | content to append after Input |
### Autocomplete Scoped Slot
| Name | Description |
|------|--------|
| — | Custom content for input suggestions. The scope parameter is { item } |
### Autocomplete Events
| Event Name | Description | Parameters |
|----| ----| ----|
|select | triggers when a suggestion is clicked | suggestion being clicked |
| change | triggers when the icon inside Input value change | (value: string \| number) |
### Autocomplete Methods
| Method | Description | Parameters |
|------|--------|-------|
| focus | focus the input element | — |

View File

@@ -0,0 +1,35 @@
## Installation
### npm
Installing with npm is recommended and it works seamlessly with [webpack](https://webpack.js.org/).
```shell
npm i element-ui -S
```
### CDN
Get the latest version from [unpkg.com/element-ui](https://unpkg.com/element-ui/) , and import JavaScript and CSS file in your page.
```html
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
```
:::tip
We recommend our users to lock Element's version when using CDN. Please refer to [unpkg.com](https://unpkg.com) for more information.
:::
### Hello world
If you are using CDN, a hello-world page is easy with Element. [Online Demo](https://codepen.io/ziyoung/pen/rRKYpd)
<iframe height="265" style="width: 100%;" scrolling="no" title="Element demo" src="//codepen.io/ziyoung/embed/rRKYpd/?height=265&theme-id=light&default-tab=html" frameborder="no" allowtransparency="true" allowfullscreen="true">
See the Pen <a href='https://codepen.io/ziyoung/pen/rRKYpd/'>Element demo</a> by hetech
(<a href='https://codepen.io/ziyoung'>@ziyoung</a>) on <a href='https://codepen.io'>CodePen</a>.
</iframe>
If you are using npm and wish to apply webpack, please continue to the next page: [Quick Start](/#/en-US/component/quickstart).

View File

@@ -0,0 +1,357 @@
## Layout
Quickly and easily create layouts with the basic 24-column.
### Basic layout
Create basic grid layout using columns.
:::demo With `row` and `col`, we can easily manipulate the layout using the `span` attribute.
```html
<el-row>
<el-col :span="24"><div class="grid-content bg-purple-dark"></div></el-col>
</el-row>
<el-row>
<el-col :span="12"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="12"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<el-row>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<el-row>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Column spacing
Column spacing is supported.
:::demo Row provides `gutter` attribute to specify spacings between columns, and its default value is 0.
```html
<el-row :gutter="20">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Hybrid layout
Form a more complex hybrid layout by combining the basic 1/24 columns.
:::demo
```html
<el-row :gutter="20">
<el-col :span="16"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="16"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Column offset
You can specify column offsets.
:::demo You can specify the number of column offset by setting the value of `offset` attribute of Col.
```html
<el-row :gutter="20">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12" :offset="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Alignment
Use the flex layout to make flexible alignment of columns.
:::demo You can enable flex layout by setting `type` attribute to 'flex', and define the layout of child elements by setting `justify` attribute with start, center, end, space-between or space-around.
```html
<el-row type="flex" class="row-bg">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="center">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="end">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="space-between">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="space-around">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Responsive Layout
Taking example by Bootstrap's responsive design, five breakpoints are preset: xs, sm, md, lg and xl.
:::demo
```html
<el-row :gutter="10">
<el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple"></div></el-col>
<el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple"></div></el-col>
<el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<style>
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
</style>
```
:::
### Utility classes for hiding elements
Additionally, Element provides a series of classes for hiding elements under certain conditions. These classes can be added to any DOM elements or custom components. You need to import the following CSS file to use these classes:
```js
import 'element-ui/lib/theme-chalk/display.css';
```
The classes are:
- `hidden-xs-only` - hide when on extra small viewports only
- `hidden-sm-only` - hide when on small viewports and down
- `hidden-sm-and-down` - hide when on small viewports and down
- `hidden-sm-and-up` - hide when on small viewports and up
- `hidden-md-only` - hide when on medium viewports only
- `hidden-md-and-down` - hide when on medium viewports and down
- `hidden-md-and-up` - hide when on medium viewports and up
- `hidden-lg-only` - hide when on large viewports only
- `hidden-lg-and-down` - hide when on large viewports and down
- `hidden-lg-and-up` - hide when on large viewports and up
- `hidden-xl-only` - hide when on extra large viewports only
### Row Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| gutter | grid spacing | number | — | 0 |
| type | layout mode, you can use flex, works in modern browsers | string | — | — |
| justify | horizontal alignment of flex layout | string | start/end/center/space-around/space-between | start |
| align | vertical alignment of flex layout | string | top/middle/bottom | top |
| tag | custom element tag | string | * | div |
### Col Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| span | number of column the grid spans | number | — | 24 |
| offset | number of spacing on the left side of the grid | number | — | 0 |
| push | number of columns that grid moves to the right | number | — | 0 |
| pull | number of columns that grid moves to the left | number | — | 0 |
| xs | `<768px` Responsive columns or column props object | number/object (e.g. {span: 4, offset: 4}) | — | — |
| sm | `≥768px` Responsive columns or column props object | number/object (e.g. {span: 4, offset: 4}) | — | — |
| md | `≥992px` Responsive columns or column props object | number/object (e.g. {span: 4, offset: 4}) | — | — |
| lg | `≥1200px` Responsive columns or column props object | number/object (e.g. {span: 4, offset: 4}) | — | — |
| xl | `≥1920px` Responsive columns or column props object | number/object (e.g. {span: 4, offset: 4}) | — | — |
| tag | custom element tag | string | * | div |

View File

@@ -0,0 +1,77 @@
## Link
Text hyperlink
### Basic
Basic text link
:::demo
```html
<div>
<el-link href="https://element.eleme.io" target="_blank">default</el-link>
<el-link type="primary">primary</el-link>
<el-link type="success">success</el-link>
<el-link type="warning">warning</el-link>
<el-link type="danger">danger</el-link>
<el-link type="info">info</el-link>
</div>
```
:::
### Disabled
Disabled state of link
:::demo
```html
<div>
<el-link disabled>default</el-link>
<el-link type="primary" disabled>primary</el-link>
<el-link type="success" disabled>success</el-link>
<el-link type="warning" disabled>warning</el-link>
<el-link type="danger" disabled>danger</el-link>
<el-link type="info" disabled>info</el-link>
</div>
```
:::
### Underline
Underline of link
:::demo
```html
<div>
<el-link :underline="false">Without Underline</el-link>
<el-link>With Underline</el-link>
</div>
```
:::
### Icon
Link with icon
:::demo
```html
<div>
<el-link icon="el-icon-edit">Edit</el-link>
<el-link>Check<i class="el-icon-view el-icon--right"></i> </el-link>
</div>
```
:::
### Attributes
| Attribute | Description | Type | Options | Default |
| --------- | ----------------------------------- | ------- | ------------------------------------------- | ------- |
| type | type | string | primary / success / warning / danger / info | default |
| underline | whether the component has underline | boolean | — | true |
| disabled | whether the component is disabled | boolean | — | false |
| href | same as native hyperlink's `href` | string | — | - |
| icon | class name of icon | string | — | - |

View File

@@ -0,0 +1,209 @@
## Loading
Show animation while loading data.
### Loading inside a container
Displays animation in a container (such as a table) while loading data.
:::demo Element provides two ways to invoke Loading: directive and service. For the custom directive `v-loading`, you just need to bind a `boolean` value to it. By default, the loading mask will append to the element where the directive is used. Adding the `body` modifier makes the mask append to the body element.
```html
<template>
<el-table
v-loading="loading"
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="Date"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="Name"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="Address">
</el-table-column>
</el-table>
</template>
<style>
body {
margin: 0;
}
</style>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-02',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-04',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-01',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}],
loading: true
};
}
};
</script>
```
:::
### Customization
You can customize loading text, loading spinner and background color.
:::demo Add attribute `element-loading-text` to the element on which `v-loading` is bound, and its value will be displayed under the spinner. Similarly, `element-loading-spinner` and `element-loading-background` are for customizing loading spinner class name and background color.
```html
<template>
<el-table
v-loading="loading"
element-loading-text="Loading..."
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0.8)"
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="Date"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="Name"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="Address">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-02',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-04',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-01',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}],
loading: true
};
}
};
</script>
```
:::
### Full screen loading
Show a full screen animation while loading data.
:::demo When used as a directive, a full screen Loading requires the `fullscreen` modifier, and it will be appended to body. In this case, if you wish to disable scrolling on body, you can add another modifier `lock`. When used as a service, Loading will be full screen by default.
```html
<template>
<el-button
type="primary"
@click="openFullScreen1"
v-loading.fullscreen.lock="fullscreenLoading">
As a directive
</el-button>
<el-button
type="primary"
@click="openFullScreen2">
As a service
</el-button>
</template>
<script>
export default {
data() {
return {
fullscreenLoading: false
}
},
methods: {
openFullScreen1() {
this.fullscreenLoading = true;
setTimeout(() => {
this.fullscreenLoading = false;
}, 2000);
},
openFullScreen2() {
const loading = this.$loading({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
setTimeout(() => {
loading.close();
}, 2000);
}
}
}
</script>
```
:::
### Service
You can also invoke Loading with a service. Import Loading service:
```javascript
import { Loading } from 'element-ui';
```
Invoke it:
```javascript
Loading.service(options);
```
The parameter `options` is the configuration of Loading, and its details can be found in the following table. `LoadingService` returns a Loading instance, and you can close it by invoking its `close` method:
```javascript
let loadingInstance = Loading.service(options);
this.$nextTick(() => { // Loading should be closed asynchronously
loadingInstance.close();
});
```
Note that in this case the full screen Loading is singleton. If a new full screen Loading is invoked before an existing one is closed, the existing full screen Loading instance will be returned instead of actually creating another Loading instance:
```javascript
let loadingInstance1 = Loading.service({ fullscreen: true });
let loadingInstance2 = Loading.service({ fullscreen: true });
console.log(loadingInstance1 === loadingInstance2); // true
```
Calling the `close` method on any one of them can close this full screen Loading.
If Element is imported entirely, a globally method `$loading` will be registered to Vue.prototype. You can invoke it like this: `this.$loading(options)`, and it also returns a Loading instance.
### Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| target | the DOM node Loading needs to cover. Accepts a DOM object or a string. If it's a string, it will be passed to `document.querySelector` to get the corresponding DOM node | object/string | — | document.body |
| body | same as the `body` modifier of `v-loading` | boolean | — | false |
| fullscreen | same as the `fullscreen` modifier of `v-loading` | boolean | — | true |
| lock | same as the `lock` modifier of `v-loading` | boolean | — | false |
| text | loading text that displays under the spinner | string | — | — |
| spinner | class name of the custom spinner | string | — | — |
| background | background color of the mask | string | — | — |
| customClass | custom class name for Loading | string | — | — |

298
examples/docs/en-US/menu.md Normal file
View File

@@ -0,0 +1,298 @@
## NavMenu
Menu that provides navigation for your website.
### Top bar
Top bar NavMenu can be used in a variety of scenarios.
:::demo By default Menu is vertical, but you can change it to horizontal by setting the mode prop to 'horizontal'. In addition, you can use the submenu component to create a second level menu. Menu provides `background-color`, `text-color` and `active-text-color` to customize the colors.
```html
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
<el-menu-item index="1">Processing Center</el-menu-item>
<el-submenu index="2">
<template slot="title">Workspace</template>
<el-menu-item index="2-1">item one</el-menu-item>
<el-menu-item index="2-2">item two</el-menu-item>
<el-menu-item index="2-3">item three</el-menu-item>
<el-submenu index="2-4">
<template slot="title">item four</template>
<el-menu-item index="2-4-1">item one</el-menu-item>
<el-menu-item index="2-4-2">item two</el-menu-item>
<el-menu-item index="2-4-3">item three</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="3" disabled>Info</el-menu-item>
<el-menu-item index="4"><a href="https://www.ele.me" target="_blank">Orders</a></el-menu-item>
</el-menu>
<div class="line"></div>
<el-menu
:default-active="activeIndex2"
class="el-menu-demo"
mode="horizontal"
@select="handleSelect"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<el-menu-item index="1">Processing Center</el-menu-item>
<el-submenu index="2">
<template slot="title">Workspace</template>
<el-menu-item index="2-1">item one</el-menu-item>
<el-menu-item index="2-2">item two</el-menu-item>
<el-menu-item index="2-3">item three</el-menu-item>
<el-submenu index="2-4">
<template slot="title">item four</template>
<el-menu-item index="2-4-1">item one</el-menu-item>
<el-menu-item index="2-4-2">item two</el-menu-item>
<el-menu-item index="2-4-3">item three</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="3" disabled>Info</el-menu-item>
<el-menu-item index="4"><a href="https://www.ele.me" target="_blank">Orders</a></el-menu-item>
</el-menu>
<script>
export default {
data() {
return {
activeIndex: '1',
activeIndex2: '1'
};
},
methods: {
handleSelect(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
```
:::
### Side bar
Vertical NavMenu with sub-menus.
:::demo You can use the el-menu-item-group component to create a menu group, and the name of the group is determined by the title prop or a named slot.
```html
<el-row class="tac">
<el-col :span="12">
<h5>Default colors</h5>
<el-menu
default-active="2"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span>Navigator One</span>
</template>
<el-menu-item-group title="Group One">
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item one</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">item four</template>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span>Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<i class="el-icon-document"></i>
<span>Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span>Navigator Four</span>
</el-menu-item>
</el-menu>
</el-col>
<el-col :span="12">
<h5>Custom colors</h5>
<el-menu
default-active="2"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span>Navigator One</span>
</template>
<el-menu-item-group title="Group One">
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item one</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">item four</template>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span>Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<i class="el-icon-document"></i>
<span>Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span>Navigator Four</span>
</el-menu-item>
</el-menu>
</el-col>
</el-row>
<script>
export default {
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
```
:::
### Collapse
Vertical NavMenu could be collapsed.
:::demo
```html
<el-radio-group v-model="isCollapse" style="margin-bottom: 20px;">
<el-radio-button :label="false">expand</el-radio-button>
<el-radio-button :label="true">collapse</el-radio-button>
</el-radio-group>
<el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose" :collapse="isCollapse">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span slot="title">Navigator One</span>
</template>
<el-menu-item-group>
<span slot="title">Group One</span>
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item two</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<span slot="title">item four</span>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span slot="title">Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<i class="el-icon-document"></i>
<span slot="title">Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span slot="title">Navigator Four</span>
</el-menu-item>
</el-menu>
<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
width: 200px;
min-height: 400px;
}
</style>
<script>
export default {
data() {
return {
isCollapse: true
};
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
```
:::
### Menu Attribute
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| mode | menu display mode | string | horizontal / vertical | vertical |
| collapse | whether the menu is collapsed (available only in vertical mode) | boolean | — | false |
| background-color | background color of Menu (hex format) | string | — | #ffffff |
| text-color | text color of Menu (hex format) | string | — | #303133 |
| active-text-color | text color of currently active menu item (hex format) | string | — | #409EFF |
| default-active | index of currently active menu | string | — | — |
| default-openeds | array that contains indexes of currently active sub-menus | Array | — | — |
| unique-opened | whether only one sub-menu can be active | boolean | — | false |
| menu-trigger | how sub-menus are triggered, only works when `mode` is 'horizontal' | string | hover / click | hover |
| router | whether `vue-router` mode is activated. If true, index will be used as 'path' to activate the route action | boolean | — | false |
| collapse-transition | whether to enable the collapse transition | boolean | — | true |
### Menu Methods
| Methods Name | Description | Parameters |
|---------- |-------- |---------- |
| open | open a specific sub-menu | index: index of the sub-menu to open |
| close | close a specific sub-menu | index: index of the sub-menu to close |
### Menu Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| select | callback function when menu is activated | index: index of activated menu, indexPath: index path of activated menu |
| open | callback function when sub-menu expands | index: index of expanded sub-menu, indexPath: index path of expanded sub-menu |
| close | callback function when sub-menu collapses | index: index of collapsed sub-menu, indexPath: index path of collapsed sub-menu |
### Menu-Item Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| click | callback function when menu-item is clicked | el: menu-item instance |
### SubMenu Attribute
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| index | unique identification | string | — | — |
| popper-class | custom class name for the popup menu | string | — | — |
| show-timeout | timeout before showing a sub-menu | number | — | 300 |
| hide-timeout | timeout before hiding a sub-menu | number | — | 300 |
| disabled | whether the sub-menu is disabled | boolean | — | false |
| popper-append-to-body | whether to append the popup menu to body. If the positioning of the menu is wrong, you can try setting this prop | boolean | - | level one Submenu: true / other Submenus: false |
### Menu-Item Attribute
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| index | unique identification | string/null | — | null |
| route | Vue Router object | object | — | — |
| disabled | whether disabled | boolean | — | false |
### Menu-Group Attribute
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| title | group title | string | — | — |

View File

@@ -0,0 +1,328 @@
## MessageBox
A set of modal boxes simulating system message box, mainly for alerting information, confirm operations and prompting messages.
:::tip
By design MessageBox provides simulations of system's `alert`, `confirm` and `prompt`so it's content should be simple. For more complicated contents, please use Dialog.
:::
### Alert
Alert interrupts user operation until the user confirms.
:::demo Open an alert by calling the `$alert` method. It simulates the system's `alert`, and cannot be closed by pressing ESC or clicking outside the box. In this example, two parameters `message` and `title` are received. It is worth mentioning that when the box is closed, it returns a `Promise` object for further processing. If you are not sure if your target browsers support `Promise`, you should import a third party polyfill or use callbacks instead like this example.
```html
<template>
<el-button type="text" @click="open">Click to open the Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$alert('This is a message', 'Title', {
confirmButtonText: 'OK',
callback: action => {
this.$message({
type: 'info',
message: `action: ${ action }`
});
}
});
}
}
}
</script>
```
:::
### Confirm
Confirm is used to ask users' confirmation.
:::demo Call `$confirm` method to open a confirm, and it simulates the system's `confirm`. We can also highly customize Message Box by passing a third attribute `options` which is a literal object. The attribute `type` indicates the message type, and it's value can be `success`, `error`, `info` and `warning`. Note that the second attribute `title` must be a `string`, and if it is an `object`, it will be handled as the attribute `options`. Here we use `Promise` to handle further processing.
```html
<template>
<el-button type="text" @click="open">Click to open the Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$confirm('This will permanently delete the file. Continue?', 'Warning', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
this.$message({
type: 'success',
message: 'Delete completed'
});
}).catch(() => {
this.$message({
type: 'info',
message: 'Delete canceled'
});
});
}
}
}
</script>
```
:::
### Prompt
Prompt is used when user input is required.
:::demo Call `$prompt` method to open a prompt, and it simulates the system's `prompt`. You can use `inputPattern` parameter to specify your own RegExp pattern. Use `inputValidator` to specify validation method, and it should return `Boolean` or `String`. Returning `false` or `String` means the validation has failed, and the string returned will be used as the `inputErrorMessage`. In addition, you can customize the placeholder of the input box with `inputPlaceholder` parameter.
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$prompt('Please input your e-mail', 'Tip', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
inputErrorMessage: 'Invalid Email'
}).then(({ value }) => {
this.$message({
type: 'success',
message: 'Your email is:' + value
});
}).catch(() => {
this.$message({
type: 'info',
message: 'Input canceled'
});
});
}
}
}
</script>
```
:::
### Customization
Can be customized to show various content.
:::demo The three methods mentioned above are repackagings of the `$msgbox` method. This example calls `$msgbox` method directly using the `showCancelButton` attribute, which is used to indicate if a cancel button is displayed. Besides we can use `cancelButtonClass` to add a custom style and `cancelButtonText` to customize the button text (the confirm button also has these fields, and a complete list of fields can be found at the end of this documentation). This example also uses the `beforeClose` attribute. It is a method and will be triggered when the MessageBox instance will be closed, and its execution will stop the instance from closing. It has three parameters: `action`, `instance` and `done`. Using it enables you to manipulate the instance before it closes, e.g. activating `loading` for confirm button; you can invoke the `done` method to close the MessageBox instance (if `done` is not called inside `beforeClose`, the instance will not be closed).
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
const h = this.$createElement;
this.$msgbox({
title: 'Message',
message: h('p', null, [
h('span', null, 'Message can be '),
h('i', { style: 'color: teal' }, 'VNode')
]),
showCancelButton: true,
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
instance.confirmButtonLoading = true;
instance.confirmButtonText = 'Loading...';
setTimeout(() => {
done();
setTimeout(() => {
instance.confirmButtonLoading = false;
}, 300);
}, 3000);
} else {
done();
}
}
}).then(action => {
this.$message({
type: 'info',
message: 'action: ' + action
});
});
},
}
}
</script>
```
:::
:::tip
The content of MessageBox can be `VNode`, allowing us to pass custom components. When opening the MessageBox, Vue compares new `VNode` with old `VNode`, then figures out how to efficiently update the UI, so the components may not be completely re-rendered ([#8931](https://github.com/ElemeFE/element/issues/8931)). In this case, you can add a unique key to `VNode` each time MessageBox opens: [example](https://jsfiddle.net/zhiyang/ezmhq2ef).
:::
### Use HTML String
`message` supports HTML string.
:::demo Set `dangerouslyUseHTMLString` to true and `message` will be treated as an HTML string.
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$alert('<strong>This is <i>HTML</i> string</strong>', 'HTML String', {
dangerouslyUseHTMLString: true
});
}
}
}
</script>
```
:::
:::warning
Although `message` property supports HTML strings, dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). So when `dangerouslyUseHTMLString` is on, please make sure the content of `message` is trusted, and **never** assign `message` to user-provided content.
:::
### Distinguishing cancel and close
In some cases, clicking the cancel button and close button may have different meanings.
:::demo By default, the parameters of Promise's reject callback and `callback` are 'cancel' when the user cancels (clicking the cancel button) and closes (clicking the close button or mask layer, pressing the ESC key) the MessageBox. If `distinguishCancelAndClose` is set to true, the parameters of the above two operations are 'cancel' and 'close' respectively.
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$confirm('You have unsaved changes, save and proceed?', 'Confirm', {
distinguishCancelAndClose: true,
confirmButtonText: 'Save',
cancelButtonText: 'Discard Changes'
})
.then(() => {
this.$message({
type: 'info',
message: 'Changes saved. Proceeding to a new route.'
});
})
.catch(action => {
this.$message({
type: 'info',
message: action === 'cancel'
? 'Changes discarded. Proceeding to a new route.'
: 'Stay in the current route'
})
});
}
}
}
</script>
```
:::
### Centered content
Content of MessageBox can be centered.
:::demo Setting `center` to `true` will center the content
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$confirm('This will permanently delete the file. Continue?', 'Warning', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning',
center: true
}).then(() => {
this.$message({
type: 'success',
message: 'Delete completed'
});
}).catch(() => {
this.$message({
type: 'info',
message: 'Delete canceled'
});
});
}
}
}
</script>
```
:::
### Global method
If Element is fully imported, it will add the following global methods for Vue.prototype: `$msgbox`, `$alert`, `$confirm` and `$prompt`. So in a Vue instance you can call `MessageBox` like what we did in this page. The parameters are:
- `$msgbox(options)`
- `$alert(message, title, options)` or `$alert(message, options)`
- `$confirm(message, title, options)` or `$confirm(message, options)`
- `$prompt(message, title, options)` or `$prompt(message, options)`
### Local import
If you prefer importing `MessageBox` on demand:
```javascript
import { MessageBox } from 'element-ui';
```
The corresponding methods are: `MessageBox`, `MessageBox.alert`, `MessageBox.confirm` and `MessageBox.prompt`. The parameters are the same as above.
### Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| title | title of the MessageBox | string | — | — |
| message | content of the MessageBox | string | — | — |
| dangerouslyUseHTMLString | whether `message` is treated as HTML string | boolean | — | false |
| type | message type, used for icon display | string | success / info / warning / error | — |
| iconClass | custom icon's class, overrides `type` | string | — | — |
| customClass | custom class name for MessageBox | string | — | — |
| callback | MessageBox closing callback if you don't prefer Promise | function(action), where action can be 'confirm', 'cancel' or 'close', and `instance` is the MessageBox instance. You can access to that instance's attributes and methods | — | — |
| showClose | whether to show close icon of MessageBox | boolean | — | true |
| beforeClose | callback before MessageBox closes, and it will prevent MessageBox from closing | function(action, instance, done), where `action` can be 'confirm', 'cancel' or 'close'; `instance` is the MessageBox instance, and you can access to that instance's attributes and methods; `done` is for closing the instance | — | — |
| distinguishCancelAndClose | whether to distinguish canceling and closing the MessageBox | boolean | — | false |
| lockScroll | whether to lock body scroll when MessageBox prompts | boolean | — | true |
| showCancelButton | whether to show a cancel button | boolean | — | false (true when called with confirm and prompt) |
| showConfirmButton | whether to show a confirm button | boolean | — | true |
| cancelButtonText | text content of cancel button | string | — | Cancel |
| confirmButtonText | text content of confirm button | string | — | OK |
| cancelButtonClass | custom class name of cancel button | string | — | — |
| confirmButtonClass | custom class name of confirm button | string | — | — |
| closeOnClickModal | whether MessageBox can be closed by clicking the mask | boolean | — | true (false when called with alert) |
| closeOnPressEscape | whether MessageBox can be closed by pressing the ESC | boolean | — | true (false when called with alert) |
| closeOnHashChange | whether to close MessageBox when hash changes | boolean | — | true |
| showInput | whether to show an input | boolean | — | false (true when called with prompt) |
| inputPlaceholder | placeholder of input | string | — | — |
| inputType | type of input | string | — | text |
| inputValue | initial value of input | string | — | — |
| inputPattern | regexp for the input | regexp | — | — |
| inputValidator | validation function for the input. Should returns a boolean or string. If a string is returned, it will be assigned to inputErrorMessage | function | — | — |
| inputErrorMessage | error message when validation fails | string | — | Illegal input |
| center | whether to align the content in center | boolean | — | false |
| roundButton | whether to use round button | boolean | — | false |

View File

@@ -0,0 +1,219 @@
## Message
Used to show feedback after an activity. The difference with Notification is that the latter is often used to show a system level passive notification.
### Basic usage
Displays at the top, and disappears after 3 seconds.
:::demo The setup of Message is very similar to notification, so parts of the options won't be explained in detail here. You can check the options table below combined with notification doc to understand it. Element has registered a `$message` method for invoking. Message can take a string or a VNode as parameter, and it will be shown as the main body.
```html
<template>
<el-button :plain="true" @click="open">Show message</el-button>
<el-button :plain="true" @click="openVn">VNode</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$message('This is a message.');
},
openVn() {
const h = this.$createElement;
this.$message({
message: h('p', null, [
h('span', null, 'Message can be '),
h('i', { style: 'color: teal' }, 'VNode')
])
});
}
}
}
</script>
```
:::
### Types
Used to show the feedback of Success, Warning, Message and Error activities.
:::demo When you need more customizations, Message component can also take an object as parameter. For example, setting value of `type` can define different types, and its default is `info`. In such cases the main body is passed in as the value of `message`. Also, we have registered methods for different types, so you can directly call it without passing a type like `open4`.
```html
<template>
<el-button :plain="true" @click="open2">success</el-button>
<el-button :plain="true" @click="open3">warning</el-button>
<el-button :plain="true" @click="open1">message</el-button>
<el-button :plain="true" @click="open4">error</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$message('This is a message.');
},
open2() {
this.$message({
message: 'Congrats, this is a success message.',
type: 'success'
});
},
open3() {
this.$message({
message: 'Warning, this is a warning message.',
type: 'warning'
});
},
open4() {
this.$message.error('Oops, this is a error message.');
}
}
}
</script>
```
:::
### Closable
A close button can be added.
:::demo A default Message cannot be closed manually. If you need a closable message, you can set `showClose` field. Besides, same as notification, message has a controllable `duration`. Default duration is 3000 ms, and it won't disappear when set to `0`.
```html
<template>
<el-button :plain="true" @click="open1">message</el-button>
<el-button :plain="true" @click="open2">success</el-button>
<el-button :plain="true" @click="open3">warning</el-button>
<el-button :plain="true" @click="open4">error</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$message({
showClose: true,
message: 'This is a message.'
});
},
open2() {
this.$message({
showClose: true,
message: 'Congrats, this is a success message.',
type: 'success'
});
},
open3() {
this.$message({
showClose: true,
message: 'Warning, this is a warning message.',
type: 'warning'
});
},
open4() {
this.$message({
showClose: true,
message: 'Oops, this is a error message.',
type: 'error'
});
}
}
}
</script>
```
:::
### Centered text
Use the `center` attribute to center the text.
:::demo
```html
<template>
<el-button :plain="true" @click="openCenter">Centered text</el-button>
</template>
<script>
export default {
methods: {
openCenter() {
this.$message({
message: 'Centered text',
center: true
});
}
}
}
</script>
```
:::
### Use HTML string
`message` supports HTML string.
:::demo Set `dangerouslyUseHTMLString` to true and `message` will be treated as an HTML string.
```html
<template>
<el-button :plain="true" @click="openHTML">Use HTML String</el-button>
</template>
<script>
export default {
methods: {
openHTML() {
this.$message({
dangerouslyUseHTMLString: true,
message: '<strong>This is <i>HTML</i> string</strong>'
});
}
}
}
</script>
```
:::
:::warning
Although `message` property supports HTML strings, dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). So when `dangerouslyUseHTMLString` is on, please make sure the content of `message` is trusted, and **never** assign `message` to user-provided content.
:::
### Global method
Element has added a global method `$message` for Vue.prototype. So in a vue instance you can call `Message` like what we did in this page.
### Local import
Import `Message`:
```javascript
import { Message } from 'element-ui';
```
In this case you should call `Message(options)`. We have also registered methods for different types, e.g. `Message.success(options)`. You can call `Message.closeAll()` to manually close all the instances.
### Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| message | message text | string / VNode | — | — |
| type | message type | string | success/warning/info/error | info |
| iconClass | custom icon's class, overrides `type` | string | — | — |
| dangerouslyUseHTMLString | whether `message` is treated as HTML string | boolean | — | false |
| customClass | custom class name for Message | string | — | — |
| duration | display duration, millisecond. If set to 0, it will not turn off automatically | number | — | 3000 |
| showClose | whether to show a close button | boolean | — | false |
| center | whether to center the text | boolean | — | false |
| onClose | callback function when closed with the message instance as the parameter | function | — | — |
| offset | set the distance to the top of viewport | number | — | 20 |
### Methods
`Message` and `this.$message` returns the current Message instance. To manually close the instance, you can call `close` on it.
| Method | Description |
| ---- | ---- |
| close | close the Message |

View File

@@ -0,0 +1,310 @@
## Notification
Displays a global notification message at a corner of the page.
### Basic usage
:::demo Element has registered the `$notify` method and it receives an object as its parameter. In the simplest case, you can set the `title` field and the` message` field for the title and body of the notification. By default, the notification automatically closes after 4500ms, but by setting `duration` you can control its duration. Specifically, if set to `0`, it will not close automatically. Note that `duration` receives a `Number` in milliseconds.
```html
<template>
<el-button
plain
@click="open1">
Closes automatically
</el-button>
<el-button
plain
@click="open2">
Won't close automatically
</el-button>
</template>
<script>
export default {
methods: {
open1() {
const h = this.$createElement;
this.$notify({
title: 'Title',
message: h('i', { style: 'color: teal' }, 'This is a reminder')
});
},
open2() {
this.$notify({
title: 'Prompt',
message: 'This is a message that does not automatically close',
duration: 0
});
}
}
}
</script>
```
:::
### With types
We provide four types: success, warning, info and error.
:::demo Element provides four notification types: `success`, `warning`, `info` and `error`. They are set by the `type` field, and other values will be ignored. We also registered methods for these types that can be invoked directly like `open3` and `open4` without passing a `type` field.
```html
<template>
<el-button
plain
@click="open1">
Success
</el-button>
<el-button
plain
@click="open2">
Warning
</el-button>
<el-button
plain
@click="open3">
Info
</el-button>
<el-button
plain
@click="open4">
Error
</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$notify({
title: 'Success',
message: 'This is a success message',
type: 'success'
});
},
open2() {
this.$notify({
title: 'Warning',
message: 'This is a warning message',
type: 'warning'
});
},
open3() {
this.$notify.info({
title: 'Info',
message: 'This is an info message'
});
},
open4() {
this.$notify.error({
title: 'Error',
message: 'This is an error message'
});
}
}
}
</script>
```
:::
### Custom position
Notification can emerge from any corner you like.
:::demo The `position` attribute defines which corner Notification slides in. It can be `top-right`, `top-left`, `bottom-right` or `bottom-left`. Defaults to `top-right`.
```html
<template>
<el-button
plain
@click="open1">
Top Right
</el-button>
<el-button
plain
@click="open2">
Bottom Right
</el-button>
<el-button
plain
@click="open3">
Bottom Left
</el-button>
<el-button
plain
@click="open4">
Top Left
</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the top right corner'
});
},
open2() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the bottom right corner',
position: 'bottom-right'
});
},
open3() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the bottom left corner',
position: 'bottom-left'
});
},
open4() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the top left corner',
position: 'top-left'
});
}
}
}
</script>
```
:::
### With offset
Customize Notification's offset from the edge of the screen.
:::demo Set the `offset` attribute to customize Notification's offset from the edge of the screen. Note that every Notification instance of the same moment should have the same offset.
```html
<template>
<el-button
plain
@click="open">
Notification with offset
</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$notify.success({
title: 'Success',
message: 'This is a success message',
offset: 100
});
}
}
}
</script>
```
:::
### Use HTML string
`message` supports HTML string.
:::demo Set `dangerouslyUseHTMLString` to true and `message` will be treated as an HTML string.
```html
<template>
<el-button
plain
@click="open">
Use HTML String
</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$notify({
title: 'HTML String',
dangerouslyUseHTMLString: true,
message: '<strong>This is <i>HTML</i> string</strong>'
});
}
}
}
</script>
```
:::
:::warning
Although `message` property supports HTML strings, dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). So when `dangerouslyUseHTMLString` is on, please make sure the content of `message` is trusted, and **never** assign `message` to user-provided content.
:::
### Hide close button
It is possible to hide the close button
:::demo Set the `showClose` attribute to `false` so the notification cannot be closed by the user.
```html
<template>
<el-button
plain
@click="open">
Hide close button
</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$notify.success({
title: 'Info',
message: 'This is a message without close button',
showClose: false
});
}
}
}
</script>
```
:::
### Global method
Element has added a global method `$notify` for Vue.prototype. So in a vue instance you can call `Notification` like what we did in this page.
### Local import
Import `Notification`:
```javascript
import { Notification } from 'element-ui';
```
In this case you should call `Notification(options)`. We have also registered methods for different types, e.g. `Notification.success(options)`. You can call `Notification.closeAll()` to manually close all the instances.
### Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| title | title | string | — | — |
| message | description text | string/Vue.VNode | — | — |
| dangerouslyUseHTMLString | whether `message` is treated as HTML string | boolean | — | false |
| type | notification type | string | success/warning/info/error | — |
| iconClass | custom icon's class. It will be overridden by `type` | string | — | — |
| customClass | custom class name for Notification | string | — | — |
| duration | duration before close. It will not automatically close if set 0 | number | — | 4500 |
| position | custom position | string | top-right/top-left/bottom-right/bottom-left | top-right |
| showClose | whether to show a close button | boolean | — | true |
| onClose | callback function when closed | function | — | — |
| onClick | callback function when notification clicked | function | — | — |
| offset | offset from the top edge of the screen. Every Notification instance of the same moment should have the same offset | number | — | 0 |
### Methods
`Notification` and `this.$notify` returns the current Notification instance. To manually close the instance, you can call `close` on it.
| Method | Description |
| ---- | ---- |
| close | close the Notification |

View File

@@ -0,0 +1,39 @@
## PageHeader
If path of the page is simple, it is recommended to use PageHeader instead of the Breadcrumb.
### Basic
:::demo
```html
<el-page-header @back="goBack" content="detail">
</el-page-header>
<script>
export default {
methods: {
goBack() {
console.log('go back');
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |------------------------------ | ------ |
| title | main title | string | — | Back |
| content | content | string | — | — |
### Events
| Event Name | Description | Parameters |
|----------- |-------------- |----------- |
| back | triggers when right side is clicked | — |
### Slots
| slot | Description |
|---------- | ---------------------- |
| title | title content |
| content | content |

View File

@@ -0,0 +1,200 @@
## Pagination
If you have too much data to display in one page, use pagination.
### Basic usage
:::demo Set `layout` with different pagination elements you wish to display separated with a comma. Pagination elements are: `prev` (a button navigating to the previous page), `next` (a button navigating to the next page), `pager` (page list), `jumper` (a jump-to input), `total` (total item count), `size` (a select to determine page size) and `->`(every element after this symbol will be pulled to the right).
```html
<div class="block">
<span class="demonstration">When you have few pages</span>
<el-pagination
layout="prev, pager, next"
:total="50">
</el-pagination>
</div>
<div class="block">
<span class="demonstration">When you have more than 7 pages</span>
<el-pagination
layout="prev, pager, next"
:total="1000">
</el-pagination>
</div>
```
:::
### Number of pagers
:::demo By default, Pagination collapses extra pager buttons when it has more than 7 pages. This can be configured with the `pager-count` attribute.
```html
<el-pagination
:page-size="20"
:pager-count="11"
layout="prev, pager, next"
:total="1000">
</el-pagination>
```
:::
### Buttons with background color
:::demo Set the `background` attribute and the buttons will have a background color.
```html
<el-pagination
background
layout="prev, pager, next"
:total="1000">
</el-pagination>
```
:::
### Small Pagination
Use small pagination in the case of limited space.
:::demo Just set the `small` attribute to `true` and the Pagination becomes smaller.
```html
<el-pagination
small
layout="prev, pager, next"
:total="50">
</el-pagination>
```
:::
### More elements
Add more modules based on your scenario.
:::demo This example is a complete use case. It uses `size-change` and `current-change` event to handle page size changes and current page changes. `page-sizes` accepts an array of integers, each of which represents a different page size in the `sizes` select options, e.g. `[100, 200, 300, 400]` indicates that the select will have four options: 100, 200, 300 or 400 items per page.
```html
<template>
<div class="block">
<span class="demonstration">Total item count</span>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="currentPage1"
:page-size="100"
layout="total, prev, pager, next"
:total="1000">
</el-pagination>
</div>
<div class="block">
<span class="demonstration">Change page size</span>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="currentPage2"
:page-sizes="[100, 200, 300, 400]"
:page-size="100"
layout="sizes, prev, pager, next"
:total="1000">
</el-pagination>
</div>
<div class="block">
<span class="demonstration">Jump to</span>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="currentPage3"
:page-size="100"
layout="prev, pager, next, jumper"
:total="1000">
</el-pagination>
</div>
<div class="block">
<span class="demonstration">All combined</span>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="currentPage4"
:page-sizes="[100, 200, 300, 400]"
:page-size="100"
layout="total, sizes, prev, pager, next, jumper"
:total="400">
</el-pagination>
</div>
</template>
<script>
export default {
methods: {
handleSizeChange(val) {
console.log(`${val} items per page`);
},
handleCurrentChange(val) {
console.log(`current page: ${val}`);
}
},
data() {
return {
currentPage1: 5,
currentPage2: 5,
currentPage3: 5,
currentPage4: 4
};
}
}
</script>
```
:::
### Hide pagination when there is only one page
When there is only one page, hide the pagination by setting the `hide-on-single-page` attribute.
:::demo
```html
<div>
<el-switch v-model="value">
</el-switch>
<el-pagination
:hide-on-single-page="value"
:total="5"
layout="prev, pager, next">
</el-pagination>
</div>
<script>
export default {
data() {
return {
value: false
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|--------------------|----------------------------------------------------------|-------------------|-------------|--------|
| small | whether to use small pagination | boolean | — | false |
| background | whether the buttons have a background color | boolean | — | false |
| page-size | item count of each page, supports the .sync modifier | number | — | 10 |
| total | total item count | number | — | — |
| page-count | total page count. Set either `total` or `page-count` and pages will be displayed; if you need `page-sizes`, `total` is required | number | — | — |
| pager-count | number of pagers. Pagination collapses when the total page count exceeds this value | number | odd number between 5 and 21 | 7 |
| current-page | current page number, supports the .sync modifier | number | — | 1 |
| layout | layout of Pagination, elements separated with a comma | string | `sizes`, `prev`, `pager`, `next`, `jumper`, `->`, `total`, `slot` | 'prev, pager, next, jumper, ->, total' |
| page-sizes | options of item count per page | number[] | — | [10, 20, 30, 40, 50, 100] |
| popper-class | custom class name for the page size Select's dropdown | string | — | — |
| prev-text | text for the prev button | string | — | — |
| next-text | text for the next button | string | — | — |
| disabled | whether Pagination is disabled | boolean | — | false |
| hide-on-single-page | whether to hide when there's only one page | boolean | — | - |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| size-change | triggers when `page-size` changes | the new page size |
| current-change | triggers when `current-page` changes | the new current page |
| prev-click | triggers when the prev button is clicked and current page changes | the new current page |
| next-click | triggers when the next button is clicked and current page changes | the new current page |
### Slot
| Name | Description |
| --- | --- |
| — | custom content. To use this, you need to declare `slot` in `layout` |

View File

@@ -0,0 +1,60 @@
## Popconfirm
A simple confirmation dialog of an element click action.
### Basic usage
Popconfirm is similar to Popover. So for some duplicated attributes, please refer to the documentation of Popover.
:::demo Only `title` attribute is avaliable in Popconfirm, `content` will be ignored.
```html
<template>
<el-popconfirm
title="Are you sure to delete this?"
>
<el-button slot="reference">Delete</el-button>
</el-popconfirm>
</template>
````
:::
### Customise
You can customise Popconfirm like:
:::demo
```html
<template>
<el-popconfirm
confirm-button-text='OK'
cancel-button-text='No, Thanks'
icon="el-icon-info"
icon-color="red"
title="Are you sure to delete this?"
>
<el-button slot="reference">Delete</el-button>
</el-popconfirm>
</template>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|--------------------|----------------------------------------------------------|-------------------|-------------|--------|
| title | Title | String | — | — |
| confirm-button-text | Confirm button text | String | — | — |
| cancel-button-text | Cancel button text | String | — | — |
| confirm-button-type | Confirm button type | String | — | Primary |
| cancel-button-type | Cancel button type | String | — | Text |
| icon | Icon | String | — | el-icon-question |
| icon-color | Icon color | String | — | #f90 |
| hide-icon | is hide Icon | Boolean | — | false |
### Slot
| Name | Description |
|--- | ---|
| reference | HTML element that triggers Popconfirm |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| confirm | triggers when click confirm button | — |
| cancel | triggers when click cancel button | — |

View File

@@ -0,0 +1,170 @@
## Popover
### Basic usage
Similar to Tooltip, Popover is also built with `Vue-popper`. So for some duplicated attributes, please refer to the documentation of Tooltip.
:::demo The `trigger` attribute is used to define how popover is triggered: `hover`, `click`, `focus` or `manual`. As for the triggering element, you can write it in two different ways: use the `slot="reference"` named slot, or use the `v-popover` directive and set it to Popover's `ref`.
```html
<template>
<el-popover
placement="top-start"
title="Title"
width="200"
trigger="hover"
content="this is content, this is content, this is content">
<el-button slot="reference">Hover to activate</el-button>
</el-popover>
<el-popover
placement="bottom"
title="Title"
width="200"
trigger="click"
content="this is content, this is content, this is content">
<el-button slot="reference">Click to activate</el-button>
</el-popover>
<el-popover
ref="popover"
placement="right"
title="Title"
width="200"
trigger="focus"
content="this is content, this is content, this is content">
</el-popover>
<el-button v-popover:popover>Focus to activate</el-button>
<el-popover
placement="bottom"
title="Title"
width="200"
trigger="manual"
content="this is content, this is content, this is content"
v-model="visible">
<el-button slot="reference" @click="visible = !visible">Manual to activate</el-button>
</el-popover>
</template>
<script>
export default {
data() {
return {
visible: false
};
}
};
</script>
```
:::
### Nested information
Other components can be nested in popover. Following is an example of nested table.
:::demo replace the `content` attribute with a default `slot`.
```html
<el-popover
placement="right"
width="400"
trigger="click">
<el-table :data="gridData">
<el-table-column width="150" property="date" label="date"></el-table-column>
<el-table-column width="100" property="name" label="name"></el-table-column>
<el-table-column width="300" property="address" label="address"></el-table-column>
</el-table>
<el-button slot="reference">Click to activate</el-button>
</el-popover>
<script>
export default {
data() {
return {
gridData: [{
date: '2016-05-02',
name: 'Jack',
address: 'New York City'
}, {
date: '2016-05-04',
name: 'Jack',
address: 'New York City'
}, {
date: '2016-05-01',
name: 'Jack',
address: 'New York City'
}, {
date: '2016-05-03',
name: 'Jack',
address: 'New York City'
}]
};
}
};
</script>
```
:::
### Nested operation
Of course, you can nest other operations. It's more light-weight than using a dialog.
:::demo
```html
<el-popover
placement="top"
width="160"
v-model="visible">
<p>Are you sure to delete this?</p>
<div style="text-align: right; margin: 0">
<el-button size="mini" type="text" @click="visible = false">cancel</el-button>
<el-button type="primary" size="mini" @click="visible = false">confirm</el-button>
</div>
<el-button slot="reference">Delete</el-button>
</el-popover>
<script>
export default {
data() {
return {
visible: false,
};
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|--------------------|----------------------------------------------------------|-------------------|-------------|--------|
| trigger | how the popover is triggered | string | click/focus/hover/manual | click |
| title | popover title | string | — | — |
| content | popover content, can be replaced with a default `slot` | string | — | — |
| width | popover width | string, number | — | Min width 150px |
| placement | popover placement | string | top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end | bottom |
| disabled | whether Popover is disabled | boolean | — | false |
| value / v-model | whether popover is visible | Boolean | — | false |
| offset | popover offset | number | — | 0 |
| transition | popover transition animation | string | — | el-fade-in-linear |
| visible-arrow | whether a tooltip arrow is displayed or not. For more info, please refer to [Vue-popper](https://github.com/element-component/vue-popper) | boolean | — | true |
| popper-options | parameters for [popper.js](https://popper.js.org/documentation.html) | object | please refer to [popper.js](https://popper.js.org/documentation.html) | `{ boundariesElement: 'body', gpuAcceleration: false }` |
| popper-class | custom class name for popover | string | — | — |
| open-delay | delay before appearing when `trigger` is hover, in milliseconds | number | — | — |
| close-delay | delay before disappearing when `trigger` is hover, in milliseconds | number | — | 200 |
| tabindex | [tabindex](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) of Popover | number | — | 0 |
### Slot
| Name | Description |
| --- | --- |
| — | text content of popover |
| reference | HTML element that triggers popover |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| show | triggers when popover shows | — |
| after-enter | triggers when the entering transition ends | — |
| hide | triggers when popover hides | — |
| after-leave | triggers when the leaving transition ends | — |

View File

@@ -0,0 +1,174 @@
## Progress
Progress is used to show the progress of current operation, and inform the user the current status.
### Linear progress bar
:::demo Use `percentage` attribute to set the percentage. It's **required** and must be between `0-100`. You can custom text format by setting `format`.
```html
<el-progress :percentage="50"></el-progress>
<el-progress :percentage="100" :format="format"></el-progress>
<el-progress :percentage="100" status="success"></el-progress>
<el-progress :percentage="100" status="warning"></el-progress>
<el-progress :percentage="50" status="exception"></el-progress>
<script>
export default {
methods: {
format(percentage) {
return percentage === 100 ? 'Full' : `${percentage}%`;
}
}
};
</script>
```
:::
### Internal percentage
In this case the percentage takes no additional space.
:::demo `stroke-width` attribute decides the `width` of progress bar, and use `text-inside` attribute to put description inside the progress bar.
```html
<el-progress :text-inside="true" :stroke-width="26" :percentage="70"></el-progress>
<el-progress :text-inside="true" :stroke-width="24" :percentage="100" status="success"></el-progress>
<el-progress :text-inside="true" :stroke-width="22" :percentage="80" status="warning"></el-progress>
<el-progress :text-inside="true" :stroke-width="20" :percentage="50" status="exception"></el-progress>
```
:::
### Custom color
You can use `color` attr to set the progress bar color. it accepts color string, function, or array.
:::demo
```html
<el-progress :percentage="percentage" :color="customColor"></el-progress>
<el-progress :percentage="percentage" :color="customColorMethod"></el-progress>
<el-progress :percentage="percentage" :color="customColors"></el-progress>
<div>
<el-button-group>
<el-button icon="el-icon-minus" @click="decrease"></el-button>
<el-button icon="el-icon-plus" @click="increase"></el-button>
</el-button-group>
</div>
<script>
export default {
data() {
return {
percentage: 20,
customColor: '#409eff',
customColors: [
{color: '#f56c6c', percentage: 20},
{color: '#e6a23c', percentage: 40},
{color: '#5cb87a', percentage: 60},
{color: '#1989fa', percentage: 80},
{color: '#6f7ad3', percentage: 100}
]
};
},
methods: {
customColorMethod(percentage) {
if (percentage < 30) {
return '#909399';
} else if (percentage < 70) {
return '#e6a23c';
} else {
return '#67c23a';
}
},
increase() {
this.percentage += 10;
if (this.percentage > 100) {
this.percentage = 100;
}
},
decrease() {
this.percentage -= 10;
if (this.percentage < 0) {
this.percentage = 0;
}
}
}
}
</script>
```
:::
### Circular progress bar
:::demo You can specify `type` attribute to `circle` to use circular progress bar, and use `width` attribute to change the size of circle.
```html
<el-progress type="circle" :percentage="0"></el-progress>
<el-progress type="circle" :percentage="25"></el-progress>
<el-progress type="circle" :percentage="100" status="success"></el-progress>
<el-progress type="circle" :percentage="70" status="warning"></el-progress>
<el-progress type="circle" :percentage="50" status="exception"></el-progress>
```
:::
### Dashboard progress bar
You also can specify `type` attribute to `dashboard` to use dashboard progress bar.
:::demo
```html
<el-progress type="dashboard" :percentage="percentage" :color="colors"></el-progress>
<div>
<el-button-group>
<el-button icon="el-icon-minus" @click="decrease"></el-button>
<el-button icon="el-icon-plus" @click="increase"></el-button>
</el-button-group>
</div>
<script>
export default {
data() {
return {
percentage: 10,
colors: [
{color: '#f56c6c', percentage: 20},
{color: '#e6a23c', percentage: 40},
{color: '#5cb87a', percentage: 60},
{color: '#1989fa', percentage: 80},
{color: '#6f7ad3', percentage: 100}
]
};
},
methods: {
increase() {
this.percentage += 10;
if (this.percentage > 100) {
this.percentage = 100;
}
},
decrease() {
this.percentage -= 10;
if (this.percentage < 0) {
this.percentage = 0;
}
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
| --- | ---- | ---- | ---- | ---- |
| **percentage** | percentage, **required** | number | 0-100 | 0 |
| type | the type of progress bar | string | line/circle/dashboard | line |
| stroke-width | the width of progress bar | number | — | 6 |
| text-inside | whether to place the percentage inside progress bar, only works when `type` is 'line' | boolean | — | false |
| status | the current status of progress bar | string | success/exception/warning | — |
| color | background color of progress bar. Overrides `status` prop | string/function/array | — | '' |
| width | the canvas width of circle progress bar | number | — | 126 |
| show-text | whether to show percentage | boolean | — | true |
| stroke-linecap | circle/dashboard type shape at the end path | string | butt/round/square | round |
| format | custom text format | function(percentage) | — | — |

View File

@@ -0,0 +1,289 @@
## Quick start
This part walks you through the process of using Element in a webpack project.
### Use vue-cli@3
We provide an [Element plugin](https://github.com/ElementUI/vue-cli-plugin-element) for vue-cli@3, which you can use to quickly build an Element-based project.
### Use Starter Kit
We provide a general [project template](https://github.com/ElementUI/element-starter) for you. For Laravel users, we also have a [template](https://github.com/ElementUI/element-in-laravel-starter). You can download and use them directly.
If you prefer not to use them, please read the following.
### Import Element
You can import Element entirely, or just import what you need. Let's start with fully import.
#### Fully import
In main.js:
```javascript
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)
});
```
The above imports Element entirely. Note that CSS file needs to be imported separately.
#### On demand
With the help of [babel-plugin-component](https://github.com/QingWei-Li/babel-plugin-component), we can import components we actually need, making the project smaller than otherwise.
First, install babel-plugin-component:
```bash
npm install babel-plugin-component -D
```
Then edit .babelrc:
```json
{
"presets": [["es2015", { "modules": false }]],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
```
Next, if you need Button and Select, edit main.js:
```javascript
import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
/* or
* Vue.use(Button)
* Vue.use(Select)
*/
new Vue({
el: '#app',
render: h => h(App)
});
```
Full example (Component list reference [components.json](https://github.com/ElemeFE/element/blob/master/components.json))
```javascript
import Vue from 'vue';
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,
DatePicker,
TimeSelect,
TimePicker,
Popover,
Tooltip,
Breadcrumb,
BreadcrumbItem,
Form,
FormItem,
Tabs,
TabPane,
Tag,
Tree,
Alert,
Slider,
Icon,
Row,
Col,
Upload,
Progress,
Spinner,
Badge,
Card,
Rate,
Steps,
Step,
Carousel,
CarouselItem,
Collapse,
CollapseItem,
Cascader,
ColorPicker,
Transfer,
Container,
Header,
Aside,
Main,
Footer,
Timeline,
TimelineItem,
Link,
Divider,
Image,
Calendar,
Backtop,
PageHeader,
CascaderPanel,
Loading,
MessageBox,
Message,
Notification
} from 'element-ui';
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(DatePicker);
Vue.use(TimeSelect);
Vue.use(TimePicker);
Vue.use(Popover);
Vue.use(Tooltip);
Vue.use(Breadcrumb);
Vue.use(BreadcrumbItem);
Vue.use(Form);
Vue.use(FormItem);
Vue.use(Tabs);
Vue.use(TabPane);
Vue.use(Tag);
Vue.use(Tree);
Vue.use(Alert);
Vue.use(Slider);
Vue.use(Icon);
Vue.use(Row);
Vue.use(Col);
Vue.use(Upload);
Vue.use(Progress);
Vue.use(Spinner);
Vue.use(Badge);
Vue.use(Card);
Vue.use(Rate);
Vue.use(Steps);
Vue.use(Step);
Vue.use(Carousel);
Vue.use(CarouselItem);
Vue.use(Collapse);
Vue.use(CollapseItem);
Vue.use(Cascader);
Vue.use(ColorPicker);
Vue.use(Transfer);
Vue.use(Container);
Vue.use(Header);
Vue.use(Aside);
Vue.use(Main);
Vue.use(Footer);
Vue.use(Timeline);
Vue.use(TimelineItem);
Vue.use(Link);
Vue.use(Divider);
Vue.use(Image);
Vue.use(Calendar);
Vue.use(Backtop);
Vue.use(PageHeader);
Vue.use(CascaderPanel);
Vue.use(Loading.directive);
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;
```
### Global config
When importing Element, you can define a global config object. For now this object has two properties: `size` and `zIndex`. The property `size` sets the default size for all components and the property `zIndex` sets the initial z-index (default: 2000) for modal boxes:
Fully import Element
```js
import Vue from 'vue';
import Element from 'element-ui';
Vue.use(Element, { size: 'small', zIndex: 3000 });
```
Partial import Element
```js
import Vue from 'vue';
import { Button } from 'element-ui';
Vue.prototype.$ELEMENT = { size: 'small', zIndex: 3000 };
Vue.use(Button);
```
With the above config, the default size of all components that have size attribute will be 'small', and the initial z-index of modal boxes is 3000.
### Start coding
Now you have implemented Vue and Element to your project, and it's time to write your code. Please refer to each component's documentation to learn how to use them.
### Use Nuxt.js
We can also start a project using [Nuxt.js](https://nuxtjs.org/):
<div class="glitch-embed-wrap" style="height: 420px; width: 100%;">
<iframe src="https://glitch.com/embed/#!/embed/nuxt-with-element?path=nuxt.config.js&previewSize=0&attributionHidden=true" alt="nuxt-with-element on glitch" style="height: 100%; width: 100%; border: 0;"></iframe>
</div>

View File

@@ -0,0 +1,213 @@
## Radio
Single selection among multiple options.
### Basic usage
Radio should not have too many options. Otherwise, use the Select component instead.
:::demo Creating a radio component is easy, you just need to bind a variable to Radio's `v-model`. It equals to the value of `label` of the chosen radio. The type of `label` is `String`, `Number` or `Boolean`.
```html
<template>
<el-radio v-model="radio" label="1">Option A</el-radio>
<el-radio v-model="radio" label="2">Option B</el-radio>
</template>
<script>
export default {
data () {
return {
radio: '1'
};
}
}
</script>
```
:::
### Disabled
`disabled` attribute is used to disable the radio.
:::demo You just need to add the `disabled` attribute.
```html
<template>
<el-radio disabled v-model="radio" label="disabled">Option A</el-radio>
<el-radio disabled v-model="radio" label="selected and disabled">Option B</el-radio>
</template>
<script>
export default {
data () {
return {
radio: 'selected and disabled'
};
}
}
</script>
```
:::
### Radio button group
Suitable for choosing from some mutually exclusive options.
:::demo Combine `el-radio-group` with `el-radio` to display a radio group. Bind a variable with `v-model` of `el-radio-group` element and set label value in `el-radio`. It also provides `change` event with the current value as its parameter.
```html
<el-radio-group v-model="radio">
<el-radio :label="3">Option A</el-radio>
<el-radio :label="6">Option B</el-radio>
<el-radio :label="9">Option C</el-radio>
</el-radio-group>
<script>
export default {
data () {
return {
radio: 3
};
}
}
</script>
```
:::
### Button style
Radio with button styles.
:::demo You just need to change `el-radio` element into `el-radio-button` element. We also provide `size` attribute.
```html
<template>
<div>
<el-radio-group v-model="radio1">
<el-radio-button label="New York"></el-radio-button>
<el-radio-button label="Washington"></el-radio-button>
<el-radio-button label="Los Angeles"></el-radio-button>
<el-radio-button label="Chicago"></el-radio-button>
</el-radio-group>
</div>
<div style="margin-top: 20px">
<el-radio-group v-model="radio2" size="medium">
<el-radio-button label="New York" ></el-radio-button>
<el-radio-button label="Washington"></el-radio-button>
<el-radio-button label="Los Angeles"></el-radio-button>
<el-radio-button label="Chicago"></el-radio-button>
</el-radio-group>
</div>
<div style="margin-top: 20px">
<el-radio-group v-model="radio3" size="small">
<el-radio-button label="New York"></el-radio-button>
<el-radio-button label="Washington" disabled ></el-radio-button>
<el-radio-button label="Los Angeles"></el-radio-button>
<el-radio-button label="Chicago"></el-radio-button>
</el-radio-group>
</div>
<div style="margin-top: 20px">
<el-radio-group v-model="radio4" disabled size="mini">
<el-radio-button label="New York"></el-radio-button>
<el-radio-button label="Washington"></el-radio-button>
<el-radio-button label="Los Angeles"></el-radio-button>
<el-radio-button label="Chicago"></el-radio-button>
</el-radio-group>
</div>
</template>
<script>
export default {
data () {
return {
radio1: 'New York',
radio2: 'New York',
radio3: 'New York',
radio4: 'New York'
};
}
}
</script>
```
:::
### With borders
:::demo The `border` attribute adds a border to Radios.
```html
<template>
<div>
<el-radio v-model="radio1" label="1" border>Option A</el-radio>
<el-radio v-model="radio1" label="2" border>Option B</el-radio>
</div>
<div style="margin-top: 20px">
<el-radio v-model="radio2" label="1" border size="medium">Option A</el-radio>
<el-radio v-model="radio2" label="2" border size="medium">Option B</el-radio>
</div>
<div style="margin-top: 20px">
<el-radio-group v-model="radio3" size="small">
<el-radio label="1" border>Option A</el-radio>
<el-radio label="2" border disabled>Option B</el-radio>
</el-radio-group>
</div>
<div style="margin-top: 20px">
<el-radio-group v-model="radio4" size="mini" disabled>
<el-radio label="1" border>Option A</el-radio>
<el-radio label="2" border>Option B</el-radio>
</el-radio-group>
</div>
</template>
<script>
export default {
data () {
return {
radio1: '1',
radio2: '1',
radio3: '1',
radio4: '1'
};
}
}
</script>
```
:::
### Radio Attributes
Attribute | Description | Type | Accepted Values | Default
---- | ---- | ---- | ---- | ----
value / v-model | binding value | string / number / boolean | — | —
label | the value of Radio | string / number / boolean | — | —
disabled | whether Radio is disabled | boolean | — | false
border | whether to add a border around Radio | boolean | — | false
size | size of the Radio, only works when `border` is true | string | medium / small / mini | —
name | native 'name' attribute | string | — | —
### Radio Events
| Event Name | Description | Parameters |
| --- | --- | --- |
| change | triggers when the bound value changes | the label value of the chosen radio |
### Radio-group Attributes
Attribute | Description | Type | Accepted Values | Default
---- | ---- | ---- | ---- | ----
value / v-model | binding value | string / number / boolean | — | —
size | the size of radio buttons or bordered radios | string | medium / small / mini | —
disabled | whether the nesting radios are disabled | boolean | — | false
text-color | font color when button is active | string | — | #ffffff |
fill | border and background color when button is active | string | — | #409EFF |
### Radio-group Events
| Event Name | Description | Parameters |
| --- | --- | --- |
| change | triggers when the bound value changes | the label value of the chosen radio |
### Radio-button Attributes
Attribute | Description | Type | Accepted Values | Default
---- | ---- | ---- | ---- | ----
label | the value of radio | string / number | — | —
disabled | whether radio is disabled | boolean | — | false
name | native 'name' attribute | string | — | —

139
examples/docs/en-US/rate.md Normal file
View File

@@ -0,0 +1,139 @@
## Rate
Used for rating
### Basic usage
:::demo Rate divides rating scores into several levels and these levels can be distinguished by using different background colors. By default background colors are the same, but you can assign them an array with three element to reflect three levels using the `colors` attribute, and their two thresholds can be defined by `low-threshold` and `high-threshold`, or you can assign them with a object which key is the threshold between two levels and value is the corresponding color.
```html
<div class="block">
<span class="demonstration">Default</span>
<el-rate v-model="value1"></el-rate>
</div>
<div class="block">
<span class="demonstration">Color for different levels</span>
<el-rate
v-model="value2"
:colors="colors">
</el-rate>
</div>
<script>
export default {
data() {
return {
value1: null,
value2: null,
colors: ['#99A9BF', '#F7BA2A', '#FF9900'] // same as { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
}
}
}
</script>
```
:::
### With text
Using text to indicate rating score
:::demo Add attribute `show-text` to display text at the right of Rate. You can assign texts for different scores using `texts`. `texts` is an array whose length should be equal to the max score `max`.
```html
<el-rate
v-model="value"
:texts="['oops', 'disappointed', 'normal', 'good', 'great']"
show-text>
</el-rate>
<script>
export default {
data() {
return {
value: null
}
}
}
</script>
```
:::
### More icons
You can use different icons to distinguish different rate components.
:::demo You can customize icons by passing `icon-classes` an array with three elements or a object which key is the threshold between two levels and value is the corresponding icon class. In this example, we also use `void-icon-class` to set the icon if it is unselected.
```html
<el-rate
v-model="value"
:icon-classes="iconClasses"
void-icon-class="icon-rate-face-off"
:colors="['#99A9BF', '#F7BA2A', '#FF9900']">
</el-rate>
<script>
export default {
data() {
return {
value: null,
iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3'] // same as { 2: 'icon-rate-face-1', 4: { value: 'icon-rate-face-2', excluded: true }, 5: 'icon-rate-face-3' }
}
}
}
</script>
```
:::
### Read-only
Read-only Rate is for displaying rating score. Half star is supported.
:::demo Use attribute `disabled` to make the component read-only. Add `show-score` to display the rating score at the right side. Additionally, you can use attribute `score-template` to provide a score template. It must contain `{value}`, and `{value}` will be replaced with the rating score.
```html
<el-rate
v-model="value"
disabled
show-score
text-color="#ff9900"
score-template="{value} points">
</el-rate>
<script>
export default {
data() {
return {
value: 3.7
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | binding value | number | — | 0 |
| max | max rating score | number | — | 5 |
| disabled | whether Rate is read-only | boolean | — | false |
| allow-half | whether picking half start is allowed | boolean | — | false |
| low-threshold | threshold value between low and medium level. The value itself will be included in low level | number | — | 2 |
| high-threshold | threshold value between medium and high level. The value itself will be included in high level | number | — | 4 |
| colors | colors for icons. If array, it should have 3 elements, each of which corresponds with a score level, else if object, the key should be threshold value between two levels, and the value should be corresponding color | array/object | — | ['#F7BA2A', '#F7BA2A', '#F7BA2A'] |
| void-color | color of unselected icons | string | — | #C6D1DE |
| disabled-void-color | color of unselected read-only icons | string | — | #EFF2F7 |
| icon-classes | class names of icons. If array, ot should have 3 elements, each of which corresponds with a score level, else if object, the key should be threshold value between two levels, and the value should be corresponding icon class | array/object | — | ['el-icon-star-on', 'el-icon-star-on','el-icon-star-on'] |
| void-icon-class | class name of unselected icons | string | — | el-icon-star-off |
| disabled-void-icon-class | class name of unselected read-only icons | string | — | el-icon-star-on |
| show-text | whether to display texts | boolean | — | false |
| show-score | whether to display current score. show-score and show-text cannot be true at the same time | boolean | — | false |
| text-color | color of texts | string | — | #1F2D3D |
| texts | text array | array | — | ['极差', '失望', '一般', '满意', '惊喜'] |
| score-template | score template | string | — | {value} |
### Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| change | Triggers when rate value is changed | value after changing |

View File

@@ -0,0 +1,591 @@
## Select
When there are plenty of options, use a drop-down menu to display and select desired ones.
### Basic usage
:::demo `v-model` is the value of `el-option` that is currently selected.
```html
<template>
<el-select v-model="value" placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'Option1',
label: 'Option1'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
</script>
```
:::
### Disabled option
:::demo Set the value of `disabled` in `el-option` to `true` to disable this option.
```html
<template>
<el-select v-model="value" placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
:disabled="item.disabled">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'Option1',
label: 'Option1'
}, {
value: 'Option2',
label: 'Option2',
disabled: true
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
</script>
```
:::
### Disabled select
Disable the whole component.
:::demo Set `disabled` of `el-select` to make it disabled.
```html
<template>
<el-select v-model="value" disabled placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'Option1',
label: 'Option1'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
</script>
```
:::
### Clearable single select
You can clear Select using a clear icon.
:::demo Set `clearable` attribute for `el-select` and a clear icon will appear. Note that `clearable` is only for single select.
```html
<template>
<el-select v-model="value" clearable placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'Option1',
label: 'Option1'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
</script>
```
:::
### Basic multiple select
Multiple select uses tags to display selected options.
:::demo Set `multiple` attribute for `el-select` to enable multiple mode. In this case, the value of `v-model` will be an array of selected options. By default the selected options will be displayed as Tags. You can collapse them to a text by using `collapse-tags` attribute.
```html
<template>
<el-select v-model="value1" multiple placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
<el-select
v-model="value2"
multiple
collapse-tags
style="margin-left: 20px;"
placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'Option1',
label: 'Option1'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value1: [],
value2: []
}
}
}
</script>
```
:::
### Custom template
You can customize HTML templates for options.
:::demo Insert customized HTML templates into the slot of `el-option`.
```html
<template>
<el-select v-model="value" placeholder="Select">
<el-option
v-for="item in cities"
:key="item.value"
:label="item.label"
:value="item.value">
<span style="float: left">{{ item.label }}</span>
<span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
cities: [{
value: 'Beijing',
label: 'Beijing'
}, {
value: 'Shanghai',
label: 'Shanghai'
}, {
value: 'Nanjing',
label: 'Nanjing'
}, {
value: 'Chengdu',
label: 'Chengdu'
}, {
value: 'Shenzhen',
label: 'Shenzhen'
}, {
value: 'Guangzhou',
label: 'Guangzhou'
}],
value: ''
}
}
}
</script>
```
:::
### Grouping
Display options in groups.
:::demo Use `el-option-group` to group the options, and its `label` attribute stands for the name of the group.
```html
<template>
<el-select v-model="value" placeholder="Select">
<el-option-group
v-for="group in options"
:key="group.label"
:label="group.label">
<el-option
v-for="item in group.options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-option-group>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
label: 'Popular cities',
options: [{
value: 'Shanghai',
label: 'Shanghai'
}, {
value: 'Beijing',
label: 'Beijing'
}]
}, {
label: 'City name',
options: [{
value: 'Chengdu',
label: 'Chengdu'
}, {
value: 'Shenzhen',
label: 'Shenzhen'
}, {
value: 'Guangzhou',
label: 'Guangzhou'
}, {
value: 'Dalian',
label: 'Dalian'
}]
}],
value: ''
}
}
}
</script>
```
:::
### Option filtering
You can filter options for your desired ones.
:::demo Adding `filterable` to `el-select` enables filtering. By default, Select will find all the options whose `label` attribute contains the input value. If you prefer other filtering strategies, you can pass the `filter-method`. `filter-method` is a `Function` that gets called when the input value changes, and its parameter is the current input value.
```html
<template>
<el-select v-model="value" filterable placeholder="Select">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'Option1',
label: 'Option1'
}, {
value: 'Option2',
label: 'Option2'
}, {
value: 'Option3',
label: 'Option3'
}, {
value: 'Option4',
label: 'Option4'
}, {
value: 'Option5',
label: 'Option5'
}],
value: ''
}
}
}
</script>
```
:::
### Remote Search
Enter keywords and search data from server.
:::demo Set the value of `filterable` and `remote` with `true` to enable remote search, and you should pass the `remote-method`. `remote-method` is a `Function` that gets called when the input value changes, and its parameter is the current input value. Note that if `el-option` is rendered with the `v-for` directive, you should add the `key` attribute for `el-option`. Its value needs to be unique, such as `item.value` in the following example.
```html
<template>
<el-select
v-model="value"
multiple
filterable
remote
reserve-keyword
placeholder="Please enter a keyword"
:remote-method="remoteMethod"
:loading="loading">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [],
value: [],
list: [],
loading: false,
states: ["Alabama", "Alaska", "Arizona",
"Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois",
"Indiana", "Iowa", "Kansas", "Kentucky",
"Louisiana", "Maine", "Maryland",
"Massachusetts", "Michigan", "Minnesota",
"Mississippi", "Missouri", "Montana",
"Nebraska", "Nevada", "New Hampshire",
"New Jersey", "New Mexico", "New York",
"North Carolina", "North Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania",
"Rhode Island", "South Carolina",
"South Dakota", "Tennessee", "Texas",
"Utah", "Vermont", "Virginia",
"Washington", "West Virginia", "Wisconsin",
"Wyoming"]
}
},
mounted() {
this.list = this.states.map(item => {
return { value: `value:${item}`, label: `label:${item}` };
});
},
methods: {
remoteMethod(query) {
if (query !== '') {
this.loading = true;
setTimeout(() => {
this.loading = false;
this.options = this.list.filter(item => {
return item.label.toLowerCase()
.indexOf(query.toLowerCase()) > -1;
});
}, 200);
} else {
this.options = [];
}
}
}
}
</script>
```
:::
### Create new items
Create and select new items that are not included in select options
:::demo By using the `allow-create` attribute, users can create new items by typing in the input box. Note that for `allow-create` to work, `filterable` must be `true`. This example also demonstrates `default-first-option`. When this attribute is set to `true`, you can select the first option in the current option list by hitting enter without having to navigate with mouse or arrow keys.
```html
<template>
<el-select
v-model="value"
multiple
filterable
allow-create
default-first-option
placeholder="Choose tags for your article">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template>
<script>
export default {
data() {
return {
options: [{
value: 'HTML',
label: 'HTML'
}, {
value: 'CSS',
label: 'CSS'
}, {
value: 'JavaScript',
label: 'JavaScript'
}],
value: []
}
}
}
</script>
```
:::
:::tip
If the binding value of Select is an object, make sure to assign `value-key` as its unique identity key name.
:::
### Select Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value / v-model | binding value | boolean / string / number | — | — |
| multiple | whether multiple-select is activated | boolean | — | false |
| disabled | whether Select is disabled | boolean | — | false |
| value-key | unique identity key name for value, required when value is an object | string | — | value |
| size | size of Input | string | large/small/mini | — |
| clearable | whether select can be cleared | boolean | — | false |
| collapse-tags | whether to collapse tags to a text when multiple selecting | boolean | — | false |
| multiple-limit | maximum number of options user can select when `multiple` is `true`. No limit when set to 0 | number | — | 0 |
| name | the name attribute of select input | string | — | — |
| autocomplete | the autocomplete attribute of select input | string | — | off |
| auto-complete | @DEPRECATED in next major version | string | — | off |
| placeholder | placeholder | string | — | Select |
| filterable | whether Select is filterable | boolean | — | false |
| allow-create | whether creating new items is allowed. To use this, `filterable` must be true | boolean | — | false |
| filter-method | custom filter method | function | — | — |
| remote | whether options are loaded from server | boolean | — | false |
| remote-method | custom remote search method | function | — | — |
| loading | whether Select is loading data from server | boolean | — | false |
| loading-text | displayed text while loading data from server | string | — | Loading |
| no-match-text | displayed text when no data matches the filtering query, you can also use slot `empty` | string | — | No matching data |
| no-data-text | displayed text when there is no options, you can also use slot `empty` | string | — | No data |
| popper-class | custom class name for Select's dropdown | string | — | — |
| reserve-keyword | when `multiple` and `filter` is true, whether to reserve current keyword after selecting an option | boolean | — | false |
| default-first-option | select first matching option on enter key. Use with `filterable` or `remote` | boolean | - | false |
| popper-append-to-body| whether to append the popper menu to body. If the positioning of the popper is wrong, you can try to set this prop to false | boolean | - | true |
| automatic-dropdown | for non-filterable Select, this prop decides if the option menu pops up when the input is focused | boolean | - | false |
### Select Events
| Event Name | Description | Parameters |
|---------|---------|---------|
| change | triggers when the selected value changes | current selected value |
| visible-change | triggers when the dropdown appears/disappears | true when it appears, and false otherwise |
| remove-tag | triggers when a tag is removed in multiple mode | removed tag value |
| clear | triggers when the clear icon is clicked in a clearable Select | — |
| blur | triggers when Input blurs | (event: Event) |
| focus | triggers when Input focuses | (event: Event) |
### Select Slots
| Name | Description |
|---------|-------------|
| — | Option component list |
| prefix | content as Select prefix |
| empty | content when there is no options |
### Option Group Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| label | name of the group | string | — | — |
| disabled | whether to disable all options in this group | boolean | — | false |
### Option Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value | value of option | string/number/object | — | — |
| label | label of option, same as `value` if omitted | string/number | — | — |
| disabled | whether option is disabled | boolean | — | false |
### Methods
| Method | Description | Parameters |
|------|--------|-------|
| focus | focus the Input component | - |
| blur | blur the Input component, and hide the dropdown | - |

View File

@@ -0,0 +1,241 @@
## Slider
Drag the slider within a fixed range.
### Basic usage
The current value is displayed when the slider is being dragged.
:::demo Customize the initial value of the slider by setting the binding value.
```html
<template>
<div class="block">
<span class="demonstration">Default value</span>
<el-slider v-model="value1"></el-slider>
</div>
<div class="block">
<span class="demonstration">Customized initial value</span>
<el-slider v-model="value2"></el-slider>
</div>
<div class="block">
<span class="demonstration">Hide Tooltip</span>
<el-slider v-model="value3" :show-tooltip="false"></el-slider>
</div>
<div class="block">
<span class="demonstration">Format Tooltip</span>
<el-slider v-model="value4" :format-tooltip="formatTooltip"></el-slider>
</div>
<div class="block">
<span class="demonstration">Disabled</span>
<el-slider v-model="value5" disabled></el-slider>
</div>
</template>
<script>
export default {
data() {
return {
value1: 0,
value2: 50,
value3: 36,
value4: 48,
value5: 42
}
},
methods: {
formatTooltip(val) {
return val / 100;
}
}
}
</script>
```
:::
### Discrete values
The options can be discrete.
:::demo Set step size with the `step` attribute. You can display breakpoints by setting the `show-stops` attribute.
```html
<template>
<div class="block">
<span class="demonstration">Breakpoints not displayed</span>
<el-slider
v-model="value1"
:step="10">
</el-slider>
</div>
<div class="block">
<span class="demonstration">Breakpoints displayed</span>
<el-slider
v-model="value2"
:step="10"
show-stops>
</el-slider>
</div>
</template>
<script>
export default {
data() {
return {
value1: 0,
value2: 0
}
}
}
</script>
```
:::
### Slider with input box
Set value via a input box.
:::demo Set the `show-input` attribute to display an input box on the right.
```html
<template>
<div class="block">
<el-slider
v-model="value"
show-input>
</el-slider>
</div>
</template>
<script>
export default {
data() {
return {
value: 0
}
}
}
</script>
```
:::
### Range selection
Selecting a range of values is supported.
:::demo Setting the `range` attribute activates range mode, where the binding value is an array made up of two boundary values.
```html
<template>
<div class="block">
<el-slider
v-model="value"
range
show-stops
:max="10">
</el-slider>
</div>
</template>
<script>
export default {
data() {
return {
value: [4, 8]
}
}
}
</script>
```
:::
### Vertical mode
:::demo Setting the `vertical` attribute to `true` enables vertical mode. In vertical mode, the `height` attribute is required.
```html
<template>
<div class="block">
<el-slider
v-model="value"
vertical
height="200px">
</el-slider>
</div>
</template>
<script>
export default {
data() {
return {
value: 0
}
}
}
</script>
```
:::
### Show marks
:::demo Setting this `marks` attribute can show mark on slider.
```html
<template>
<div class="block">
<el-slider
v-model="value"
range
:marks="marks">
</el-slider>
</div>
</template>
<script>
export default {
data() {
return {
value: [30, 60],
marks: {
0: '0°C',
8: '8°C',
37: '37°C',
50: {
style: {
color: '#1989FA'
},
label: this.$createElement('strong', '50%')
}
}
}
}
}
</script>
```
:::
## Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value / v-model | binding value | number | — | 0 |
| min | minimum value | number | — | 0 |
| max | maximum value | number | — | 100 |
| disabled | whether Slider is disabled | boolean | — | false |
| step | step size | number | — | 1 |
| show-input | whether to display an input box, works when `range` is false | boolean | — | false |
| show-input-controls | whether to display control buttons when `show-input` is true | boolean | — | true |
| input-size | size of the input box | string | large / medium / small / mini | small |
| show-stops | whether to display breakpoints | boolean | — | false |
| show-tooltip | whether to display tooltip value | boolean | — | true |
| format-tooltip | format to display tooltip value | function(value) | — | — |
| range | whether to select a range | boolean | — | false |
| vertical | vertical mode | boolean | — | false |
| height | Slider height, required in vertical mode | string | — | — |
| label | label for screen reader | string | — | — |
| debounce | debounce delay when typing, in milliseconds, works when `show-input` is true | number | — | 300 |
| tooltip-class | custom class name for the tooltip | string | — | — |
| marks | marks type of key must be `number` and must in closed interval `[min, max]`, each mark can custom style| object | — | — |
## Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| change | triggers when the value changes (if the mouse is being dragged, this event only fires when the mouse is released) | value after changing |
| input | triggers when the data changes (It'll be emitted in real time during sliding) | value after changing |

View File

@@ -0,0 +1,160 @@
## Steps
Guide the user to complete tasks in accordance with the process. Its steps can be set according to the actual application scenario and the number of the steps can't be less than 2.
### Basic usage
Simple step bar.
:::demo Set `active` attribute with `Number` type, which indicates the index of steps and starts from 0. You can set `space` attribute when the width of the step needs to be fixed which accepts `Number` type. The unit of the `space` attribute is `px`. If not set, it is responsive. Setting the `finish-status` attribute can change the state of the steps that have been completed.
```html
<el-steps :active="active" finish-status="success">
<el-step title="Step 1"></el-step>
<el-step title="Step 2"></el-step>
<el-step title="Step 3"></el-step>
</el-steps>
<el-button style="margin-top: 12px;" @click="next">Next step</el-button>
<script>
export default {
data() {
return {
active: 0
};
},
methods: {
next() {
if (this.active++ > 2) this.active = 0;
}
}
}
</script>
```
:::
### Step bar that contains status
Shows the status of the step for each step.
:::demo Use `title` attribute to set the name of the step, or override the attribute by using a named `slot`. We have listed all the slot names for you at the end of this page.
```html
<el-steps :space="200" :active="1" finish-status="success">
<el-step title="Done"></el-step>
<el-step title="Processing"></el-step>
<el-step title="Step 3"></el-step>
</el-steps>
```
:::
### Center
Title and desription can be centered.
:::demo
```html
<el-steps :active="2" align-center>
<el-step title="Step 1" description="Some description"></el-step>
<el-step title="Step 2" description="Some description"></el-step>
<el-step title="Step 3" description="Some description"></el-step>
<el-step title="Step 4" description="Some description"></el-step>
</el-steps>
```
:::
### Step bar with description
There is description for each step.
:::demo
```html
<el-steps :active="1">
<el-step title="Step 1" description="Some description"></el-step>
<el-step title="Step 2" description="Some description"></el-step>
<el-step title="Step 3" description="Some description"></el-step>
</el-steps>
```
:::
### Step bar with icon
A variety of custom icons can be used in the step bar.
:::demo The icon is set by the `icon` property. The types of icons can be found in the document for the Icon component. In addition, you can customize the icon through a named `slot`.
```html
<el-steps :active="1">
<el-step title="Step 1" icon="el-icon-edit"></el-step>
<el-step title="Step 2" icon="el-icon-upload"></el-step>
<el-step title="Step 3" icon="el-icon-picture"></el-step>
</el-steps>
```
:::
### Vertical step bar
Vertical step bars.
:::demo You only need to set the `direction` attribute to` vertical` in the `el-steps` element.
```html
<div style="height: 300px;">
<el-steps direction="vertical" :active="1">
<el-step title="Step 1"></el-step>
<el-step title="Step 2"></el-step>
<el-step title="Step 3"></el-step>
</el-steps>
</div>
```
:::
### Simple step bar
Simple step bars, where `align-center`, `description`, `direction` and `space` will be ignored.
:::demo
```html
<el-steps :space="200" :active="1" simple>
<el-step title="Step 1" icon="el-icon-edit"></el-step>
<el-step title="Step 2" icon="el-icon-upload"></el-step>
<el-step title="Step 3" icon="el-icon-picture"></el-step>
</el-steps>
<el-steps :active="1" finish-status="success" simple style="margin-top: 20px">
<el-step title="Step 1" ></el-step>
<el-step title="Step 2" ></el-step>
<el-step title="Step 3" ></el-step>
</el-steps>
```
:::
### Steps Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| space | the spacing of each step, will be responsive if omitted. Supports percentage. | number / string | — | — |
| direction | display direction | string | vertical/horizontal | horizontal |
| active | current activation step | number | — | 0 |
| process-status | status of current step | string | wait / process / finish / error / success | process |
| finish-status | status of end step | string | wait / process / finish / error / success | finish |
| align-center | center title and description | boolean | — | false |
| simple | whether to apply simple theme | boolean | - | false |
### Step Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| title | step title | string | — | — |
| description | step description | string | — | — |
| icon | step icon | step icon's class name. Icons can be passed via named slot as well | string | — |
| status | current status. It will be automatically set by Steps if not configured. | wait / process / finish / error / success | - |
### Step Slot
| Name | Description |
|----|----|
| icon | custom icon |
| title | step title |
| description | step description |

View File

@@ -0,0 +1,143 @@
## Switch
Switch is used for switching between two opposing states.
### Basic usage
:::demo Bind `v-model` to a `Boolean` typed variable. The `active-color` and `inactive-color` attribute decides the background color in two states.
```html
<el-switch v-model="value1">
</el-switch>
<el-switch
v-model="value2"
active-color="#13ce66"
inactive-color="#ff4949">
</el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: true
}
}
};
</script>
```
:::
### Text description
:::demo You can add `active-text` and `inactive-text` attribute to show texts.
```html
<el-switch
v-model="value1"
active-text="Pay by month"
inactive-text="Pay by year">
</el-switch>
<el-switch
style="display: block"
v-model="value2"
active-color="#13ce66"
inactive-color="#ff4949"
active-text="Pay by month"
inactive-text="Pay by year">
</el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: true
}
}
};
</script>
```
:::
### Extended value types
:::demo You can set `active-value` and `inactive-value` attributes. They both receive a `Boolean`, `String` or `Number` typed value.
```html
<el-tooltip :content="'Switch value: ' + value" placement="top">
<el-switch
v-model="value"
active-color="#13ce66"
inactive-color="#ff4949"
active-value="100"
inactive-value="0">
</el-switch>
</el-tooltip>
<script>
export default {
data() {
return {
value: '100'
}
}
};
</script>
```
:::
### Disabled
:::demo Adding the `disabled` attribute disables Switch.
```html
<el-switch
v-model="value1"
disabled>
</el-switch>
<el-switch
v-model="value2"
disabled>
</el-switch>
<script>
export default {
data() {
return {
value1: true,
value2: false
}
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|-----| ----| ----| ----|---- |
| value / v-model | binding value | boolean / string / number | — | — |
| disabled | whether Switch is disabled | boolean | — | false |
| width | width of Switch | number | — | 40 |
| active-icon-class | class name of the icon displayed when in `on` state, overrides `active-text` | string | — | — |
| inactive-icon-class |class name of the icon displayed when in `off` state, overrides `inactive-text`| string | — | — |
| active-text | text displayed when in `on` state | string | — | — |
| inactive-text | text displayed when in `off` state | string | — | — |
| active-value | switch value when in `on` state | boolean / string / number | — | true |
| inactive-value | switch value when in `off` state | boolean / string / number | — | false |
| active-color | background color when in `on` state | string | — | #409EFF |
| inactive-color | background color when in `off` state | string | — | #C0CCDA |
| name | input name of Switch | string | — | — |
| validate-event | whether to trigger form validation | boolean | - | true |
### Events
| Event Name | Description | Parameters |
| ---- | ----| ---- |
| change | triggers when value changes | value after changing |
### Methods
| Method | Description | Parameters |
| ------|--------|------- |
| focus | focus the Switch component | — |

1919
examples/docs/en-US/table.md Normal file

File diff suppressed because it is too large Load Diff

305
examples/docs/en-US/tabs.md Normal file
View File

@@ -0,0 +1,305 @@
## Tabs
Divide data collections which are related yet belong to different types.
### Basic usage
Basic and concise tabs.
:::demo Tabs provide a selective card functionality. By default the first tab is selected as active, and you can activate any tab by setting the `value` attribute.
```html
<template>
<el-tabs v-model="activeName" @tab-click="handleClick">
<el-tab-pane label="User" name="first">User</el-tab-pane>
<el-tab-pane label="Config" name="second">Config</el-tab-pane>
<el-tab-pane label="Role" name="third">Role</el-tab-pane>
<el-tab-pane label="Task" name="fourth">Task</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeName: 'first'
};
},
methods: {
handleClick(tab, event) {
console.log(tab, event);
}
}
};
</script>
```
:::
### Card Style
Tabs styled as cards.
:::demo Set `type` to `card` can get a card-styled tab.
```html
<template>
<el-tabs type="card" @tab-click="handleClick">
<el-tab-pane label="User">User</el-tab-pane>
<el-tab-pane label="Config">Config</el-tab-pane>
<el-tab-pane label="Role">Role</el-tab-pane>
<el-tab-pane label="Task">Task</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
activeName: 'first'
};
},
methods: {
handleClick(tab, event) {
console.log(tab, event);
}
}
};
</script>
```
:::
### Border card
Border card tabs.
:::demo Set `type` to `border-card`.
```html
<el-tabs type="border-card">
<el-tab-pane label="User">User</el-tab-pane>
<el-tab-pane label="Config">Config</el-tab-pane>
<el-tab-pane label="Role">Role</el-tab-pane>
<el-tab-pane label="Task">Task</el-tab-pane>
</el-tabs>
```
:::
### Tab position
You can use `tab-position` attribute to set the tab's position.
:::demo You can choose from four directions: `tabPosition="left|right|top|bottom"`
```html
<template>
<el-radio-group v-model="tabPosition" style="margin-bottom: 30px;">
<el-radio-button label="top">top</el-radio-button>
<el-radio-button label="right">right</el-radio-button>
<el-radio-button label="bottom">bottom</el-radio-button>
<el-radio-button label="left">left</el-radio-button>
</el-radio-group>
<el-tabs :tab-position="tabPosition" style="height: 200px;">
<el-tab-pane label="User">User</el-tab-pane>
<el-tab-pane label="Config">Config</el-tab-pane>
<el-tab-pane label="Role">Role</el-tab-pane>
<el-tab-pane label="Task">Task</el-tab-pane>
</el-tabs>
</template>
<script>
export default {
data() {
return {
tabPosition: 'left'
};
}
};
</script>
```
:::
### Custom Tab
You can use named slot to customize the tab label content.
:::demo
```html
<el-tabs type="border-card">
<el-tab-pane>
<span slot="label"><i class="el-icon-date"></i> Route</span>
Route
</el-tab-pane>
<el-tab-pane label="Config">Config</el-tab-pane>
<el-tab-pane label="Role">Role</el-tab-pane>
<el-tab-pane label="Task">Task</el-tab-pane>
</el-tabs>
```
:::
### Add & close tab
Only card type Tabs support addable & closeable.
:::demo
```html
<el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
<el-tab-pane
v-for="(item, index) in editableTabs"
:key="item.name"
:label="item.title"
:name="item.name"
>
{{item.content}}
</el-tab-pane>
</el-tabs>
<script>
export default {
data() {
return {
editableTabsValue: '2',
editableTabs: [{
title: 'Tab 1',
name: '1',
content: 'Tab 1 content'
}, {
title: 'Tab 2',
name: '2',
content: 'Tab 2 content'
}],
tabIndex: 2
}
},
methods: {
handleTabsEdit(targetName, action) {
if (action === 'add') {
let newTabName = ++this.tabIndex + '';
this.editableTabs.push({
title: 'New Tab',
name: newTabName,
content: 'New Tab content'
});
this.editableTabsValue = newTabName;
}
if (action === 'remove') {
let tabs = this.editableTabs;
let activeName = this.editableTabsValue;
if (activeName === targetName) {
tabs.forEach((tab, index) => {
if (tab.name === targetName) {
let nextTab = tabs[index + 1] || tabs[index - 1];
if (nextTab) {
activeName = nextTab.name;
}
}
});
}
this.editableTabsValue = activeName;
this.editableTabs = tabs.filter(tab => tab.name !== targetName);
}
}
}
}
</script>
```
:::
### Customized trigger button of new tab
:::demo
```html
<div style="margin-bottom: 20px;">
<el-button
size="small"
@click="addTab(editableTabsValue)"
>
add tab
</el-button>
</div>
<el-tabs v-model="editableTabsValue" type="card" closable @tab-remove="removeTab">
<el-tab-pane
v-for="(item, index) in editableTabs"
:key="item.name"
:label="item.title"
:name="item.name"
>
{{item.content}}
</el-tab-pane>
</el-tabs>
<script>
export default {
data() {
return {
editableTabsValue: '2',
editableTabs: [{
title: 'Tab 1',
name: '1',
content: 'Tab 1 content'
}, {
title: 'Tab 2',
name: '2',
content: 'Tab 2 content'
}],
tabIndex: 2
}
},
methods: {
addTab(targetName) {
let newTabName = ++this.tabIndex + '';
this.editableTabs.push({
title: 'New Tab',
name: newTabName,
content: 'New Tab content'
});
this.editableTabsValue = newTabName;
},
removeTab(targetName) {
let tabs = this.editableTabs;
let activeName = this.editableTabsValue;
if (activeName === targetName) {
tabs.forEach((tab, index) => {
if (tab.name === targetName) {
let nextTab = tabs[index + 1] || tabs[index - 1];
if (nextTab) {
activeName = nextTab.name;
}
}
});
}
this.editableTabsValue = activeName;
this.editableTabs = tabs.filter(tab => tab.name !== targetName);
}
}
}
</script>
```
:::
### Tabs Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | binding value, name of the selected tab | string | — | name of first tab |
| type | type of Tab | string | card/border-card | — |
| closable | whether Tab is closable | boolean | — | false |
| addable | whether Tab is addable | boolean | — | false |
| editable | whether Tab is addable and closable | boolean | — | false |
| tab-position | position of tabs | string | top/right/bottom/left | top |
| stretch | whether width of tab automatically fits its container | boolean | - | false |
| before-leave | hook function before switching tab. If `false` is returned or a `Promise` is returned and then is rejected, switching will be prevented | Function(activeName, oldActiveName) | — | — |
### Tabs Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| tab-click | triggers when a tab is clicked | clicked tab |
| tab-remove | triggers when tab-remove button is clicked | name of the removed tab |
| tab-add | triggers when tab-add button is clicked | — |
| edit | triggers when tab-add button or tab-remove is clicked | (targetName, action) |
### Tab-pane Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| label | title of the tab | string | — | — |
| disabled | whether Tab is disabled | boolean | — | false |
| name | identifier corresponding to the name of Tabs, representing the alias of the tab-pane | string | — | ordinal number of the tab-pane in the sequence, e.g. the first tab-pane is '1' |
| closable | whether Tab is closable | boolean | — | false |
| lazy | whether Tab is lazily rendered | boolean | — | false |

204
examples/docs/en-US/tag.md Normal file
View File

@@ -0,0 +1,204 @@
## Tag
Used for marking and selection.
### Basic usage
:::demo Use the `type` attribute to define Tag's type. In addition, the `color` attribute can be used to set the background color of the Tag.
```html
<el-tag>Tag 1</el-tag>
<el-tag type="success">Tag 2</el-tag>
<el-tag type="info">Tag 3</el-tag>
<el-tag type="warning">Tag 4</el-tag>
<el-tag type="danger">Tag 5</el-tag>
```
:::
### Removable Tag
:::demo `closable` attribute can be used to define a removable tag. It accepts a `Boolean`. By default the removal of Tag has a fading animation. If you don't want to use it, you can set the `disable-transitions` attribute, which accepts a `Boolean`, to `true`. `close` event triggers when Tag is removed.
```html
<el-tag
v-for="tag in tags"
:key="tag.name"
closable
:type="tag.type">
{{tag.name}}
</el-tag>
<script>
export default {
data() {
return {
tags: [
{ name: 'Tag 1', type: '' },
{ name: 'Tag 2', type: 'success' },
{ name: 'Tag 3', type: 'info' },
{ name: 'Tag 4', type: 'warning' },
{ name: 'Tag 5', type: 'danger' }
]
};
}
}
</script>
```
:::
### Edit Dynamically
You can use the `close` event to add and remove tag dynamically.
:::demo
```html
<el-tag
:key="tag"
v-for="tag in dynamicTags"
closable
:disable-transitions="false"
@close="handleClose(tag)">
{{tag}}
</el-tag>
<el-input
class="input-new-tag"
v-if="inputVisible"
v-model="inputValue"
ref="saveTagInput"
size="mini"
@keyup.enter.native="handleInputConfirm"
@blur="handleInputConfirm"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
<style>
.el-tag + .el-tag {
margin-left: 10px;
}
.button-new-tag {
margin-left: 10px;
height: 32px;
line-height: 30px;
padding-top: 0;
padding-bottom: 0;
}
.input-new-tag {
width: 90px;
margin-left: 10px;
vertical-align: bottom;
}
</style>
<script>
export default {
data() {
return {
dynamicTags: ['Tag 1', 'Tag 2', 'Tag 3'],
inputVisible: false,
inputValue: ''
};
},
methods: {
handleClose(tag) {
this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
},
showInput() {
this.inputVisible = true;
this.$nextTick(_ => {
this.$refs.saveTagInput.$refs.input.focus();
});
},
handleInputConfirm() {
let inputValue = this.inputValue;
if (inputValue) {
this.dynamicTags.push(inputValue);
}
this.inputVisible = false;
this.inputValue = '';
}
}
}
</script>
```
:::
### Sizes
Besides default size, Tag component provides three additional sizes for you to choose among different scenarios.
:::demo Use attribute `size` to set additional sizes with `medium`, `small` or `mini`.
```html
<el-tag>Default</el-tag>
<el-tag size="medium">Medium</el-tag>
<el-tag size="small">Small</el-tag>
<el-tag size="mini">Mini</el-tag>
```
:::
### Theme
Tag provide three different themes: `dark``light` and `plain`
:::demo Using `effect` to change, default is `light`
```html
<div class="tag-group">
<span class="tag-group__title">Dark</span>
<el-tag
v-for="item in items"
:key="item.label"
:type="item.type"
effect="dark">
{{ item.label }}
</el-tag>
</div>
<div class="tag-group">
<span class="tag-group__title">Plain</span>
<el-tag
v-for="item in items"
:key="item.label"
:type="item.type"
effect="plain">
{{ item.label }}
</el-tag>
</div>
<script>
export default {
data() {
return {
items: [
{ type: '', label: 'Tag 1' },
{ type: 'success', label: 'Tag 2' },
{ type: 'info', label: 'Tag 3' },
{ type: 'danger', label: 'Tag 4' },
{ type: 'warning', label: 'Tag 5' }
]
}
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| type | component type | string | success/info/warning/danger | — |
| closable | whether Tag can be removed | boolean | — | false |
| disable-transitions | whether to disable animations | boolean | — | false |
| hit | whether Tag has a highlighted border | boolean | — | false |
| color | background color of the Tag | string | — | — |
| size | tag size | string | medium / small / mini | — |
| effect | component theme | string | dark / light / plain | light |
### Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| click | triggers when Tag is clicked | — |
| close | triggers when Tag is removed | — |

View File

@@ -0,0 +1,199 @@
## TimePicker
Use Time Picker for time input.
### Fixed time picker
Provide a list of fixed time for users to choose.
:::demo Use `el-time-select` label, then assign start time, end time and time step with `start`, `end` and `step`.
```html
<el-time-select
v-model="value"
:picker-options="{
start: '08:30',
step: '00:15',
end: '18:30'
}"
placeholder="Select time">
</el-time-select>
<script>
export default {
data() {
return {
value: ''
};
}
}
</script>
```
:::
### Arbitrary time picker
Can pick an arbitrary time.
:::demo Use `el-time-picker` label, and you can limit the time range by specifying `selectableRange`. By default, you can scroll the mouse wheel to pick time, alternatively you can use the control arrows when the `arrow-control` attribute is set.
```html
<template>
<el-time-picker
v-model="value1"
:picker-options="{
selectableRange: '18:30:00 - 20:30:00'
}"
placeholder="Arbitrary time">
</el-time-picker>
<el-time-picker
arrow-control
v-model="value2"
:picker-options="{
selectableRange: '18:30:00 - 20:30:00'
}"
placeholder="Arbitrary time">
</el-time-picker>
</template>
<script>
export default {
data() {
return {
value1: new Date(2016, 9, 10, 18, 40),
value2: new Date(2016, 9, 10, 18, 40)
};
}
}
</script>
```
:::
### Fixed time range
If start time is picked at first, then the end time will change accordingly.
:::demo
```html
<template>
<el-time-select
placeholder="Start time"
v-model="startTime"
:picker-options="{
start: '08:30',
step: '00:15',
end: '18:30'
}">
</el-time-select>
<el-time-select
placeholder="End time"
v-model="endTime"
:picker-options="{
start: '08:30',
step: '00:15',
end: '18:30',
minTime: startTime
}">
</el-time-select>
</template>
<script>
export default {
data() {
return {
startTime: '',
endTime: ''
};
}
}
</script>
```
:::
### Arbitrary time range
Can pick an arbitrary time range.
:::demo We can pick a time range by adding an `is-range` attribute. Also, `arrow-control` is supported in range mode.
```html
<template>
<el-time-picker
is-range
v-model="value1"
range-separator="To"
start-placeholder="Start time"
end-placeholder="End time">
</el-time-picker>
<el-time-picker
is-range
arrow-control
v-model="value2"
range-separator="To"
start-placeholder="Start time"
end-placeholder="End time">
</el-time-picker>
</template>
<script>
export default {
data() {
return {
value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
value2: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)]
};
}
}
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value / v-model | binding value | date(TimePicker) / string(TimeSelect) | - | - |
| readonly | whether TimePicker is read only | boolean | — | false |
| disabled | whether TimePicker is disabled | boolean | — | false |
| editable | whether the input is editable | boolean | — | true |
| clearable | whether to show clear button | boolean | — | true |
| size | size of Input | string | medium / small / mini | — |
| placeholder | placeholder in non-range mode | string | — | — |
| start-placeholder | placeholder for the start time in range mode | string | — | — |
| end-placeholder | placeholder for the end time in range mode | string | — | — |
| is-range | whether to pick a time range, only works with `<el-time-picker>` | boolean | — | false |
| arrow-control | whether to pick time using arrow buttons, only works with `<el-time-picker>` | boolean | — | false |
| align | alignment | left / center / right | left |
| popper-class | custom class name for TimePicker's dropdown | string | — | — |
| picker-options | additional options, check the table below | object | — | {} |
| range-separator | range separator | string | - | '-' |
| default-value | optional, default date of the calendar | Date for TimePicker, string for TimeSelect | anything accepted by `new Date()` for TimePicker, selectable value for TimeSelect | — |
| value-format | optional, only for TimePicker, format of binding value. If not specified, the binding value will be a Date object | string | see [date formats](#/en-US/component/date-picker#date-formats) | — |
| name | same as `name` in native input | string | — | — |
| prefix-icon | Custom prefix icon class | string | — | el-icon-time |
| clear-icon | Custom clear icon class | string | — | el-icon-circle-close |
### Time Select Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| start | start time | string | — | 09:00 |
| end | end time | string | — | 18:00 |
| step | time step | string | — | 00:30 |
| minTime | minimum time, any time before this time will be disabled | string | — | 00:00 |
| maxTime | maximum time, any time after this time will be disabled | string | — | — |
### Time Picker Options
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| selectableRange | available time range, e.g.`'18:30:00 - 20:30:00'`or`['09:30:00 - 12:00:00', '14:30:00 - 18:30:00']` | string / array | — | — |
| format | format of the picker | string | hour `HH`, minute `mm`, second `ss`, AM/PM `A` | HH:mm:ss |
### Events
| Event Name | Description | Parameters |
|---------|--------|---------|
| change | triggers when user confirms the value | component's binding value |
| blur | triggers when Input blurs | component instance |
| focus | triggers when Input focuses | component instance |
### Methods
| Method | Description | Parameters |
| ---- | ---- | ---- |
| focus | focus the Input component | - |

View File

@@ -0,0 +1,153 @@
## Timeline
Visually display timeline.
### Basic usage
Timeline can be split into multiple activities in ascending or descending. Timestamps are important features that distinguish them from other components. Note the difference with Steps.
:::demo
```html
<div class="block">
<div class="radio">
Order:
<el-radio-group v-model="reverse">
<el-radio :label="true">descending</el-radio>
<el-radio :label="false">ascending</el-radio>
</el-radio-group>
</div>
<el-timeline :reverse="reverse">
<el-timeline-item
v-for="(activity, index) in activities"
:key="index"
:timestamp="activity.timestamp">
{{activity.content}}
</el-timeline-item>
</el-timeline>
</div>
<script>
export default {
data() {
return {
reverse: true,
activities: [{
content: 'Event start',
timestamp: '2018-04-15'
}, {
content: 'Approved',
timestamp: '2018-04-13'
}, {
content: 'Success',
timestamp: '2018-04-11'
}]
};
}
};
</script>
```
:::
### Custom node
Size, color, and icons can be customized in node.
:::demo
```html
<div class="block">
<el-timeline>
<el-timeline-item
v-for="(activity, index) in activities"
:key="index"
:icon="activity.icon"
:type="activity.type"
:color="activity.color"
:size="activity.size"
:timestamp="activity.timestamp">
{{activity.content}}
</el-timeline-item>
</el-timeline>
</div>
<script>
export default {
data() {
return {
activities: [{
content: 'Custom icon',
timestamp: '2018-04-12 20:46',
size: 'large',
type: 'primary',
icon: 'el-icon-more'
}, {
content: 'Custom color',
timestamp: '2018-04-03 20:46',
color: '#0bbd87'
}, {
content: 'Custom size',
timestamp: '2018-04-03 20:46',
size: 'large'
}, {
content: 'Default node',
timestamp: '2018-04-03 20:46'
}]
};
}
};
</script>
```
:::
### Custom timestamp
Timestamp can be placed on top of content when content is too high.
:::demo
```html
<div class="block">
<el-timeline>
<el-timeline-item timestamp="2018/4/12" placement="top">
<el-card>
<h4>Update Github template</h4>
<p>Tom committed 2018/4/12 20:46</p>
</el-card>
</el-timeline-item>
<el-timeline-item timestamp="2018/4/3" placement="top">
<el-card>
<h4>Update Github template</h4>
<p>Tom committed 2018/4/3 20:46</p>
</el-card>
</el-timeline-item>
<el-timeline-item timestamp="2018/4/2" placement="top">
<el-card>
<h4>Update Github template</h4>
<p>Tom committed 2018/4/2 20:46</p>
</el-card>
</el-timeline-item>
</el-timeline>
</div>
```
:::
### Timeline Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| reverse | whether the node is ascending or descending, default is ascending | boolean | — | false |
### Timeline-item Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| timestamp | timestamp content | string | - | — |
| hide-timestamp | whether to show timestamp | boolean | — | false |
| placement | position of timestamp | string | top / bottom | bottom |
| type | node type | string | primary / success / warning / danger / info | - |
| color | background color of node | string | hsl / hsv / hex / rgb | - |
| size | node size | string | normal / large | normal |
| icon | icon class name | string | — | - |
### Timeline-Item Slot
| name | Description |
|------|--------|
| — | Custom content for timeline item |
| dot | Custom defined node |

View File

@@ -0,0 +1,196 @@
## Tooltip
Display prompt information for mouse hover.
### Basic usage
Tooltip has 9 placements.
:::demo Use attribute `content` to set the display content when hover. The attribute `placement` determines the position of the tooltip. Its value is `[orientation]-[alignment]` with four orientations `top`, `left`, `right`, `bottom` and three alignments `start`, `end`, `null`, and the default alignment is null. Take `placement="left-end"` for example, Tooltip will display on the left of the element which you are hovering and the bottom of the tooltip aligns with the bottom of the element.
```html
<div class="box">
<div class="top">
<el-tooltip class="item" effect="dark" content="Top Left prompts info" placement="top-start">
<el-button>top-start</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Top Center prompts info" placement="top">
<el-button>top</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Top Right prompts info" placement="top-end">
<el-button>top-end</el-button>
</el-tooltip>
</div>
<div class="left">
<el-tooltip class="item" effect="dark" content="Left Top prompts info" placement="left-start">
<el-button>left-start</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Left Center prompts info" placement="left">
<el-button>left</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Left Bottom prompts info" placement="left-end">
<el-button>left-end</el-button>
</el-tooltip>
</div>
<div class="right">
<el-tooltip class="item" effect="dark" content="Right Top prompts info" placement="right-start">
<el-button>right-start</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Right Center prompts info" placement="right">
<el-button>right</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Right Bottom prompts info" placement="right-end">
<el-button>right-end</el-button>
</el-tooltip>
</div>
<div class="bottom">
<el-tooltip class="item" effect="dark" content="Bottom Left prompts info" placement="bottom-start">
<el-button>bottom-start</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Bottom Center prompts info" placement="bottom">
<el-button>bottom</el-button>
</el-tooltip>
<el-tooltip class="item" effect="dark" content="Bottom Right prompts info" placement="bottom-end">
<el-button>bottom-end</el-button>
</el-tooltip>
</div>
</div>
<style>
.box {
width: 400px;
.top {
text-align: center;
}
.left {
float: left;
width: 110px;
}
.right {
float: right;
width: 110px;
}
.bottom {
clear: both;
text-align: center;
}
.item {
margin: 4px;
}
.left .el-tooltip__popper,
.right .el-tooltip__popper {
padding: 8px 10px;
}
.el-button {
width: 110px;
}
}
</style>
```
:::
### Theme
Tooltip has two themes: `dark` and `light`
:::demo Set `effect` to modify theme, and the default value is `dark`.
```html
<el-tooltip content="Top center" placement="top">
<el-button>Dark</el-button>
</el-tooltip>
<el-tooltip content="Bottom center" placement="bottom" effect="light">
<el-button>Light</el-button>
</el-tooltip>
```
:::
### More Content
Display multiple lines of text and set their format.
:::demo Override attribute `content` of `el-tooltip` by adding a slot named `content`.
```html
<el-tooltip placement="top">
<div slot="content">multiple lines<br/>second line</div>
<el-button>Top center</el-button>
</el-tooltip>
```
:::
### Advanced usage
In addition to basic usages, there are some attributes that allow you to customize your own:
`transition` attribute allows you to customize the animation in which the tooltip shows or hides, and the default value is el-fade-in-linear.
`disabled` attribute allows you to disable `tooltip`. You just need set it to `true`.
In fact, Tooltip is an extension based on [Vue-popper](https://github.com/element-component/vue-popper), you can use any attribute that are allowed in Vue-popper.
:::demo
```html
<template>
<el-tooltip :disabled="disabled" content="click to close tooltip function" placement="bottom" effect="light">
<el-button @click="disabled = !disabled">click to {{disabled ? 'active' : 'close'}} tooltip function</el-button>
</el-tooltip>
</template>
<script>
export default {
data() {
return {
disabled: false
};
}
};
</script>
<style>
.slide-fade-enter-active {
transition: all .3s ease;
}
.slide-fade-leave-active {
transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .expand-fade-leave-active {
margin-left: 20px;
opacity: 0;
}
</style>
```
:::
:::tip
The `router-link` component is not supported in tooltip, please use `vm.$router.push`.
Disabled form elements are not supported for Tooltip, more information can be found at [MDN](https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter). You need to wrap the disabled form element with a container element for Tooltip to work.
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|----------------|---------|-----------|-------------|--------|
| effect | Tooltip theme | string | dark/light | dark |
| content | display content, can be overridden by `slot#content` | String | — | — |
| placement | position of Tooltip | string | top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end | bottom |
| value / v-model | visibility of Tooltip | boolean | — | false |
| disabled | whether Tooltip is disabled | boolean | — | false |
| offset | offset of the Tooltip | number | — | 0 |
| transition | animation name | string | — | el-fade-in-linear |
| visible-arrow | whether an arrow is displayed. For more information, check [Vue-popper](https://github.com/element-component/vue-popper) page | boolean | — | true |
| popper-options | [popper.js](https://popper.js.org/documentation.html) parameters | Object | refer to [popper.js](https://popper.js.org/documentation.html) doc | `{ boundariesElement: 'body', gpuAcceleration: false }` |
| open-delay | delay of appearance, in millisecond | number | — | 0 |
| manual | whether to control Tooltip manually. `mouseenter` and `mouseleave` won't have effects if set to `true` | boolean | — | false |
| popper-class | custom class name for Tooltip's popper | string | — | — |
| enterable | whether the mouse can enter the tooltip | Boolean | — | true |
| hide-after | timeout in milliseconds to hide tooltip | number | — | 0 |
| tabindex | [tabindex](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) of Tooltip | number | — | 0 |

View File

@@ -0,0 +1,252 @@
## Transfer
### Basic usage
:::demo Data is passed to Transfer via the `data` attribute. The data needs to be an object array, and each object should have these attributes: `key` being the identification of the data item, `label` being the displayed text, and `disabled` indicating if the data item is disabled. Items inside the target list are in sync with the variable binding to `v-model`, and the value of that variable is an array of target item keys. So, if you don't want the target list be initially empty, you can initialize the `v-model` with an array.
```html
<template>
<el-transfer
v-model="value"
:data="data">
</el-transfer>
</template>
<script>
export default {
data() {
const generateData = _ => {
const data = [];
for (let i = 1; i <= 15; i++) {
data.push({
key: i,
label: `Option ${ i }`,
disabled: i % 4 === 0
});
}
return data;
};
return {
data: generateData(),
value: [1, 4]
};
}
};
</script>
```
:::
### Filterable
You can search and filter data items.
:::demo Set the `filterable` attribute to `true` to enable filter mode. By default, if the data item `label` contains the search keyword, it will be included in the search result. Also, you can implement you own filter method with the `filter-method` attribute. It takes a method and passes search keyword and each data item to it whenever the keyword changes. For a certain data item, if the method returns true, it will be included in the result list.
```html
<template>
<el-transfer
filterable
:filter-method="filterMethod"
filter-placeholder="State Abbreviations"
v-model="value"
:data="data">
</el-transfer>
</template>
<script>
export default {
data() {
const generateData = _ => {
const data = [];
const states = ['California', 'Illinois', 'Maryland', 'Texas', 'Florida', 'Colorado', 'Connecticut '];
const initials = ['CA', 'IL', 'MD', 'TX', 'FL', 'CO', 'CT'];
states.forEach((city, index) => {
data.push({
label: city,
key: index,
initial: initials[index]
});
});
return data;
};
return {
data: generateData(),
value: [],
filterMethod(query, item) {
return item.initial.toLowerCase().indexOf(query.toLowerCase()) > -1;
}
};
}
};
</script>
```
:::
### Customizable
You can customize list titles, button texts, render function for data items, checking status texts in list footer and list footer contents.
:::demo Use `titles`, `button-texts`, `render-content` and `format` to respectively customize list titles, button texts, render function for data items, checking status texts in list header. Plus, you can also use scoped slot to customize data items. For list footer contents, two named slots are provided: `left-footer` and `right-footer`. Plus, if you want some items initially checked, you can use `left-default-checked` and `right-default-checked`. Finally, this example demonstrate the `change` event. Note that this demo can't run in jsfiddle because it doesn't support JSX syntax. In a real project, `render-content` will work if relevant dependencies are correctly configured.
```html
<template>
<p style="text-align: center; margin: 0 0 20px">Customize data items using render-content</p>
<div style="text-align: center">
<el-transfer
style="text-align: left; display: inline-block"
v-model="value"
filterable
:left-default-checked="[2, 3]"
:right-default-checked="[1]"
:render-content="renderFunc"
:titles="['Source', 'Target']"
:button-texts="['To left', 'To right']"
:format="{
noChecked: '${total}',
hasChecked: '${checked}/${total}'
}"
@change="handleChange"
:data="data">
<el-button class="transfer-footer" slot="left-footer" size="small">Operation</el-button>
<el-button class="transfer-footer" slot="right-footer" size="small">Operation</el-button>
</el-transfer>
<p style="text-align: center; margin: 50px 0 20px">Customize data items using scoped slot</p>
<div style="text-align: center">
<el-transfer
style="text-align: left; display: inline-block"
v-model="value4"
filterable
:left-default-checked="[2, 3]"
:right-default-checked="[1]"
:titles="['Source', 'Target']"
:button-texts="['To left', 'To right']"
:format="{
noChecked: '${total}',
hasChecked: '${checked}/${total}'
}"
@change="handleChange"
:data="data">
<span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>
<el-button class="transfer-footer" slot="left-footer" size="small">Operation</el-button>
<el-button class="transfer-footer" slot="right-footer" size="small">Operation</el-button>
</el-transfer>
</div>
</div>
</template>
<style>
.transfer-footer {
margin-left: 20px;
padding: 6px 5px;
}
</style>
<script>
export default {
data() {
const generateData = _ => {
const data = [];
for (let i = 1; i <= 15; i++) {
data.push({
key: i,
label: `Option ${ i }`,
disabled: i % 4 === 0
});
}
return data;
};
return {
data: generateData(),
value: [1],
value4: [1],
renderFunc(h, option) {
return <span>{ option.key } - { option.label }</span>;
}
};
},
methods: {
handleChange(value, direction, movedKeys) {
console.log(value, direction, movedKeys);
}
}
};
</script>
```
:::
### Prop aliases
By default, Transfer looks for `key`, `label` and `disabled` in a data item. If your data items have different key names, you can use the `props` attribute to define aliases.
:::demo The data items in this example do not have `key`s or `label`s, instead they have `value`s and `desc`s. So you need to set aliases for `key` and `label`.
```html
<template>
<el-transfer
v-model="value"
:props="{
key: 'value',
label: 'desc'
}"
:data="data">
</el-transfer>
</template>
<script>
export default {
data() {
const generateData = _ => {
const data = [];
for (let i = 1; i <= 15; i++) {
data.push({
value: i,
desc: `Option ${ i }`,
disabled: i % 4 === 0
});
}
return data;
};
return {
data: generateData(),
value: []
};
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
|---------- |-------- |---------- |------------- |-------- |
| value / v-model | binding value | array | — | — |
| data | data source | array[{ key, label, disabled }] | — | [ ] |
| filterable | whether Transfer is filterable | boolean | — | false |
| filter-placeholder | placeholder for the filter input | string | — | Enter keyword |
| filter-method | custom filter method | function | — | — |
| target-order | order strategy for elements in the target list. If set to `original`, the elements will keep the same order as the data source. If set to `push`, the newly added elements will be pushed to the bottom. If set to `unshift`, the newly added elements will be inserted on the top | string | original / push / unshift | original |
| titles | custom list titles | array | — | ['List 1', 'List 2'] |
| button-texts | custom button texts | array | — | [ ] |
| render-content | custom render function for data items | function(h, option) | — | — |
| format | texts for checking status in list header | object{noChecked, hasChecked} | — | { noChecked: '${checked}/${total}', hasChecked: '${checked}/${total}' } |
| props | prop aliases for data source | object{key, label, disabled} | — | — |
| left-default-checked | key array of initially checked data items of the left list | array | — | [ ] |
| right-default-checked | key array of initially checked data items of the right list | array | — | [ ] |
### Slot
| Name | Description |
|------|--------|
| left-footer | content of left list footer |
| right-footer | content of right list footer |
### Scoped Slot
| Name | Description |
|------|--------|
| — | Custom content for data items. The scope parameter is { option } |
### Methods
| Method | Description | Parameters |
| ---- | ---- | ---- |
| clearQuery | clear the filter keyword of a certain panel | 'left' / 'right' |
### Events
| Event Name | Description | Parameters |
|---------- |-------- |---------- |
| change | triggers when data items change in the right list | key array of current data items in the right list, transfer direction (left or right), moved item keys |
| left-check-change | triggers when end user changes the checked state of any data item in the left list | key array of currently checked items, key array of items whose checked state have changed |
| right-check-change | triggers when end user changes the checked state of any data item in the right list | key array of currently checked items, key array of items whose checked state have changed |

View File

@@ -0,0 +1,155 @@
## Built-in transition
You can use Element's built-in transitions directly. Before that, please read the [transition docs](https://vuejs.org/v2/api/#transition).
### fade
:::demo We have two fading effects: `el-fade-in-linear` and `el-fade-in`.
```html
<template>
<div>
<el-button @click="show = !show">Click Me</el-button>
<div style="display: flex; margin-top: 20px; height: 100px;">
<transition name="el-fade-in-linear">
<div v-show="show" class="transition-box">.el-fade-in-linear</div>
</transition>
<transition name="el-fade-in">
<div v-show="show" class="transition-box">.el-fade-in</div>
</transition>
</div>
</div>
</template>
<script>
export default {
data: () => ({
show: true
})
}
</script>
<style>
.transition-box {
margin-bottom: 10px;
width: 200px;
height: 100px;
border-radius: 4px;
background-color: #409EFF;
text-align: center;
color: #fff;
padding: 40px 20px;
box-sizing: border-box;
margin-right: 20px;
}
</style>
```
:::
### zoom
:::demo `el-zoom-in-center`, `el-zoom-in-top` and `el-zoom-in-bottom` are provided.
```html
<template>
<div>
<el-button @click="show2 = !show2">Click Me</el-button>
<div style="display: flex; margin-top: 20px; height: 100px;">
<transition name="el-zoom-in-center">
<div v-show="show2" class="transition-box">.el-zoom-in-center</div>
</transition>
<transition name="el-zoom-in-top">
<div v-show="show2" class="transition-box">.el-zoom-in-top</div>
</transition>
<transition name="el-zoom-in-bottom">
<div v-show="show2" class="transition-box">.el-zoom-in-bottom</div>
</transition>
</div>
</div>
</template>
<script>
export default {
data: () => ({
show2: true
})
}
</script>
<style>
.transition-box {
margin-bottom: 10px;
width: 200px;
height: 100px;
border-radius: 4px;
background-color: #409EFF;
text-align: center;
color: #fff;
padding: 40px 20px;
box-sizing: border-box;
margin-right: 20px;
}
</style>
```
:::
### collapse
For collapse effect, use the `el-collapse-transition` component.
:::demo
```html
<template>
<div>
<el-button @click="show3 = !show3">Click Me</el-button>
<div style="margin-top: 20px; height: 200px;">
<el-collapse-transition>
<div v-show="show3">
<div class="transition-box">el-collapse-transition</div>
<div class="transition-box">el-collapse-transition</div>
</div>
</el-collapse-transition>
</div>
</div>
</template>
<script>
export default {
data: () => ({
show3: true
})
}
</script>
<style>
.transition-box {
margin-bottom: 10px;
width: 200px;
height: 100px;
border-radius: 4px;
background-color: #409EFF;
text-align: center;
color: #fff;
padding: 40px 20px;
box-sizing: border-box;
margin-right: 20px;
}
</style>
```
:::
### On demand
```js
// fade/zoom
import 'element-ui/lib/theme-chalk/base.css';
// collapse
import CollapseTransition from 'element-ui/lib/transitions/collapse-transition';
import Vue from 'vue'
Vue.component(CollapseTransition.name, CollapseTransition)
```

866
examples/docs/en-US/tree.md Normal file
View File

@@ -0,0 +1,866 @@
## Tree
Display a set of data with hierarchies.
### Basic usage
Basic tree structure.
:::demo
```html
<el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
<script>
export default {
data() {
return {
data: [{
label: 'Level one 1',
children: [{
label: 'Level two 1-1',
children: [{
label: 'Level three 1-1-1'
}]
}]
}, {
label: 'Level one 2',
children: [{
label: 'Level two 2-1',
children: [{
label: 'Level three 2-1-1'
}]
}, {
label: 'Level two 2-2',
children: [{
label: 'Level three 2-2-1'
}]
}]
}, {
label: 'Level one 3',
children: [{
label: 'Level two 3-1',
children: [{
label: 'Level three 3-1-1'
}]
}, {
label: 'Level two 3-2',
children: [{
label: 'Level three 3-2-1'
}]
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
},
methods: {
handleNodeClick(data) {
console.log(data);
}
}
};
</script>
```
:::
### Selectable
Used for node selection.
:::demo This example also shows how to load node data asynchronously.
```html
<el-tree
:props="props"
:load="loadNode"
lazy
show-checkbox
@check-change="handleCheckChange">
</el-tree>
<script>
export default {
data() {
return {
props: {
label: 'name',
children: 'zones'
},
count: 1
};
},
methods: {
handleCheckChange(data, checked, indeterminate) {
console.log(data, checked, indeterminate);
},
handleNodeClick(data) {
console.log(data);
},
loadNode(node, resolve) {
if (node.level === 0) {
return resolve([{ name: 'Root1' }, { name: 'Root2' }]);
}
if (node.level > 3) return resolve([]);
var hasChild;
if (node.data.name === 'region1') {
hasChild = true;
} else if (node.data.name === 'region2') {
hasChild = false;
} else {
hasChild = Math.random() > 0.5;
}
setTimeout(() => {
var data;
if (hasChild) {
data = [{
name: 'zone' + this.count++
}, {
name: 'zone' + this.count++
}];
} else {
data = [];
}
resolve(data);
}, 500);
}
}
};
</script>
```
:::
### Custom leaf node in lazy mode
:::demo A node's data is not fetched until it is clicked, so the Tree cannot predict whether a node is a leaf node. That's why a drop-down button is added to each node, and if it is a leaf node, the drop-down button will disappear when clicked. That being said, you can also tell the Tree in advance whether the node is a leaf node, avoiding the render of the drop-down button before a leaf node.
```html
<el-tree
:props="props"
:load="loadNode"
lazy
show-checkbox>
</el-tree>
<script>
export default {
data() {
return {
props: {
label: 'name',
children: 'zones',
isLeaf: 'leaf'
},
};
},
methods: {
loadNode(node, resolve) {
if (node.level === 0) {
return resolve([{ name: 'region' }]);
}
if (node.level > 1) return resolve([]);
setTimeout(() => {
const data = [{
name: 'leaf',
leaf: true
}, {
name: 'zone'
}];
resolve(data);
}, 500);
}
}
};
</script>
```
:::
### Disabled checkbox
The checkbox of a node can be set as disabled.
:::demo In the example, 'disabled' property is declared in defaultProps, and some nodes are set as 'disabled:true'. The corresponding checkboxes are disabled and can't be clicked.
```html
<el-tree
:data="data"
:props="defaultProps"
show-checkbox
@check-change="handleCheckChange">
</el-tree>
<script>
export default {
data() {
return {
data: [{
id: 1,
label: 'Level one 1',
children: [{
id: 3,
label: 'Level two 2-1',
children: [{
id: 4,
label: 'Level three 3-1-1'
}, {
id: 5,
label: 'Level three 3-1-2',
disabled: true
}]
}, {
id: 2,
label: 'Level two 2-2',
disabled: true,
children: [{
id: 6,
label: 'Level three 3-2-1'
}, {
id: 7,
label: 'Level three 3-2-2',
disabled: true
}]
}]
}],
defaultProps: {
children: 'children',
label: 'label',
disabled: 'disabled',
},
};
}
};
</script>
```
:::
### Default expanded and default checked
Tree nodes can be initially expanded or checked
:::demo Use `default-expanded-keys` and `default-checked-keys` to set initially expanded and initially checked nodes respectively. Note that for them to work, `node-key` is required. Its value is the name of a key in the data object, and the value of that key should be unique across the whole tree.
```html
<el-tree
:data="data"
show-checkbox
node-key="id"
:default-expanded-keys="[2, 3]"
:default-checked-keys="[5]"
:props="defaultProps">
</el-tree>
<script>
export default {
data() {
return {
data: [{
id: 1,
label: 'Level one 1',
children: [{
id: 4,
label: 'Level two 1-1',
children: [{
id: 9,
label: 'Level three 1-1-1'
}, {
id: 10,
label: 'Level three 1-1-2'
}]
}]
}, {
id: 2,
label: 'Level one 2',
children: [{
id: 5,
label: 'Level two 2-1'
}, {
id: 6,
label: 'Level two 2-2'
}]
}, {
id: 3,
label: 'Level one 3',
children: [{
id: 7,
label: 'Level two 3-1'
}, {
id: 8,
label: 'Level two 3-2'
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
}
};
</script>
```
:::
### Checking tree nodes
:::demo This example shows how to get and set checked nodes. They both can be done in two approaches: node and key. If you are taking the key approach, `node-key` is required.
```html
<el-tree
:data="data"
show-checkbox
default-expand-all
node-key="id"
ref="tree"
highlight-current
:props="defaultProps">
</el-tree>
<div class="buttons">
<el-button @click="getCheckedNodes">get by node</el-button>
<el-button @click="getCheckedKeys">get by key</el-button>
<el-button @click="setCheckedNodes">set by node</el-button>
<el-button @click="setCheckedKeys">set by key</el-button>
<el-button @click="resetChecked">reset</el-button>
</div>
<script>
export default {
methods: {
getCheckedNodes() {
console.log(this.$refs.tree.getCheckedNodes());
},
getCheckedKeys() {
console.log(this.$refs.tree.getCheckedKeys());
},
setCheckedNodes() {
this.$refs.tree.setCheckedNodes([{
id: 5,
label: 'Level two 2-1'
}, {
id: 9,
label: 'Level three 1-1-1'
}]);
},
setCheckedKeys() {
this.$refs.tree.setCheckedKeys([3]);
},
resetChecked() {
this.$refs.tree.setCheckedKeys([]);
}
},
data() {
return {
data: [{
id: 1,
label: 'Level one 1',
children: [{
id: 4,
label: 'Level two 1-1',
children: [{
id: 9,
label: 'Level three 1-1-1'
}, {
id: 10,
label: 'Level three 1-1-2'
}]
}]
}, {
id: 2,
label: 'Level one 2',
children: [{
id: 5,
label: 'Level two 2-1'
}, {
id: 6,
label: 'Level two 2-2'
}]
}, {
id: 3,
label: 'Level one 3',
children: [{
id: 7,
label: 'Level two 3-1'
}, {
id: 8,
label: 'Level two 3-2'
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
}
};
</script>
```
:::
### Custom node content
The content of tree nodes can be customized, so you can add icons or buttons as you will
:::demo There are two ways to customize template for tree nodes: `render-content` and scoped slot. Use `render-content` to assign a render function that returns the content of tree nodes. See Vue's documentation for a detailed introduction of render functions. If you prefer scoped slot, you'll have access to `node` and `data` in the scope, standing for the TreeNode object and node data of the current node respectively. Note that the `render-content` demo can't run in jsfiddle because it doesn't support JSX syntax. In a real project, `render-content` will work if relevant dependencies are correctly configured.
```html
<div class="custom-tree-container">
<div class="block">
<p>Using render-content</p>
<el-tree
:data="data"
show-checkbox
node-key="id"
default-expand-all
:expand-on-click-node="false"
:render-content="renderContent">
</el-tree>
</div>
<div class="block">
<p>Using scoped slot</p>
<el-tree
:data="data"
show-checkbox
node-key="id"
default-expand-all
:expand-on-click-node="false">
<span class="custom-tree-node" slot-scope="{ node, data }">
<span>{{ node.label }}</span>
<span>
<el-button
type="text"
size="mini"
@click="() => append(data)">
Append
</el-button>
<el-button
type="text"
size="mini"
@click="() => remove(node, data)">
Delete
</el-button>
</span>
</span>
</el-tree>
</div>
</div>
<script>
let id = 1000;
export default {
data() {
const data = [{
id: 1,
label: 'Level one 1',
children: [{
id: 4,
label: 'Level two 1-1',
children: [{
id: 9,
label: 'Level three 1-1-1'
}, {
id: 10,
label: 'Level three 1-1-2'
}]
}]
}, {
id: 2,
label: 'Level one 2',
children: [{
id: 5,
label: 'Level two 2-1'
}, {
id: 6,
label: 'Level two 2-2'
}]
}, {
id: 3,
label: 'Level one 3',
children: [{
id: 7,
label: 'Level two 3-1'
}, {
id: 8,
label: 'Level two 3-2'
}]
}];
return {
data: JSON.parse(JSON.stringify(data)),
data: JSON.parse(JSON.stringify(data))
}
},
methods: {
append(data) {
const newChild = { id: id++, label: 'testtest', children: [] };
if (!data.children) {
this.$set(data, 'children', []);
}
data.children.push(newChild);
},
remove(node, data) {
const parent = node.parent;
const children = parent.data.children || parent.data;
const index = children.findIndex(d => d.id === data.id);
children.splice(index, 1);
},
renderContent(h, { node, data, store }) {
return (
<span class="custom-tree-node">
<span>{node.label}</span>
<span>
<el-button size="mini" type="text" on-click={ () => this.append(data) }>Append</el-button>
<el-button size="mini" type="text" on-click={ () => this.remove(node, data) }>Delete</el-button>
</span>
</span>);
}
}
};
</script>
<style>
.custom-tree-node {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
padding-right: 8px;
}
</style>
```
:::
### Tree node filtering
Tree nodes can be filtered
:::demo Invoke the `filter` method of the Tree instance to filter tree nodes. Its parameter is the filtering keyword. Note that for it to work, `filter-node-method` is required, and its value is the filtering method.
```html
<el-input
placeholder="Filter keyword"
v-model="filterText">
</el-input>
<el-tree
class="filter-tree"
:data="data"
:props="defaultProps"
default-expand-all
:filter-node-method="filterNode"
ref="tree">
</el-tree>
<script>
export default {
watch: {
filterText(val) {
this.$refs.tree.filter(val);
}
},
methods: {
filterNode(value, data) {
if (!value) return true;
return data.label.indexOf(value) !== -1;
}
},
data() {
return {
filterText: '',
data: [{
id: 1,
label: 'Level one 1',
children: [{
id: 4,
label: 'Level two 1-1',
children: [{
id: 9,
label: 'Level three 1-1-1'
}, {
id: 10,
label: 'Level three 1-1-2'
}]
}]
}, {
id: 2,
label: 'Level one 2',
children: [{
id: 5,
label: 'Level two 2-1'
}, {
id: 6,
label: 'Level two 2-2'
}]
}, {
id: 3,
label: 'Level one 3',
children: [{
id: 7,
label: 'Level two 3-1'
}, {
id: 8,
label: 'Level two 3-2'
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
}
};
</script>
```
:::
### Accordion
Only one node among the same level can be expanded at one time.
:::demo
```html
<el-tree
:data="data"
:props="defaultProps"
accordion
@node-click="handleNodeClick">
</el-tree>
<script>
export default {
data() {
return {
data: [{
label: 'Level one 1',
children: [{
label: 'Level two 1-1',
children: [{
label: 'Level three 1-1-1'
}]
}]
}, {
label: 'Level one 2',
children: [{
label: 'Level two 2-1',
children: [{
label: 'Level three 2-1-1'
}]
}, {
label: 'Level two 2-2',
children: [{
label: 'Level three 2-2-1'
}]
}]
}, {
label: 'Level one 3',
children: [{
label: 'Level two 3-1',
children: [{
label: 'Level three 3-1-1'
}]
}, {
label: 'Level two 3-2',
children: [{
label: 'Level three 3-2-1'
}]
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
},
methods: {
handleNodeClick(data) {
console.log(data);
}
}
};
</script>
```
:::
### Draggable
You can drag and drop Tree nodes by adding a `draggable` attribute.
:::demo
```html
<el-tree
:data="data"
node-key="id"
default-expand-all
@node-drag-start="handleDragStart"
@node-drag-enter="handleDragEnter"
@node-drag-leave="handleDragLeave"
@node-drag-over="handleDragOver"
@node-drag-end="handleDragEnd"
@node-drop="handleDrop"
draggable
:allow-drop="allowDrop"
:allow-drag="allowDrag">
</el-tree>
<script>
export default {
data() {
return {
data: [{
label: 'Level one 1',
children: [{
label: 'Level two 1-1',
children: [{
label: 'Level three 1-1-1'
}]
}]
}, {
label: 'Level one 2',
children: [{
label: 'Level two 2-1',
children: [{
label: 'Level three 2-1-1'
}]
}, {
label: 'Level two 2-2',
children: [{
label: 'Level three 2-2-1'
}]
}]
}, {
label: 'Level one 3',
children: [{
label: 'Level two 3-1',
children: [{
label: 'Level three 3-1-1'
}]
}, {
label: 'Level two 3-2',
children: [{
label: 'Level three 3-2-1'
}]
}]
}],
defaultProps: {
children: 'children',
label: 'label'
}
};
},
methods: {
handleDragStart(node, ev) {
console.log('drag start', node);
},
handleDragEnter(draggingNode, dropNode, ev) {
console.log('tree drag enter: ', dropNode.label);
},
handleDragLeave(draggingNode, dropNode, ev) {
console.log('tree drag leave: ', dropNode.label);
},
handleDragOver(draggingNode, dropNode, ev) {
console.log('tree drag over: ', dropNode.label);
},
handleDragEnd(draggingNode, dropNode, dropType, ev) {
console.log('tree drag end: ', dropNode && dropNode.label, dropType);
},
handleDrop(draggingNode, dropNode, dropType, ev) {
console.log('tree drop: ', dropNode.label, dropType);
},
allowDrop(draggingNode, dropNode, type) {
if (dropNode.data.label === 'Level two 3-1') {
return type !== 'inner';
} else {
return true;
}
},
allowDrag(draggingNode) {
return draggingNode.data.label.indexOf('Level three 3-1-1') === -1;
}
}
};
</script>
```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default |
| --------------------- | ---------------------------------------- | --------------------------- | --------------- | ------- |
| data | tree data | array | — | — |
| empty-text | text displayed when data is void | string | — | — |
| node-key | unique identity key name for nodes, its value should be unique across the whole tree | string | — | — |
| props | configuration options, see the following table | object | — | — |
| render-after-expand | whether to render child nodes only after a parent node is expanded for the first time | boolean | — | true |
| load | method for loading subtree data, only works when `lazy` is true | function(node, resolve) | — | — |
| render-content | render function for tree node | Function(h, { node, data, store } | — | — |
| highlight-current | whether current node is highlighted | boolean | — | false |
| default-expand-all | whether to expand all nodes by default | boolean | — | false |
| expand-on-click-node | whether to expand or collapse node when clicking on the node, if false, then expand or collapse node only when clicking on the arrow icon. | boolean | — | true |
| check-on-click-node | whether to check or uncheck node when clicking on the node, if false, the node can only be checked or unchecked by clicking on the checkbox. | boolean | — | false |
| auto-expand-parent | whether to expand father node when a child node is expanded | boolean | — | true |
| default-expanded-keys | array of keys of initially expanded nodes | array | — | — |
| show-checkbox | whether node is selectable | boolean | — | false |
| check-strictly | whether checked state of a node not affects its father and child nodes when `show-checkbox` is `true` | boolean | — | false |
| default-checked-keys | array of keys of initially checked nodes | array | — | — |
| current-node-key | key of initially selected node | string, number | — | — |
| filter-node-method | this function will be executed on each node when use filter method. if return `false`, tree node will be hidden. | Function(value, data, node) | — | — |
| accordion | whether only one node among the same level can be expanded at one time | boolean | — | false |
| indent | horizontal indentation of nodes in adjacent levels in pixels | number | — | 16 |
| icon-class | custome tree node icon | string | - | - |
| lazy | whether to lazy load leaf node, used with `load` attribute | boolean | — | false |
| draggable | whether enable tree nodes drag and drop | boolean | — | false |
| allow-drag | this function will be executed before dragging a node. If `false` is returned, the node can not be dragged | Function(node) | — | — |
| allow-drop | this function will be executed before the dragging node is dropped. If `false` is returned, the dragging node can not be dropped at the target node. `type` has three possible values: 'prev' (inserting the dragging node before the target node), 'inner' (inserting the dragging node to the target node) and 'next' (inserting the dragging node after the target node) | Function(draggingNode, dropNode, type) | — | — |
### props
| Attribute | Description | Type | Accepted Values | Default |
| --------- | ---------------------------------------- | ------ | --------------- | ------- |
| label | specify which key of node object is used as the node's label | string, function(data, node) | — | — |
| children | specify which node object is used as the node's subtree | string | — | — |
| disabled | specify which key of node object represents if node's checkbox is disabled | boolean, function(data, node) | — | — |
| isLeaf | specify whether the node is a leaf node, only works when lazy load is enabled | boolean, function(data, node) | — | — |
### Method
`Tree` has the following method, which returns the currently selected array of nodes.
| Method | Description | Parameters |
| --------------- | ---------------------------------------- | ---------------------------------------- |
| filter | filter all tree nodes, filtered nodes will be hidden | Accept a parameter which will be used as first parameter for filter-node-method |
| updateKeyChildren | set new data to node, only works when `node-key` is assigned | (key, data) Accept two parameters: 1. key of node 2. new data |
| getCheckedNodes | If the node can be selected (`show-checkbox` is `true`), it returns the currently selected array of nodes | (leafOnly, includeHalfChecked) Accept two boolean type parameters: 1. default value is `false`. If the parameter is `true`, it only returns the currently selected array of sub-nodes. 2. default value is `false`. If the parameter is `true`, the return value contains halfchecked nodes |
| setCheckedNodes | set certain nodes to be checked, only works when `node-key` is assigned | an array of nodes to be checked |
| getCheckedKeys | If the node can be selected (`show-checkbox` is `true`), it returns the currently selected array of node's keys | (leafOnly) Accept a boolean type parameter whose default value is `false`. If the parameter is `true`, it only returns the currently selected array of sub-nodes. |
| setCheckedKeys | set certain nodes to be checked, only works when `node-key` is assigned | (keys, leafOnly) Accept two parameters: 1. an array of node's keys to be checked 2. a boolean type parameter whose default value is `false`. If the parameter is `true`, it only returns the currently selected array of sub-nodes. |
| setChecked | set node to be checked or not, only works when `node-key` is assigned | (key/data, checked, deep) Accept three parameters: 1. node's key or data to be checked 2. a boolean typed parameter indicating checked or not. 3. a boolean typed parameter indicating deep or not. |
| getHalfCheckedNodes | If the node can be selected (`show-checkbox` is `true`), it returns the currently half selected array of nodes | - |
| getHalfCheckedKeys | If the node can be selected (`show-checkbox` is `true`), it returns the currently half selected array of node's keys | - |
| getCurrentKey | return the highlight node's key (null if no node is highlighted) | — |
| getCurrentNode | return the highlight node's data (null if no node is highlighted) | — |
| setCurrentKey | set highlighted node by key, only works when `node-key` is assigned | (key) the node's key to be highlighted. If `null`, cancel the currently highlighted node |
| setCurrentNode | set highlighted node, only works when `node-key` is assigned | (node) the node to be highlighted |
| getNode | get node by data or key | (data) the node's data or key |
| remove | remove a node, only works when node-key is assigned | (data) the node's data or node to be deleted |
| append | append a child node to a given node in the tree | (data, parentNode) 1. child node's data to be appended 2. parent node's data, key or node |
| insertBefore | insert a node before a given node in the tree | (data, refNode) 1. node's data to be inserted 2. reference node's data, key or node |
| insertAfter | insert a node after a given node in the tree | (data, refNode) 1. node's data to be inserted 2. reference node's data, key or node |
### Events
| Event Name | Description | Parameters |
| -------------- | ---------------------------------------- | ---------------------------------------- |
| node-click | triggers when a node is clicked | three parameters: node object corresponding to the node clicked, `node` property of TreeNode, TreeNode itself |
| node-contextmenu | triggers when a node is clicked by right button | four parameters: event, node object corresponding to the node clicked, `node` property of TreeNode, TreeNode itself |
| check-change | triggers when the selected state of the node changes | three parameters: node object corresponding to the node whose selected state is changed, whether the node is selected, whether node's subtree has selected nodes |
| check | triggers after clicking the checkbox of a node | two parameters: node object corresponding to the node that is checked / unchecked, tree checked status object which has four props: checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys |
| current-change | triggers when current node changes | two parameters: node object corresponding to the current node, `node` property of TreeNode |
| node-expand | triggers when current node open | three parameters: node object corresponding to the node opened, `node` property of TreeNode, TreeNode itself |
| node-collapse | triggers when current node close | three parameters: node object corresponding to the node closed, `node` property of TreeNode, TreeNode itself |
| node-drag-start | triggers when dragging starts | two parameters: node object corresponding to the dragging node, event. |
| node-drag-enter | triggers when the dragging node enters another node | three parameters: node object corresponding to the dragging node, node object corresponding to the entering node, event. |
| node-drag-leave | triggers when the dragging node leaves a node | three parameters: node object corresponding to the dragging node, node object corresponding to the leaving node, event. |
| node-drag-over | triggers when dragging over a node (like mouseover event) | three parameters: node object corresponding to the dragging node, node object corresponding to the dragging over node, event. |
| node-drag-end | triggers when dragging ends | four parameters: node object corresponding to the dragging node, node object corresponding to the dragging end node (may be `undefined`), node drop type (before / after / inner), event. |
| node-drop | triggers after the dragging node is dropped | four parameters: node object corresponding to the dragging node, node object corresponding to the dropped node, node drop type (before / after / inner), event. |
### Scoped Slot
| Name | Description |
|------|--------|
| — | Custom content for tree nodes. The scope parameter is { node, data } |

View File

@@ -0,0 +1,151 @@
<script>
import bus from '../../bus';
import { ACTION_USER_CONFIG_UPDATE } from '../../components/theme/constant.js';
const varMap = [
'$--font-size-extra-large',
'$--font-size-large',
'$--font-size-medium',
'$--font-size-base',
'$--font-size-small',
'$--font-size-extra-small'
];
const original = {
'font_size_extra_large': '20px',
'font_size_large': '18px',
'font_size_medium': '16px',
'font_size_base': '14px',
'font_size_small': '13px',
'font_size_extra_small': '12px'
}
export default {
created() {
bus.$on(ACTION_USER_CONFIG_UPDATE, this.setGlobal);
},
mounted() {
this.setGlobal();
},
methods: {
tintColor(color, tint) {
return tintColor(color, tint);
},
setGlobal() {
if (window.userThemeConfig) {
this.global = window.userThemeConfig.global;
}
}
},
data() {
return {
global: {},
'font_size_extra_large': '',
'font_size_large': '',
'font_size_medium': '',
'font_size_base': '',
'font_size_small': '',
'font_size_extra_small': ''
}
},
watch: {
global: {
immediate: true,
handler(value) {
varMap.forEach((v) => {
const key = v.replace('$--', '').replace(/-/g, '_')
if (value[v]) {
this[key] = value[v]
} else {
this[key] = original[key]
}
});
}
}
},
}
</script>
## Typography
We create a font convention to ensure the best presentation across different platforms.
### Font
<div class="demo-term-box">
<img src="../../assets/images/term-pingfang.png" alt="">
<img src="../../assets/images/term-hiragino.png" alt="">
<img src="../../assets/images/term-microsoft.png" alt="">
<img src="../../assets/images/term-sf.png" alt="">
<img src="../../assets/images/term-helvetica.png" alt="">
<img src="../../assets/images/term-arial.png" alt="">
</div>
### Font Convention
<table class="demo-typo-size">
<tbody>
<tr
>
<td>Level</td>
<td>Font Size</td>
<td class="color-dark-light">Demo</td>
</tr>
<tr
:style="{ fontSize: font_size_extra_small }"
>
<td>Supplementary text</td>
<td class="color-dark-light">{{font_size_extra_small}} Extra Small</td>
<td>Build with Element</td>
</tr>
<tr
:style="{ fontSize: font_size_small }"
>
<td>Body (small)</td>
<td class="color-dark-light">{{font_size_small}} Small</td>
<td>Build with Element</td>
</tr>
<tr
:style="{ fontSize: font_size_base }"
>
<td>Body</td>
<td class="color-dark-light">{{font_size_base}} Base</td>
<td>Build with Element</td>
</tr>
<tr
:style="{ fontSize: font_size_medium }"
>
<td >Small Title</td>
<td class="color-dark-light">{{font_size_medium}} Medium</td>
<td>Build with Element</td>
</tr>
<tr
:style="{ fontSize: font_size_large }"
>
<td>Title</td>
<td class="color-dark-light">{{font_size_large}} large</td>
<td>Build with Element</td>
</tr>
<tr
:style="{ fontSize: font_size_extra_large }"
>
<td>Main Title</td>
<td class="color-dark-light">{{font_size_extra_large}} Extra large</td>
<td>Build with Element</td>
</tr>
</tbody>
</table>
### Font Line Height
<div>
<img class="lineH-left" src="~examples/assets/images/typography.png" />
<ul class="lineH-right">
<li>line-height:1 <span>No line height</span></li>
<li>line-height:1.3 <span>Compact</span></li>
<li>line-height:1.5 <span>Regular</span></li>
<li>line-height:1.7 <span>Loose</span></li>
</ul>
</div>
### Font-family
```css
font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
```

View File

@@ -0,0 +1,383 @@
## Upload
Upload files by clicking or drag-and-drop
### Click to upload files
:::demo Customize upload button type and text using `slot`. Set `limit` and `on-exceed` to limit the maximum number of uploads allowed and specify method when the limit is exceeded. Plus, you can abort removing a file in the `before-remove` hook.
```html
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
multiple
:limit="3"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">Click to upload</el-button>
<div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
</el-upload>
<script>
export default {
data() {
return {
fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`The limit is 3, you selected ${files.length} files this time, add up to ${files.length + fileList.length} totally`);
},
beforeRemove(file, fileList) {
return this.$confirm(`Cancel the transfert of ${ file.name } ?`);
}
}
}
</script>
```
:::
### User avatar upload
Use `before-upload` hook to limit the upload file format and size.
:::demo
```html
<el-upload
class="avatar-uploader"
action="https://jsonplaceholder.typicode.com/posts/"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<script>
export default {
data() {
return {
imageUrl: ''
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('Avatar picture must be JPG format!');
}
if (!isLt2M) {
this.$message.error('Avatar picture size can not exceed 2MB!');
}
return isJPG && isLt2M;
}
}
}
</script>
```
:::
### Photo Wall
Use `list-type` to change the fileList style.
:::demo
```html
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
}
}
}
</script>
```
:::
### Custom file thumbnail
Use `scoped-slot` to change default thumbnail template.
:::demo
```html
<el-upload
action="#"
list-type="picture-card"
:auto-upload="false">
<i slot="default" class="el-icon-plus"></i>
<div slot="file" slot-scope="{file}">
<img
class="el-upload-list__item-thumbnail"
:src="file.url" alt=""
>
<span class="el-upload-list__item-actions">
<span
class="el-upload-list__item-preview"
@click="handlePictureCardPreview(file)"
>
<i class="el-icon-zoom-in"></i>
</span>
<span
v-if="!disabled"
class="el-upload-list__item-delete"
@click="handleDownload(file)"
>
<i class="el-icon-download"></i>
</span>
<span
v-if="!disabled"
class="el-upload-list__item-delete"
@click="handleRemove(file)"
>
<i class="el-icon-delete"></i>
</span>
</span>
</div>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false,
disabled: false
};
},
methods: {
handleRemove(file) {
console.log(file);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
handleDownload(file) {
console.log(file);
}
}
}
</script>
```
:::
### FileList with thumbnail
:::demo
```html
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
list-type="picture">
<el-button size="small" type="primary">Click to upload</el-button>
<div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
</el-upload>
<script>
export default {
data() {
return {
fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePreview(file) {
console.log(file);
}
}
}
</script>
```
:::
### File list control
Use `on-change` hook function to control upload file list
:::demo
```html
<el-upload
class="upload-demo"
action="https://jsonplaceholder.typicode.com/posts/"
:on-change="handleChange"
:file-list="fileList">
<el-button size="small" type="primary">Click to upload</el-button>
<div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
</el-upload>
<script>
export default {
data() {
return {
fileList: [{
name: 'food.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
}, {
name: 'food2.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
}]
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList.slice(-3);
}
}
}
</script>
```
:::
### Drag to upload
You can drag your file to a certain area to upload it.
:::demo
```html
<el-upload
class="upload-demo"
drag
action="https://jsonplaceholder.typicode.com/posts/"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">Drop file here or <em>click to upload</em></div>
<div class="el-upload__tip" slot="tip">jpg/png files with a size less than 500kb</div>
</el-upload>
```
:::
### Manual upload
:::demo
```html
<el-upload
class="upload-demo"
ref="upload"
action="https://jsonplaceholder.typicode.com/posts/"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">select file</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">upload to server</el-button>
<div class="el-upload__tip" slot="tip">jpg/png files with a size less than 500kb</div>
</el-upload>
<script>
export default {
methods: {
submitUpload() {
this.$refs.upload.submit();
}
}
}
</script>
```
:::
### Attributes
Attribute | Description | Type | Accepted Values | Default
----| ----| ----| ----| ----
action | required, request URL | string | — | —
headers | request headers | object | — | —
multiple | whether uploading multiple files is permitted | boolean | — | —
data | additions options of request | object | — | —
name | key name for uploaded file | string | — | file
with-credentials | whether cookies are sent | boolean | — |false
show-file-list | whether to show the uploaded file list | boolean | — | true
drag | whether to activate drag and drop mode | boolean | — | false
accept | accepted [file types](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-accept), will not work when `thumbnail-mode` is `true` | string | — | —
on-preview | hook function when clicking the uploaded files | function(file) | — | —
on-remove | hook function when files are removed | function(file, fileList) | — | —
on-success | hook function when uploaded successfully | function(response, file, fileList) | — | —
on-error | hook function when some errors occurs | function(err, file, fileList) | — | —
on-progress | hook function when some progress occurs | function(event, file, fileList) | — | — |
on-change | hook function when select file or upload file success or upload file fail | function(file, fileList) | — | — |
before-upload | hook function before uploading with the file to be uploaded as its parameter. If `false` is returned or a `Promise` is returned and then is rejected, uploading will be aborted | function(file) | — | —
before-remove | hook function before removing a file with the file and file list as its parameters. If `false` is returned or a `Promise` is returned and then is rejected, removing will be aborted. | function(file, fileList) | — | — |
thumbnail-mode | whether thumbnail is displayed | boolean | — | false
file-list | default uploaded files, e.g. [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] | array | — | []
list-type | type of fileList | string | text/picture/picture-card | text |
auto-upload | whether to auto upload file | boolean | — | true |
http-request | override default xhr behavior, allowing you to implement your own upload-file's request | function | — | — |
disabled | whether to disable upload | boolean | — | false |
limit | maximum number of uploads allowed | number | — | — |
on-exceed | hook function when limit is exceeded | function(files, fileList) | — | - |
### Slot
| Name | Description |
|------|--------|
| trigger | content which triggers file dialog |
| tip | content of tips |
### Methods
| Methods Name | Description | Parameters |
|---------- |-------- |---------- |
| clearFiles | clear the uploaded file list (this method is not supported in the `before-upload` hook) | — |
| abort | cancel upload request | file: fileList's item |
| submit | upload the file list manually | — |

244
examples/docs/es/alert.md Normal file
View File

@@ -0,0 +1,244 @@
## Alert
Mostrar mensajes de alertas importantes.
### Uso básico
Los componentes de alertas no son elementos overlay de la página y no desaparecen automáticamente.
:::demo Alert provee 4 tipos de temas definidos por `type`, el valor por defecto es `info`.
```html
<template>
<el-alert
title="success alert"
type="success">
</el-alert>
<el-alert
title="info alert"
type="info">
</el-alert>
<el-alert
title="warning alert"
type="warning">
</el-alert>
<el-alert
title="error alert"
type="error">
</el-alert>
</template>
```
:::
### Theme
Alert provee dos diferentes temas `light` y `dark`.
:::demo Use `effect` para cambiar el tema, por defecto es `light`.
```html
<template>
<el-alert
title="success alert"
type="success"
effect="dark">
</el-alert>
<el-alert
title="info alert"
type="info"
effect="dark">
</el-alert>
<el-alert
title="warning alert"
type="warning"
effect="dark">
</el-alert>
<el-alert
title="error alert"
type="error"
effect="dark">
</el-alert>
</template>
```
:::
### Personalización del botón de cerrar
Personalizar el botón de cerrar como texto u otros símbolos.
:::demo Alert permite configurar si es posible cerrarla. El texto del botón de cerrado, así como los callbacks de cerrado son personalizables. El atributo `closable` define si el componente puede cerrarse o no. Acepta un `boolean`, que por defecto es `true`. También puede configurar el atributo `close-text` para reemplazar el símbolo de cerrado que se muestra por defecto. El atributo `close-text` debe ser un string. El evento `close` se dispara cuando el componente se cierra.
```html
<template>
<el-alert
title="unclosable alert"
type="success"
:closable="false">
</el-alert>
<el-alert
title="customized close-text"
type="info"
close-text="Gotcha">
</el-alert>
<el-alert
title="alert with callback"
type="warning"
@close="hello">
</el-alert>
</template>
<script>
export default {
methods: {
hello() {
alert('Hello World!');
}
}
}
</script>
```
:::
### Usar iconos
Mostrar un icono mejora la legibilidad.
:::demo Setear el atributo `show-icon` muestra un icono que corresponde al tipo de Alert que se está mostrando.
```html
<template>
<el-alert
title="success alert"
type="success"
show-icon>
</el-alert>
<el-alert
title="info alert"
type="info"
show-icon>
</el-alert>
<el-alert
title="warning alert"
type="warning"
show-icon>
</el-alert>
<el-alert
title="error alert"
type="error"
show-icon>
</el-alert>
</template>
```
:::
### Texto centrado
Para centrar el texto utilice el atributo `center`.
:::demo
```html
<template>
<el-alert
title="success alert"
type="success"
center
show-icon>
</el-alert>
<el-alert
title="info alert"
type="info"
center
show-icon>
</el-alert>
<el-alert
title="warning alert"
type="warning"
center
show-icon>
</el-alert>
<el-alert
title="error alert"
type="error"
center
show-icon>
</el-alert>
</template>
```
:::
### Con descripción
Descripción incluye un mensaje con información más detallada.
:::demo Además del atributo requerido `title`, se puede agregar el atributo `description` para ayudar a describir la alerta con mas detalles. La descripción puede contener solamente un string y va a usar word wrap automáticamente.
```html
<template>
<el-alert
title="with description"
type="success"
description="This is a description.">
</el-alert>
</template>
```
:::
### Utilizando icono y descripción
:::demo Finalmente este es un ejemplo utilizando icono y descripción.
```html
<template>
<el-alert
title="success alert"
type="success"
description="more text description"
show-icon>
</el-alert>
<el-alert
title="info alert"
type="info"
description="more text description"
show-icon>
</el-alert>
<el-alert
title="warning alert"
type="warning"
description="more text description"
show-icon>
</el-alert>
<el-alert
title="error alert"
type="error"
description="more text description"
show-icon>
</el-alert>
</template>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------- | ---------------------------------------- | ------- | -------------------------- | ----------- |
| title | título | string | — | — |
| type | tipo de componente | string | success/warning/info/error | info |
| description | texto descriptivo. También puede ser pasado con el slot por defecto | string | — | — |
| closable | si se puede cerrar o no | boolean | — | true |
| center | si el texto debe estar centrado | boolean | — | false |
| close-text | texto de cerrado personalizado | string | — | — |
| show-icon | si un icono del tipo de alerta se debe mostrar | boolean | — | false |
| effect | selecciona tema | string | light/dark | light |
### Slot
| Nombre | Descripción |
|------|--------|
| — | descripción |
| title | El contenido del título de alerta. |
### Eventos
| Nombre del evento | Descripción | Parámetros |
| ----------------- | ------------------------------------- | ---------- |
| close | Se dispara cuando la alerta se cierra | — |

146
examples/docs/es/avatar.md Normal file
View File

@@ -0,0 +1,146 @@
## Avatar
Los avatares pueden utilizarse para representar personas u objetos. Soporta imágenes, iconos o caracteres.
### Básico
Use los props `shape` y `size` para establecer la forma y el tamaño del avatar
:::demo
```html
<template>
<el-row class="demo-avatar demo-basic">
<el-col :span="12">
<div class="sub-title">circle</div>
<div class="demo-basic--circle">
<div class="block"><el-avatar :size="50" :src="circleUrl"></el-avatar></div>
<div class="block" v-for="size in sizeList" :key="size">
<el-avatar :size="size" :src="circleUrl"></el-avatar>
</div>
</div>
</el-col>
<el-col :span="12">
<div class="sub-title">square</div>
<div class="demo-basic--circle">
<div class="block"><el-avatar shape="square" :size="50" :src="squareUrl"></el-avatar></div>
<div class="block" v-for="size in sizeList" :key="size">
<el-avatar shape="square" :size="size" :src="squareUrl"></el-avatar>
</div>
</div>
</el-col>
</el-row>
</template>
<script>
export default {
data () {
return {
circleUrl: "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
squareUrl: "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
sizeList: ["large", "medium", "small"]
}
}
}
</script>
```
:::
### Tipos
Soporta imágenes, iconos o caracteres.
:::demo
```html
<template>
<div class="demo-type">
<div>
<el-avatar icon="el-icon-user-solid"></el-avatar>
</div>
<div>
<el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
</div>
<div>
<el-avatar> user </el-avatar>
</div>
</div>
</template>
```
:::
### Fallback cuando se produce un error de carga de imagen
Fallback cuando se produce un error de carga de imagen
:::demo
```html
<template>
<div class="demo-type">
<el-avatar :size="60" src="https://empty" @error="errorHandler">
<img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"/>
</el-avatar>
</div>
</template>
<script>
export default {
methods: {
errorHandler() {
return true
}
}
}
</script>
```
:::
### Cómo encaja la imagen en su contenedor
Establezca cómo la imagen se ajusta a su contenedor para un avatar de imagen, igual que [object-fit](https://developer.mozilla.org/es/docs/Web/CSS/object-fit).
:::demo
```html
<template>
<div class="demo-fit">
<div class="block" v-for="fit in fits" :key="fit">
<span class="title">{{ fit }}</span>
<el-avatar shape="square" :size="100" :fit="fit" :src="url"></el-avatar>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
}
}
}
</script>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------- | -------------------------------- | --------------- | ------ | ------ |
| icon | establece el tipo de representación a Icono, más información en Componente Icon | string | | |
| size | Establece el tamaño del avatar | number/string | number / large / medium / small | large |
| shape | establece la forma del avatar | string | circle / square | circle |
| src | la dirección de la imagen para un avatar de imagen | string | | |
| srcSet | Una lista de una o más cadenas separadas por comas que indica un conjunto de posibles fuentes de imágenes para que el agente de usuario las utilice. | string | | |
| alt | Este atributo define una descripción de texto alternativo de la imagen | string | | |
| fit | establece cómo encaja la imagen en su contenedor para un avatar de imagen | string | fill / contain / cover / none / scale-down | cover |
### Eventos
| Nombre | Descripción | Parámetros |
| ------ | ------------------ | -------- |
| error | cuando se produce un error de carga de img, devuelve false para evitar el comportamiento de repliegue predeterminado |(e: Event) |
### Slot
| Nombre | Descripción |
| default | personalice el contenido del avatar |

View File

@@ -0,0 +1,60 @@
## Backtop
Un botón para volver a la parte superior
### Uso básico
Desplácese hacia abajo para ver el botón en el lado inferior derecho.
:::demo
```html
<template>
Scroll down to see the bottom-right button.
<el-backtop target=".page-component__scroll .el-scrollbar__wrap"></el-backtop>
</template>
```
:::
### Personalización
Área de visualización de 40px \* 40px.
:::demo
```html
<template>
Scroll down to see the bottom-right button.
<el-backtop target=".page-component__scroll .el-scrollbar__wrap" :bottom="100">
<div
style="{
height: 100%;
width: 100%;
background-color: #f2f5f6;
box-shadow: 0 0 6px rgba(0,0,0, .12);
text-align: center;
line-height: 40px;
color: #1989fa;
}"
>
UP
</div>
</el-backtop>
</template>
```
:::
### Atributos
| Atributos | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------- | ------------------------------------------------------------------- | --------------- | --------------- | ------- |
| target | el objetivo para activar el scroll | string | | |
| visibility-height | el botón no se mostrará hasta que la altura de desplazamiento alcance este valor | number | | 200 |
| right | separación desde la derecha | number | | 40 |
| bottom | separación desde abajo | number | | 40 |
### Eventos
| Nombre del evento | Descripción | Parámetros |
| ----------------- | ----------------------- | ----------- |
| click | se activa al hacer clic | click event |

125
examples/docs/es/badge.md Normal file
View File

@@ -0,0 +1,125 @@
## Badge
Marcas en forma de número o estado para botones e iconos.
### Uso básico
Muestra la cantidad de mensajes nuevos.
:::demo La cantidad está definida por `value` que acepta `Number` o `String`.
```html
<el-badge :value="12" class="item">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge :value="3" class="item">
<el-button size="small">replies</el-button>
</el-badge>
<el-badge :value="1" class="item" type="primary">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge :value="2" class="item" type="warning">
<el-button size="small">replies</el-button>
</el-badge>
<el-dropdown trigger="click">
<span class="el-dropdown-link">
Click Me<i class="el-icon-caret-bottom el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item class="clearfix">
comments
<el-badge class="mark" :value="12" />
</el-dropdown-item>
<el-dropdown-item class="clearfix">
replies
<el-badge class="mark" :value="3" />
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Valor máximo
Se puede personalizar el valor máximo.
:::demo El valor máximo se define como `max` el cual es un `Number`. Nota: solo funciona si `value` es también un `Number`.
```html
<el-badge :value="200" :max="99" class="item">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge :value="100" :max="10" class="item">
<el-button size="small">replies</el-button>
</el-badge>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Personalizaciones
Mostrar texto en vez de números.
:::demo Cuando `value` es un `String`, puede mostrar texto personalizado.
```html
<el-badge value="new" class="item">
<el-button size="small">comments</el-button>
</el-badge>
<el-badge value="hot" class="item">
<el-button size="small">replies</el-button>
</el-badge>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Pequeño punto rojo
Puede utilizar un punto rojo para marcar contenido que debe ser notado.
:::demo Use el atributo `is-dot`. Es un `Boolean`.
```html
<el-badge is-dot class="item">query</el-badge>
<el-badge is-dot class="item">
<el-button class="share-button" icon="el-icon-share" type="primary"></el-button>
</el-badge>
<style>
.item {
margin-top: 10px;
margin-right: 40px;
}
</style>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ---------------------------------------- | -------------- | ----------------- | ----------- |
| value | valor a mostrar | string, number | — | — |
| max | valor máximo, Muestra '{max}+' cuando se excede. Solo funciona si `value` es un `Number` | number | — | — |
| is-dot | si se debe mostrar un pequeño punto | boolean | — | false |
| hidden | oculta el badge | boolean | — | false |
| type | tipo de botón | string | primary / success / warning / danger / info | — |

135
examples/docs/es/border.md Normal file
View File

@@ -0,0 +1,135 @@
<script>
import bus from '../../bus';
import { ACTION_USER_CONFIG_UPDATE } from '../../components/theme/constant.js';
const varMap = {
'$--box-shadow-light': 'boxShadowLight',
'$--box-shadow-base': 'boxShadowBase',
'$--border-radius-base': 'borderRadiusBase',
'$--border-radius-small': 'borderRadiusSmall'
};
const original = {
boxShadowLight: '0 2px 12px 0 rgba(0, 0, 0, 0.1)',
boxShadowBase: '0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)',
borderRadiusBase: '4px',
borderRadiusSmall: '2px'
}
export default {
created() {
bus.$on(ACTION_USER_CONFIG_UPDATE, this.setGlobal);
},
mounted() {
this.setGlobal();
},
methods: {
setGlobal() {
if (window.userThemeConfig) {
this.global = window.userThemeConfig.global;
}
}
},
data() {
return {
global: {},
boxShadowLight: '',
boxShadowBase: '',
borderRadiusBase: '',
borderRadiusSmall: ''
}
},
watch: {
global: {
immediate: true,
handler(value) {
Object.keys(varMap).forEach((c) => {
if (value[c]) {
this[varMap[c]] = value[c]
} else {
this[varMap[c]] = original[varMap[c]]
}
});
}
}
}
}
</script>
## Border
Estandarizamos los bordes que se pueden utilizar en botones, tarjetas, pop-ups y otros componentes.
### Border
Hay pocos estilos de borde para elegir.
<table class="demo-border">
<tbody>
<tr>
<td class="text">Name</td>
<td class="text">Thickness</td>
<td class="line">Demo</td>
</tr>
<tr>
<td class="text">Solid</td>
<td class="text">1px</td>
<td class="line">
<div></div>
</td>
</tr>
<tr>
<td class="text">Dashed</td>
<td class="text">2px</td>
<td class="line">
<div class="dashed"></div>
</td>
</tr>
</tbody>
</table>
### Radius
Hay pocos estilos de radio para elegir.
<el-row :gutter="12" class="demo-radius">
<el-col :span="6" :xs="{span: 12}">
<div class="title">No Radius</div>
<div class="value">border-radius: 0px</div>
<div class="radius"></div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="title">Small Radius</div>
<div class="value">border-radius: {{borderRadiusSmall}}</div>
<div
class="radius"
:style="{ borderRadius: borderRadiusSmall }"
></div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="title">Large Radius</div>
<div class="value">border-radius: {{borderRadiusBase}}</div>
<div
class="radius"
:style="{ borderRadius: borderRadiusBase }"
></div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="title">Round Radius</div>
<div class="value">border-radius: 30px</div>
<div class="radius radius-30"></div>
</el-col>
</el-row>
### Shadow
Hay pocos estilos de sombra para elegir.
<div
class="demo-shadow"
:style="{ boxShadow: boxShadowBase }"
></div>
<span class="demo-shadow-text">Basic Shadow box-shadow: {{boxShadowBase}}</span>
<div
class="demo-shadow"
:style="{ boxShadow: boxShadowLight }"
></div>
<span class="demo-shadow-text">Light Shadow box-shadow: {{boxShadowLight}}</span>

View File

@@ -0,0 +1,49 @@
## Breadcrumb
Muestra la localización de la página actual, haciendo más fácil el poder ir a la página anterior.
### Uso básico
:::demo En `el-breadcrumb`, cada `el-breadcrumb-item` es un tag que representa cada nivel empezando desde la homepage. Este componente tiene un atributo `String` llamado `separator`, el mismo determina el carácter separador. El valor por defecto es '/'.
```html
<el-breadcrumb separator="/">
<el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item>
<el-breadcrumb-item><a href="/">promotion management</a></el-breadcrumb-item>
<el-breadcrumb-item>promotion list</el-breadcrumb-item>
<el-breadcrumb-item>promotion detail</el-breadcrumb-item>
</el-breadcrumb>
```
:::
### Icono separador
:::demo Setee `separator-class` para que utilice `iconfont` como separadorel mismo va a cubrir `separator`
```html
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/' }">homepage</el-breadcrumb-item>
<el-breadcrumb-item>promotion management</el-breadcrumb-item>
<el-breadcrumb-item>promotion list</el-breadcrumb-item>
<el-breadcrumb-item>promotion detail</el-breadcrumb-item>
</el-breadcrumb>
```
:::
### Breadcrumb atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| --------------- | -------------------------------------- | ------ | ----------------- | ----------- |
| separator | carácter separador | string | — | / |
| separator-class | nombre de la clase del icono separador | string | — | - |
### Breadcrumb Item atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ---------------------------------------- | ------------- | ----------------- | ----------- |
| to | ruta del link, lo mismo que `to` de `vue-router` | string/object | — | — |
| replace | si `true`, la navegación no dejara una entrada en la historia | boolean | — | false |

166
examples/docs/es/button.md Normal file
View File

@@ -0,0 +1,166 @@
## Button
Botones comúnmente usados.
### Uso básico
:::demo Use `type`, `plain`,`round` y `circle` para definir estilos a los botones.
```html
<el-row>
<el-button>Default</el-button>
<el-button type="primary">Primary</el-button>
<el-button type="success">Success</el-button>
<el-button type="info">Info</el-button>
<el-button type="warning">Warning</el-button>
<el-button type="danger">Danger</el-button>
</el-row>
<el-row>
<el-button plain>Plain</el-button>
<el-button type="primary" plain>Primary</el-button>
<el-button type="success" plain>Success</el-button>
<el-button type="info" plain>Info</el-button>
<el-button type="warning" plain>Warning</el-button>
<el-button type="danger" plain>Danger</el-button>
</el-row>
<el-row>
<el-button round>Round</el-button>
<el-button type="primary" round>Primary</el-button>
<el-button type="success" round>Success</el-button>
<el-button type="info" round>Info</el-button>
<el-button type="warning" round>Warning</el-button>
<el-button type="danger" round>Danger</el-button>
</el-row>
<el-row>
<el-button icon="el-icon-search" circle></el-button>
<el-button type="primary" icon="el-icon-edit" circle></el-button>
<el-button type="success" icon="el-icon-check" circle></el-button>
<el-button type="info" icon="el-icon-message" circle></el-button>
<el-button type="warning" icon="el-icon-star-off" circle></el-button>
<el-button type="danger" icon="el-icon-delete" circle></el-button>
</el-row>
```
:::
### Botón deshabilitado
El atributo `disabled` determina su un botón esta deshabilitado.
:::demo Use el atributo `disabled` para determinar si un botón esta deshabilitado. Acepta un valor `Boolean`.
```html
<el-row>
<el-button disabled>Default</el-button>
<el-button type="primary" disabled>Primary</el-button>
<el-button type="success" disabled>Success</el-button>
<el-button type="info" disabled>Info</el-button>
<el-button type="warning" disabled>Warning</el-button>
<el-button type="danger" disabled>Danger</el-button>
</el-row>
<el-row>
<el-button plain disabled>Plain</el-button>
<el-button type="primary" plain disabled>Primary</el-button>
<el-button type="success" plain disabled>Success</el-button>
<el-button type="info" plain disabled>Info</el-button>
<el-button type="warning" plain disabled>Warning</el-button>
<el-button type="danger" plain disabled>Danger</el-button>
</el-row>
```
:::
### Botón de texto
Botones sin borde ni fondo.
:::demo
```html
<el-button type="text">Text Button</el-button>
<el-button type="text" disabled>Text Button</el-button>
```
:::
### Botón icono
Use iconos para darle mayor significado a Button. Se puede usar simplemente un icono o un icono con texto.
:::demo Use el atributo `icon` para agregar un icono. Puede encontrar el listado de iconos en el componente de iconos. Agregar iconos a la derecha del texto se puede conseguir con un tag `<i>`. También se pueden usar iconos personalizados.
```html
<el-button type="primary" icon="el-icon-edit"></el-button>
<el-button type="primary" icon="el-icon-share"></el-button>
<el-button type="primary" icon="el-icon-delete"></el-button>
<el-button type="primary" icon="el-icon-search">Search</el-button>
<el-button type="primary">Upload<i class="el-icon-upload el-icon-right"></i></el-button>
```
:::
### Grupo de botones
Mostrar un grupo de botones puede ser usado para mostrar un grupo de operaciones similares.
:::demo Use el tag `<el-button-group>` para agrupar sus botones.
```html
<el-button-group>
<el-button type="primary" icon="el-icon-arrow-left">Previous Page</el-button>
<el-button type="primary">Next Page<i class="el-icon-arrow-right el-icon-right"></i></el-button>
</el-button-group>
<el-button-group>
<el-button type="primary" icon="el-icon-edit"></el-button>
<el-button type="primary" icon="el-icon-share"></el-button>
<el-button type="primary" icon="el-icon-delete"></el-button>
</el-button-group>
```
:::
### Botón de descarga
Cuando se hace clic en un botón para descargar datos, el botón muestra un estado de descarga.
:::demo Ajuste el atributo `loading` a `true` para mostrar el estado de descarga.
```html
<el-button type="primary" :loading="true">Loading</el-button>
```
:::
### Tamaños
Además del tamaño por defecto, el componente Button provee tres tamaños adicionales para utilizar en diferentes escenarios.
:::demo Use el atributo `size` para setear tamaños adicionales con `medium`, `small` o `mini`.
```html
<el-row>
<el-button>Default</el-button>
<el-button size="medium">Medium</el-button>
<el-button size="small">Small</el-button>
<el-button size="mini">Mini</el-button>
</el-row>
<el-row>
<el-button round>Default</el-button>
<el-button size="medium" round>Medium</el-button>
<el-button size="small" round>Small</el-button>
<el-button size="mini" round>Mini</el-button>
</el-row>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------- | --------------------------------------------- | ------- | -------------------------------------------------- | ----------- |
| size | tamaño del botón | string | medium / small / mini | — |
| type | tipo de botón | string | primary / success / warning / danger / info / text | — |
| plain | determinar si es o no un botón plano | boolean | — | false |
| round | determinar si es o no un botón redondo | boolean | — | false |
| circle | determina si es un botón circular | boolean | — | false |
| loading | determinar si es o no un botón de descarga | boolean | — | false |
| disabled | deshabilitar el botón | boolean | — | false |
| icon | nombre de la clase del icono | string | — | — |
| autofocus | misma funcionalidad que la nativa `autofocus` | boolean | — | false |
| native-type | misma funcionalidad que la nativa `type` | string | button / submit / reset | button |

View File

@@ -0,0 +1,68 @@
## Calendar
Muestra fechas.
### Básico
:::demo Configure el valor para especificar el mes que se muestra actualmente. Si no se especifica el valor, se muestra el mes actual. el valor soporta la vinculación bidireccional.
```html
<el-calendar v-model="value">
</el-calendar>
<script>
export default {
data() {
return {
value: new Date()
}
}
}
</script>
```
:::
### Contenido personalizado
:::demo Personalice lo que se muestra en la celda del calendario configurando el `scoped-slot` llamada `dateCell`. En la ranura de alcance se puede obtener la fecha (la fecha de la celda actual), los datos (incluyendo el tipo, isSelected, el atributo day). Para obtener más información, consulte la documentación de la API a continuación.
```html
<el-calendar>
<!-- Use 2.5 slot syntax. If you use Vue 2.6, please use new slot syntax-->
<template
slot="dateCell"
slot-scope="{date, data}">
<p :class="data.isSelected ? 'is-selected' : ''">
{{ data.day.split('-').slice(1).join('-') }} {{ data.isSelected ? '✔️' : ''}}
</p>
</template>
</el-calendar>
<style>
.is-selected {
color: #1989FA;
}
</style>
```
:::
### Rango
:::demo Defina el atributo `range` para especificar el rango de visualización del calendario. El tiempo de inicio debe ser el lunes, el tiempo de finalización debe ser el domingo y el período no puede exceder los dos meses.
```html
<el-calendar :range="['2019-03-04', '2019-03-24']">
</el-calendar>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|-----------------|------------------- |---------- |---------------------- |------------ |
| value / v-model | valor vinculante | Date/string/number | — | — |
| range | rango de tiempo, incluyendo el tiempo de inicio y el tiempo final. Start time debe ser el primer dia de la semana, end time debe ser el ultimo día de la semana, el time entre las fechas no puede exceder dos meses | Array | — | — |
| first-day-of-week | primer día de la semana | Number | 1 to 7 | 1 |
### dateCell scoped slot
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|-----------------|-------------- |---------- |---------------------- |--------- |
| date | fecha que la celda representa | Date | — | — |
| data | { type, isSelected, day}. `type` indica el mes al que pertenece la fecha, los valores opcionales son mes anterior, mes actual, mes siguiente; `isSelected` indica si la fecha está seleccionada; `day` es la fecha formateada en el formato yyyy-MM-dd | Object | — | — |

172
examples/docs/es/card.md Normal file
View File

@@ -0,0 +1,172 @@
## Card
Muestra información dentro de un contenedor `card`
### Uso Básico
`Card` incluye titulo, contenido y operaciones.
:::demo Card se compone de cabecera y cuerpo. La cabecera es opcional y la colocación de su contenido depende de un slot con nombre.
```html
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>Card name</span>
<el-button style="float: right; padding: 3px 0" type="text">Operation button</el-button>
</div>
<div v-for="o in 4" :key="o" class="text item">
{{'List item ' + o }}
</div>
</el-card>
<style>
.text {
font-size: 14px;
}
.item {
margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
display: table;
content: "";
}
.clearfix:after {
clear: both
}
.box-card {
width: 480px;
}
</style>
```
:::
### Card simple
La parte de la cabecera puede omitirse.
:::demo
```html
<el-card class="box-card">
<div v-for="o in 4" :key="o" class="text item">
{{'List item ' + o }}
</div>
</el-card>
<style>
.text {
font-size: 14px;
}
.item {
padding: 18px 0;
}
.box-card {
width: 480px;
}
</style>
```
:::
### Con imágenes
Muestre un contenido más rico añadiendo algunas configuraciones.
:::demo El atributo `body-style` define el estilo CSS del `body` personalizado. Este ejemplo también utiliza `el-col` para el layout.
```html
<el-row>
<el-col :span="8" v-for="(o, index) in 2" :key="o" :offset="index > 0 ? 2 : 0">
<el-card :body-style="{ padding: '0px' }">
<img src="https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png" class="image">
<div style="padding: 14px;">
<span>Yummy hamburger</span>
<div class="bottom clearfix">
<time class="time">{{ currentDate }}</time>
<el-button type="text" class="button">Operating</el-button>
</div>
</div>
</el-card>
</el-col>
</el-row>
<style>
.time {
font-size: 13px;
color: #999;
}
.bottom {
margin-top: 13px;
line-height: 12px;
}
.button {
padding: 0;
float: right;
}
.image {
width: 100%;
display: block;
}
.clearfix:before,
.clearfix:after {
display: table;
content: "";
}
.clearfix:after {
clear: both
}
</style>
<script>
export default {
data() {
return {
currentDate: new Date()
};
}
}
</script>
```
:::
### Shadow
Puede definir cuándo mostrar las sombras.
:::demo El atributo de sombra determina cuándo se muestran las sombras. Puede ser `always`, `hover` o `never`.
```html
<el-row :gutter="12">
<el-col :span="8">
<el-card shadow="always">
Always
</el-card>
</el-col>
<el-col :span="8">
<el-card shadow="hover">
Hover
</el-card>
</el-col>
<el-col :span="8">
<el-card shadow="never">
Never
</el-card>
</el-col>
</el-row>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ---------- | ---------------------------------------- | ------ | ----------------- | ------------------- |
| header | Titulo del card. También acepta DOM pasado por `slot#header` | string | — | — |
| body-style | Estilo CSS del cuerpo | object | — | { padding: '20px' } |
| shadow | Cuando mostrar la sombra del Card | string | always / hover / never | always |

View File

@@ -0,0 +1,217 @@
## Carousel
Presenta una serie de imágenes o textos en un espacio limitado
### Uso básico
:::demo Combine `el-carousel` con `el-carousel-item`, para conseguir el carrusel. El contenido de cada diapositiva es completamente personalizable, y sólo tiene que colocarla dentro de la etiqueta `el-carousel-item` . Por defecto, el carrusel cambia cuando el ratón pasa por encima de un indicador. Fije `trigger` para `click`, si lo que se desea es que el carrusel cambie sólo cuando se haga clic en un indicador.
```html
<template>
<div class="block">
<span class="demonstration">Switch when indicator is hovered (default)</span>
<el-carousel height="150px">
<el-carousel-item v-for="item in 4" :key="item">
<h3 class="small">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</div>
<div class="block">
<span class="demonstration">Switch when indicator is clicked</span>
<el-carousel trigger="click" height="150px">
<el-carousel-item v-for="item in 4" :key="item">
<h3 class="small">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</div>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 150px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Indicadores
Los indicadores de paginación pueden mostrarse fuera del carrusel
:::demo El atributo `indicator-position` determina dónde se encuentran los indicadores de paginación. Por defecto están dentro del carrusel, y el ajuste de `indicator-position` a `outside` los mueve hacia fuera; en cambio `indicator-position` a `none` los oculta.
```html
<template>
<el-carousel indicator-position="outside">
<el-carousel-item v-for="item in 4" :key="item">
<h3>{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 18px;
opacity: 0.75;
line-height: 300px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Flechas
Puede definir cuando se visualizan las flechas
:::demo El atributo `arrow` determina cuándo se visualizan las flechas. Por defecto aparecen cuando el ratón se desplaza sobre el carrusel. Ajuste `arrow` a `always` o `never` para mostrar u ocultar las flechas permanentemente.
```html
<template>
<el-carousel :interval="5000" arrow="always">
<el-carousel-item v-for="item in 4" :key="item">
<h3>{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 18px;
opacity: 0.75;
line-height: 300px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Modo Card
Cuando una página es suficientemente ancha pero tiene una altura limitada, puede activar el modo `card` para carrusel.
:::demo Ajuste `type` a `card` para activar el modo tarjeta. Aparte de la apariencia, la mayor diferencia entre el modo tarjeta y el modo común es que al hacer clic en las diapositivas de ambos lados, el carrusel cambia directamente en modo tarjeta.
```html
<template>
<el-carousel :interval="4000" type="card" height="200px">
<el-carousel-item v-for="item in 6" :key="item">
<h3 class="medium">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 200px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
Por defecto, `direction` es `horizontal`. El carousel puede ser mostrado de forma vertical cambiando `direction` a `vertical`.
:::demo
```html
<template>
<el-carousel height="200px" direction="vertical" :autoplay="false">
<el-carousel-item v-for="item in 4" :key="item">
<h3 class="medium">{{ item }}</h3>
</el-carousel-item>
</el-carousel>
</template>
<style>
.el-carousel__item h3 {
color: #475669;
font-size: 14px;
opacity: 0.75;
line-height: 200px;
margin: 0;
}
.el-carousel__item:nth-child(2n) {
background-color: #99a9bf;
}
.el-carousel__item:nth-child(2n+1) {
background-color: #d3dce6;
}
</style>
```
:::
### Atributos de Carousel
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------------ | -------------------------------------------------- | ------- | ------------------- | ----------- |
| height | Alto del carrusel | string | — | — |
| initial-index | Indice del slider inicial activo (empieza desde 0) | number | — | 0 |
| trigger | Evento que muestra los indicadores | string | hover/click | hover |
| autoplay | Si se enlazan automáticamente las diapositivas | boolean | — | true |
| interval | Intervalo del auto loop, en mili segundos | number | — | 3000 |
| indicator-position | Posición del indicador de paginación | string | outside/none | — |
| arrow | Cuando se muestran las flechas | string | always/hover/never | hover |
| type | Tipo de carrusel | string | card | — |
| loop | Si se muestra cíclicamente | boolean | — | true |
| direction | dirección en la que se muestra el contenido | string | horizontal/vertical | horizontal |
### Eventos de Carousel
| Nombre evento | Descripción | Parámetros |
| ------------- | ----------------------------------------- | ------------------------------------------------------------ |
| change | Se dispara cuando el slider activo cambia | Indice del nuevo slider activo, indice del anterior slider activo. |
### Metodos de Carousel
| Metodos | Descripción | Parámetros |
| ------------- | -------------------------- | ------------------------------------------------------------ |
| setActiveItem | Cambio manual de slider | indice del slider al que se va a cambiar, empezando por 0; o el `name` del `el-carousel-item` correspondiente |
| prev | Cambia al slider anterior | — |
| next | Cambia al slider siguiente | — |
### Atributos de Carousel-Item
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ------------------------------------------------------------ | ------ | ----------------- | ----------- |
| name | Nombre del ítem que puede ser usado en `setActiveItem` | string | — | — |
| label | Texto que se mostrara en el indicador de paginación correspondiente | string | — | — |

1990
examples/docs/es/cascader.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,284 @@
## Checkbox
Un grupo de opciones para manejar múltiples elecciones.
### Uso básico
Checkbox puede ser usado para alternar entre dos estados.
:::demo Define `v-model`(enlaza la variable) en `el-checkbox`. El valor por defecto es un `Boolean` para un `checkbox`, y se convierte en `true` cuando este es seleccionado. El contenido dentro del tag `el-checkbox` se convierte en la descripción al costado del botón del checkbox.
```html
<template>
<!-- `checked` debe ser true o false -->
<el-checkbox v-model="checked">Opción</el-checkbox>
</template>
<script>
export default {
data() {
return {
checked: true
};
}
};
</script>
```
:::
### Estado Deshabilitado
Estado deshabilitado para el checkbox.
:::demo Setear el atributo `disabled`.
```html
<template>
<el-checkbox v-model="checked1" disabled>Opción</el-checkbox>
<el-checkbox v-model="checked2" disabled>Opción</el-checkbox>
</template>
<script>
export default {
data() {
return {
checked1: false,
checked2: true
};
}
};
</script>
```
:::
### Grupo de Checkboxes
Es usado por múltiples checkboxes los cuales están enlazados a un grupo, indica si una opción está seleccionada verificando si esta está marcada.
:::demo El elemento `checkbox-group` puede manejar múltiples checkboxes en un grupo usando `v-model` el cuál está enlazado a un `Array`. Dentro del elemento `el-checkbox`, `label` es el valor del checkbox. Si en ese tag no hay contenido anidado, `label` va a ser mostrado como la descripción al lado del botón del checkbox. `label` también se corresponde con los valores del array. Es seleccionado si el valor especificado existe en el array y viceversa.
```html
<template>
<el-checkbox-group v-model="checkList">
<el-checkbox label="Opción A"></el-checkbox>
<el-checkbox label="Opción B"></el-checkbox>
<el-checkbox label="Opción C"></el-checkbox>
<el-checkbox label="disabled" disabled></el-checkbox>
<el-checkbox label="Seleccionado y deshabilitado" disabled></el-checkbox>
</el-checkbox-group>
</template>
<script>
export default {
data () {
return {
checkList: ['Seleccionado y deshabilitado','Opción A']
};
}
};
</script>
```
:::
### Indeterminado
La propiedad `indeterminate` puede ser usada para generar el efecto de marcar todos (check all).
:::demo
```html
<template>
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">Marcar todos</el-checkbox>
<div style="margin: 15px 0;"></div>
<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
<el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
</el-checkbox-group>
</template>
<script>
const cityOptions = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'];
export default {
data() {
return {
checkAll: false,
checkedCities: ['Shanghai', 'Beijing'],
cities: cityOptions,
isIndeterminate: true
};
},
methods: {
handleCheckAllChange(val) {
this.checkedCities = val ? cityOptions : [];
this.isIndeterminate = false;
},
handleCheckedCitiesChange(value) {
let checkedCount = value.length;
this.checkAll = checkedCount === this.cities.length;
this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
}
}
};
</script>
```
:::
### Cantidad Mínima / Máxima de elementos seleccionados
Las propiedades `min` y `max` pueden limitar la cantidad de elementos seleccionados.
:::demo
```html
<template>
<el-checkbox-group
v-model="checkedCities"
:min="1"
:max="2">
<el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
</el-checkbox-group>
</template>
<script>
const cityOptions = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'];
export default {
data() {
return {
checkedCities: ['Shanghai', 'Beijing'],
cities: cityOptions
};
}
};
</script>
```
:::
### Estilo tipo Botón
Checkbox con estilo tipo Botón.
:::demo Sólo debe cambiar el elemento `el-checkbox` por el elemento `el-checkbox-button`. También proveemos el atributo `size`.
```html
<template>
<div>
<el-checkbox-group v-model="checkboxGroup1">
<el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup2" size="medium">
<el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup3" size="small">
<el-checkbox-button v-for="city in cities" :label="city" :disabled="city === 'Beijing'" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup4" size="mini" disabled>
<el-checkbox-button v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox-button>
</el-checkbox-group>
</div>
</template>
<script>
const cityOptions = ['Shanghai', 'Beijing', 'Guangzhou', 'Shenzhen'];
export default {
data () {
return {
checkboxGroup1: ['Shanghai'],
checkboxGroup2: ['Shanghai'],
checkboxGroup3: ['Shanghai'],
checkboxGroup4: ['Shanghai'],
cities: cityOptions
};
}
}
</script>
```
:::
### Con bordes
:::demo El atributo `border` agrega un borde a los Checkboxes.
```html
<template>
<div>
<el-checkbox v-model="checked1" label="Opción1" border></el-checkbox>
<el-checkbox v-model="checked2" label="Opción2" border></el-checkbox>
</div>
<div style="margin-top: 20px">
<el-checkbox v-model="checked3" label="Opción1" border size="medium"></el-checkbox>
<el-checkbox v-model="checked4" label="Opción2" border size="medium"></el-checkbox>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup1" size="small">
<el-checkbox label="Opción1" border></el-checkbox>
<el-checkbox label="Opción2" border disabled></el-checkbox>
</el-checkbox-group>
</div>
<div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup2" size="mini" disabled>
<el-checkbox label="Opción1" border></el-checkbox>
<el-checkbox label="Opción2" border></el-checkbox>
</el-checkbox-group>
</div>
</template>
<script>
export default {
data () {
return {
checked1: true,
checked2: false,
checked3: false,
checked4: true,
checkboxGroup1: [],
checkboxGroup2: []
};
}
}
</script>
```
:::
### Atributos de Checkbox
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------- | ---------------------------------------- | ------------------------- | --------------------- | ----------- |
| value / v-model | valor enlazado | string / number / boolean | — | — |
| label | valor del Checkbox si es usado dentro de un tag `checkbox-group` | string / number / boolean | — | — |
| true-label | valor del Checkbox si está marcado | string / number | — | — |
| false-label | valor del Checkbox si no está marcado | string / number | — | — |
| disabled | especifica si el Checkbox está deshabilitado | boolean | — | false |
| border | especifica si agrega un borde alrededor del Checkbox | boolean | — | false |
| size | tamaño del Checkbox, sólo funciona si `border` es true | string | medium / small / mini | — |
| name | atributo `name` nativo | string | — | — |
| checked | especifica si el Checkbox está marcado | boolean | — | false |
| indeterminate | similar a `indeterminate` en el checkbox nativo | boolean | — | false |
### Eventos de Checkbox
| Nombre | Descripción | Parámetros |
| ------ | ------------------------------------------ | -------------------- |
| change | se ejecuta cuando el valor enlazado cambia | el valor actualizado |
### Atributos de Checkbox-group
| Atributo | Descripción | Tipo | Valores aceptados | Por Defecto |
| ---------- | ---------------------------------------- | ------- | --------------------- | ----------- |
| value / v-model | valor enlazado | array | — | — |
| size | tamaño de los checkboxes de tipo botón o los checkboxes con border | string | medium / small / mini | — |
| disabled | especifica si los checkboxes anidados están deshabilitados | boolean | — | false |
| min | cantidad mínima de checkboxes que deben ser marcados | number | — | — |
| max | cantidad máxima de checkboxes que pueden ser marcados | number | — | — |
| text-color | color de fuente cuando el botón está activo | string | — | #ffffff |
| fill | color de border y de fondo cuando el botón está activo | string | — | #409EFF |
### Eventos de Checkbox-group
| Nombre de Evento | Descripción | Parámetros |
| ---------------- | ------------------------------------------ | -------------------- |
| change | se ejecuta cuando el valor enlazado cambia | el valor actualizado |
### Atributos de Checkbox-button
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------- | ---------------------------------------- | ------------------------- | ----------------- | ----------- |
| label | valor del checkbox cuando es usado dentro de un `checkbox-group` | string / number / boolean | — | — |
| true-label | valor del checkbox si este está marcado | string / number | — | — |
| false-label | valor del checkbox si este no está marcado | string / number | — | — |
| disabled | especifica si el checkbox está deshabilitado | boolean | — | false |
| name | atributo 'name' del checbox nativo | string | — | — |
| checked | si el checkbox está marcado | boolean | — | false |

View File

@@ -0,0 +1,133 @@
## Collapse
Use Collapse para almacenar contenidos.
### Uso básico
Puede expandir varios paneles
:::demo
```html
<el-collapse v-model="activeNames" @change="handleChange">
<el-collapse-item title="Consistency" name="1">
<div>Consistent with real life: in line with the process and logic of real life, and comply with languages and habits that the users are used to;</div>
<div>Consistent within interface: all elements should be consistent, such as: design style, icons and texts, position of elements, etc.</div>
</el-collapse-item>
<el-collapse-item title="Feedback" name="2">
<div>Operation feedback: enable the users to clearly perceive their operations by style updates and interactive effects;</div>
<div>Visual feedback: reflect current state by updating or rearranging elements of the page.</div>
</el-collapse-item>
<el-collapse-item title="Efficiency" name="3">
<div>Simplify the process: keep operating process simple and intuitive;</div>
<div>Definite and clear: enunciate your intentions clearly so that the users can quickly understand and make decisions;</div>
<div>Easy to identify: the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.</div>
</el-collapse-item>
<el-collapse-item title="Controllability" name="4">
<div>Decision making: giving advices about operations is acceptable, but do not make decisions for the users;</div>
<div>Controlled consequences: users should be granted the freedom to operate, including canceling, aborting or terminating current operation.</div>
</el-collapse-item>
</el-collapse>
<script>
export default {
data() {
return {
activeNames: ['1']
};
},
methods: {
handleChange(val) {
console.log(val);
}
}
}
</script>
```
:::
### Acordeón
En modo acordeón sólo un panel puede ser expandido a la vez
:::demo Activa el modo acordeón usado el atributo `accordion`.
```html
<el-collapse v-model="activeName" accordion>
<el-collapse-item title="Consistency" name="1">
<div>Consistent with real life: in line with the process and logic of real life, and comply with languages and habits that the users are used to;</div>
<div>Consistent within interface: all elements should be consistent, such as: design style, icons and texts, position of elements, etc.</div>
</el-collapse-item>
<el-collapse-item title="Feedback" name="2">
<div>Operation feedback: enable the users to clearly perceive their operations by style updates and interactive effects;</div>
<div>Visual feedback: reflect current state by updating or rearranging elements of the page.</div>
</el-collapse-item>
<el-collapse-item title="Efficiency" name="3">
<div>Simplify the process: keep operating process simple and intuitive;</div>
<div>Definite and clear: enunciate your intentions clearly so that the users can quickly understand and make decisions;</div>
<div>Easy to identify: the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.</div>
</el-collapse-item>
<el-collapse-item title="Controllability" name="4">
<div>Decision making: giving advices about operations is acceptable, but do not make decisions for the users;</div>
<div>Controlled consequences: users should be granted the freedom to operate, including canceling, aborting or terminating current operation.</div>
</el-collapse-item>
</el-collapse>
<script>
export default {
data() {
return {
activeName: '1'
};
}
}
</script>
```
:::
### Título personalizado
Además de usar el atributo `title`, se puede personalizar el título del panel con slots con nombre, esto hace posible agregar contenido personalizado, por ejemplo: iconos.
:::demo
```html
<el-collapse accordion>
<el-collapse-item name="1">
<template slot="title">
Consistency<i class="header-icon el-icon-information"></i>
</template>
<div>Consistent with real life: in line with the process and logic of real life, and comply with languages and habits that the users are used to;</div>
<div>Consistent within interface: all elements should be consistent, such as: design style, icons and texts, position of elements, etc.</div>
</el-collapse-item>
<el-collapse-item title="Feedback" name="2">
<div>Operation feedback: enable the users to clearly perceive their operations by style updates and interactive effects;</div>
<div>Visual feedback: reflect current state by updating or rearranging elements of the page.</div>
</el-collapse-item>
<el-collapse-item title="Efficiency" name="3">
<div>Simplify the process: keep operating process simple and intuitive;</div>
<div>Definite and clear: enunciate your intentions clearly so that the users can quickly understand and make decisions;</div>
<div>Easy to identify: the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.</div>
</el-collapse-item>
<el-collapse-item title="Controllability" name="4">
<div>Decision making: giving advices about operations is acceptable, but do not make decisions for the users;</div>
<div>Controlled consequences: users should be granted the freedom to operate, including canceling, aborting or terminating current operation.</div>
</el-collapse-item>
</el-collapse>
```
:::
### Atributos de Collapse
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| --------- | ------------------------------------- | ---------------------------------------- | ----------------- | ----------- |
| value / v-model | panel activo | string (modo acordeón) / array (No modo acordeón) | — | — |
| accordion | especifica si activa el modo acordeón | boolean | — | false |
### Eventos de Collapse
| Nombre de Evento | Descripción | Parámetros |
| ---------------- | --------------------------------------------- | ------------------------------------------------------------ |
| change | se dispara cuando los paneles activos cambian | (activeNames: array (No modo acordeón) / string (modo acordeón)) |
### Atributos de Collapse Item
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ----------------------------- | ------------- | ----------------- | ----------- |
| name | identificador único del panel | string/number | — | — |
| title | título del panel | string | — | — |
| disabled | deshabilita el collapse ítem | boolean | — | — |

View File

@@ -0,0 +1,124 @@
## ColorPicker
ColorPicker es un selector de color que soporta varios formatos de color.
### Uso básico
:::demo ColorPicker requiere una variable de tipo `string` para ser enlazada a `v-model`.
```html
<div class="block">
<span class="demonstration">Especifica valor por defecto</span>
<el-color-picker v-model="color1"></el-color-picker>
</div>
<div class="block">
<span class="demonstration">No especifica valor por defecto</span>
<el-color-picker v-model="color2"></el-color-picker>
</div>
<script>
export default {
data() {
return {
color1: '#409EFF',
color2: null
}
}
};
</script>
```
:::
### Alpha
:::demo ColorPicker soporta selección de canales alpha. Para activarlo sólo agregue el atributo `show-alpha`.
```html
<el-color-picker v-model="color" show-alpha></el-color-picker>
<script>
export default {
data() {
return {
color: 'rgba(19, 206, 102, 0.8)'
}
}
};
</script>
```
:::
### Colores predefinidos
:::demo ColorPicker soporta opciones de color predefinidas
```html
<el-color-picker
v-model="color"
show-alpha
:predefine="predefineColors">
</el-color-picker>
<script>
export default {
data() {
return {
color: 'rgba(255, 69, 0, 0.68)',
predefineColors: [
'#ff4500',
'#ff8c00',
'#ffd700',
'#90ee90',
'#00ced1',
'#1e90ff',
'#c71585',
'rgba(255, 69, 0, 0.68)',
'rgb(255, 120, 0)',
'hsv(51, 100, 98)',
'hsva(120, 40, 94, 0.5)',
'hsl(181, 100%, 37%)',
'hsla(209, 100%, 56%, 0.73)',
'#c7158577'
]
}
}
};
</script>
```
:::
### Sizes
:::demo
```html
<el-color-picker v-model="color"></el-color-picker>
<el-color-picker v-model="color" size="medium"></el-color-picker>
<el-color-picker v-model="color" size="small"></el-color-picker>
<el-color-picker v-model="color" size="mini"></el-color-picker>
<script>
export default {
data() {
return {
color: '#409EFF'
}
}
};
</script>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ---------------------------------------- | ------- | --------------------- | ---------------------------------------- |
| value / v-model | valor enlazado | string | — | — |
| disabled | especifica si se deshabilita el ColorPicker | boolean | — | false |
| size | tamaño del ColorPicker | string | — | medium / small / mini |
| show-alpha | especifica si se muestra el control deslizante para el valor alpha | boolean | — | false |
| color-format | formato de color del `v-model` | string | hsl / hsv / hex / rgb | hex (si show-alpha es false)/ rgb (si show-alpha es true) |
| popper-class | nombre de clase para el dropdown del ColorPicker | string | — | — |
| predefine | opciones de colores predefinidas | array | — | — |
### Eventos
| Nombre de Evento | Descripción | Parámetros |
| ---------------- | ----------------------------------------------- | ---------------------- |
| change | se dispara cuando el valor del input cambia | valor del color |
| active-change | se dispara cuando el actual color activo cambia | valor del color activo |

250
examples/docs/es/color.md Normal file
View File

@@ -0,0 +1,250 @@
<script>
import bus from '../../bus';
import { tintColor } from '../../color.js';
import { ACTION_USER_CONFIG_UPDATE } from '../../components/theme/constant.js';
const varMap = {
'primary': '$--color-primary',
'success': '$--color-success',
'warning': '$--color-warning',
'danger': '$--color-danger',
'info': '$--color-info',
'white': '$--color-white',
'black': '$--color-black',
'textPrimary': '$--color-text-primary',
'textRegular': '$--color-text-regular',
'textSecondary': '$--color-text-secondary',
'textPlaceholder': '$--color-text-placeholder',
'borderBase': '$--border-color-base',
'borderLight': '$--border-color-light',
'borderLighter': '$--border-color-lighter',
'borderExtraLight': '$--border-color-extra-light'
};
const original = {
primary: '#409EFF',
success: '#67C23A',
warning: '#E6A23C',
danger: '#F56C6C',
info: '#909399',
white: '#FFFFFF',
black: '#000000',
textPrimary: '#303133',
textRegular: '#606266',
textSecondary: '#909399',
textPlaceholder: '#C0C4CC',
borderBase: '#DCDFE6',
borderLight: '#E4E7ED',
borderLighter: '#EBEEF5',
borderExtraLight: '#F2F6FC'
}
export default {
created() {
bus.$on(ACTION_USER_CONFIG_UPDATE, this.setGlobal);
},
mounted() {
this.setGlobal();
},
methods: {
tintColor(color, tint) {
return tintColor(color, tint);
},
setGlobal() {
if (window.userThemeConfig) {
this.global = window.userThemeConfig.global;
}
}
},
data() {
return {
global: {},
primary: '',
success: '',
warning: '',
danger: '',
info: '',
white: '',
black: '',
textPrimary: '',
textRegular: '',
textSecondary: '',
textPlaceholder: '',
borderBase: '',
borderLight: '',
borderLighter: '',
borderExtraLight: ''
}
},
watch: {
global: {
immediate: true,
handler(value) {
Object.keys(original).forEach((o) => {
if (value[varMap[o]]) {
this[o] = value[varMap[o]]
} else {
this[o] = original[o]
}
});
}
}
},
}
</script>
## Color
Element utiliza un conjunto de paletas para especificar colores, y así, proporcionar una apariencia y sensación coherente para los productos que construye.
### Color principal
El color principal de Element es el azul brillante y amigable.
<el-row :gutter="12">
<el-col :span="10" :xs="{span: 12}">
<div
class="demo-color-box"
:style="{ background: primary }"
>
Brand Color<div class="value">#409EFF</div>
<div
class="bg-color-sub"
:style="{ background: tintColor(primary, 0.9) }"
>
<div
class="bg-blue-sub-item"
v-for="(item, key) in Array(8)"
:key="key"
:style="{ background: tintColor(primary, (key + 1) / 10) }"
>
</div>
</div>
</div>
</el-col>
</el-row>
### Color secundario
Además del color principal, se necesitan utilizar distintos colores para diferentes escenarios (por ejemplo, el color en tono rojo indica una operación peligrosa).
<el-row :gutter="12">
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: success }"
>Success<div class="value">#67C23A</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(success, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: warning }"
>Warning<div class="value">#E6A23C</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(warning, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: danger }"
>Danger<div class="value">#F56C6C</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(danger, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box"
:style="{ background: info }"
>Info<div class="value">#909399</div>
<div
class="bg-color-sub"
>
<div
class="bg-success-sub-item"
v-for="(item, key) in Array(2)"
:key="key"
:style="{ background: tintColor(info, (key + 8) / 10) }"
>
</div>
</div>
</div>
</el-col>
</el-row>
### Color neutro
Los colores neutrales son para texto, fondos y bordes. Puede usar diferentes colores neutrales para representar una estructura jerárquica.
<el-row :gutter="12">
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box-group">
<div class="demo-color-box demo-color-box-other"
:style="{ background: textPrimary }"
>Texto primario<div class="value">{{textPrimary}}</div></div>
<div class="demo-color-box demo-color-box-other"
:style="{ background: textRegular }"
>
Texto regular<div class="value">{{textRegular}}</div></div>
<div class="demo-color-box demo-color-box-other"
:style="{ background: textSecondary }"
>Texto secundario<div class="value">{{textSecondary}}</div></div>
<div class="demo-color-box demo-color-box-other"
:style="{ background: textPlaceholder }"
>Texto de placeholder<div class="value">{{textPlaceholder}}</div></div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box-group">
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderBase }"
>Borde base<div class="value">{{borderBase}}</div></div>
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderLight }"
>Borde ligero<div class="value">{{borderLight}}</div></div>
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderLighter }"
>Borde claro<div class="value">{{borderLighter}}</div></div>
<div class="demo-color-box demo-color-box-other demo-color-box-lite"
:style="{ background: borderExtraLight }"
>Borde extra claro<div class="value">{{borderExtraLight}}</div></div>
</div>
</el-col>
<el-col :span="6" :xs="{span: 12}">
<div class="demo-color-box-group">
<div
class="demo-color-box demo-color-box-other"
:style="{ background: black }"
>Basic Black<div class="value">{{black}}</div></div>
<div
class="demo-color-box demo-color-box-other"
:style="{ background: white, color: '#303133', border: '1px solid #eee' }"
>Basic White<div class="value">{{white}}</div></div>
<div class="demo-color-box demo-color-box-other bg-transparent">Transparent<div class="value">Transparent</div>
</div>
</div>
</el-col>
</el-row>

View File

@@ -0,0 +1,241 @@
## Contenedor
Componentes contenedores para iniciar una estructura básica de un sitio:
`<el-container>`: Contenedor. Cuando este elemento se anida con un `<el-header>` o `<el-footer>`, todos los elementos secundarios se organizan verticalmente.
De lo contrario, de forma horizontal.
`<el-header>`: Contenedor para cabeceras.
`<el-aside>`: Contenedor para secciones laterales (generalmente, una barra lateral).
`<el-main>`: Contenedor para sección principal.
`<el-footer>`: Contenedor para pie de página.
:::tip
Estos componentes utilizan flex para el diseño, así que asegúrese que el navegador lo soporta. Además, los elementos directos de `<el-container>` tienen que ser uno o más de los últimos cuatro componentes. Y el elemento padre de los últimos cuatro componentes debe ser un `<el-container>`.
:::
### Diseños comunes
:::demo
```html
<el-container>
<el-header>Cabecera</el-header>
<el-main>Principal</el-main>
</el-container>
<el-container>
<el-header>Cabecera</el-header>
<el-main>Principal</el-main>
<el-footer>Pie de página</el-footer>
</el-container>
<el-container>
<el-aside width="200px">Barra lateral</el-aside>
<el-main>Principal</el-main>
</el-container>
<el-container>
<el-header>Cabecera</el-header>
<el-container>
<el-aside width="200px">Barra lateral</el-aside>
<el-main>Principal</el-main>
</el-container>
</el-container>
<el-container>
<el-header>Cabecera</el-header>
<el-container>
<el-aside width="200px">Barra lateral</el-aside>
<el-container>
<el-main>Principal</el-main>
<el-footer>Pie de página</el-footer>
</el-container>
</el-container>
</el-container>
<el-container>
<el-aside width="200px">Barra lateral</el-aside>
<el-container>
<el-header>Cabecera</el-header>
<el-main>Principal</el-main>
</el-container>
</el-container>
<el-container>
<el-aside width="200px">Barra lateral</el-aside>
<el-container>
<el-header>Cabecera</el-header>
<el-main>Principal</el-main>
<el-footer>Pie de página</el-footer>
</el-container>
</el-container>
<style>
.el-header, .el-footer {
background-color: #B3C0D1;
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: #D3DCE6;
color: #333;
text-align: center;
line-height: 200px;
}
.el-main {
background-color: #E9EEF3;
color: #333;
text-align: center;
line-height: 160px;
}
body > .el-container {
margin-bottom: 40px;
}
.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
line-height: 260px;
}
.el-container:nth-child(7) .el-aside {
line-height: 320px;
}
</style>
```
:::
### Ejemplo
:::demo
```html
<el-container style="height: 500px; border: 1px solid #eee">
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="['1', '3']">
<el-submenu index="1">
<template slot="title"><i class="el-icon-message"></i>Navigator One</template>
<el-menu-item-group>
<template slot="title">Group 1</template>
<el-menu-item index="1-1">Option 1</el-menu-item>
<el-menu-item index="1-2">Option 2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group 2">
<el-menu-item index="1-3">Option 3</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">Option4</template>
<el-menu-item index="1-4-1">Option 4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="2">
<template slot="title"><i class="el-icon-menu"></i>Navigator Two</template>
<el-menu-item-group>
<template slot="title">Group 1</template>
<el-menu-item index="2-1">Option 1</el-menu-item>
<el-menu-item index="2-2">Option 2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group 2">
<el-menu-item index="2-3">Option 3</el-menu-item>
</el-menu-item-group>
<el-submenu index="2-4">
<template slot="title">Option 4</template>
<el-menu-item index="2-4-1">Option 4-1</el-menu-item>
</el-submenu>
</el-submenu>
<el-submenu index="3">
<template slot="title"><i class="el-icon-setting"></i>Navigator Three</template>
<el-menu-item-group>
<template slot="title">Group 1</template>
<el-menu-item index="3-1">Option 1</el-menu-item>
<el-menu-item index="3-2">Option 2</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group 2">
<el-menu-item index="3-3">Option 3</el-menu-item>
</el-menu-item-group>
<el-submenu index="3-4">
<template slot="title">Option 4</template>
<el-menu-item index="3-4-1">Option 4-1</el-menu-item>
</el-submenu>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<el-header style="text-align: right; font-size: 12px">
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px"></i>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>View</el-dropdown-item>
<el-dropdown-item>Add</el-dropdown-item>
<el-dropdown-item>Delete</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span>Tom</span>
</el-header>
<el-main>
<el-table :data="tableData">
<el-table-column prop="date" label="Date" width="140">
</el-table-column>
<el-table-column prop="name" label="Name" width="120">
</el-table-column>
<el-table-column prop="address" label="Address">
</el-table-column>
</el-table>
</el-main>
</el-container>
</el-container>
<style>
.el-header {
background-color: #B3C0D1;
color: #333;
line-height: 60px;
}
.el-aside {
color: #333;
}
</style>
<script>
export default {
data() {
const item = {
date: '2016-05-02',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles'
};
return {
tableData: Array(20).fill(item)
}
}
};
</script>
```
:::
### Atributos de contenedor
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| --------- | ---------------------------------------- | ------ | --------------------- | ---------------------------------------- |
| direction | dirección de diseño para elementos secundarios | string | horizontal / vertical | vertical cuando el elemento está anidado con `el-header`, de lo contrario, horizontal |
### Atributos de cabecera
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | --------------------- | ------ | ----------------- | ----------- |
| height | altura de la cabecera | string | — | 60px |
### Atributos de barra lateral
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ------------------------- | ------ | ----------------- | ----------- |
| width | ancho de la barra lateral | string | — | 300px |
### Atributos de pie de página
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ------------------------ | ------ | ----------------- | ----------- |
| height | altura del pie de página | string | — | 60px |

View File

@@ -0,0 +1,131 @@
## Tema personalizado
Element utiliza la metodología BEM en CSS con la finalidad de que puedas sobrescribir los estilos fácilmente. Pero, si necesita remplazar estilos a gran escala, por ejemplo, cambiar el color del tema de azul a naranja o verde, quizás reemplazarlos uno a uno no sea lo más adecuado, para ello hay 4 maneras de modificar los estilos.
### Theme Roller
Use [Online Theme Roller](./#/es/theme) para personalizar el diseño de las variables globales y componentes, y vea el resultado en tiempo real. Puede generar un completo paquete de estilos basado en un nuevo tema que puede bajar directamente (para importar los archivos del nuevo estilo al proyecto por favor vea la sección 'Importar un tema personalizado').
También puede usar [Theme Roller Chrome Extension](https://chrome.google.com/webstore/detail/element-theme-roller/lifkjlojflekabbmlddfccdkphlelmim), para personalizar un tema y ver el resultado en tiempo real en cualquier sitio desarrollado con Element.<img src="https://shadow.elemecdn.com/app/sns-client/element-theme-editor2.e16c6a01-806d-11e9-bc23-21435c54c509.png" style="width: 100%;margin: 30px auto 0;display: block;">
### Cambiando el color del tema
Si lo que se busca es cambiar el color del tema de Element, se recomienda utilizar el [sitio de visualización de temas](https://elementui.github.io/theme-chalk-preview/#/en-US). Element utiliza un color azul brillante y amigable como tema principal. Al cambiarlo, puede hacer que Element este más conectado visualmente a proyectos específicos.
Este sitio, le permitirá obtener una vista previa del tema con un nuevo color en tiempo real, y, además, obtener un paquete de estilos completo basado en el nuevo color para su descarga (para importar estos nuevos estilos, consulte la sección Importar un tema personalizado o Importar un tema de componente bajo demanda' que se encuentran dentro de esta sección).
### Actualizando variables SCSS en tu proyecto
`theme-chalk` esta escrito en SCSS. Si su proyecto también utiliza SCSS, puede cambiar las variables de estilos de Element. Para ello, solo necesita crear un nuevo archivo de estilos, por ejemplo, `element-variables.scss`:
```html
/* Color del tema */
$--color-primary: teal;
/* Ubicación de la fuente, obligatoria */
$--font-path: '~element-ui/lib/theme-chalk/fonts';
@import "~element-ui/packages/theme-chalk/src/index";
```
Entonces, en el archivo principal del proyecto, importe este archivo de estilos en lugar de los estilos de Element:
```JS
import Vue from 'vue'
import Element from 'element-ui'
import './element-variables.scss'
Vue.use(Element)
```
:::tip
Nota es necesario sobrescribir la ruta de la fuente por una ruta relativa de las fuentes de Element.
:::
### CLI para generar temas
Si su proyecto no utiliza SCSS, puede personalizar el tema a través de esta herramienta:
#### <strong>Instalación</strong>
Primero, debe instalar el generador de temas ya sea de forma global o local. Se recomienda instalarlo de forma local, ya que de esta manera, cuando otros clonen su proyecto, npm automáticamente los instalará para ellos.
```shell
npm i element-theme -g
```
Ahora, instale el tema `chalk` desde npm o Github.
```shell
# desde npm
npm i element-theme-chalk -D
# desde GitHub
npm i https://github.com/ElementUI/theme-chalk -D
```
#### <strong>Inicializar archivo de variables</strong>
Después de haber instalado correctamente los paquetes, el comando `et` estará disponible en su CLI (si instalo el paquete de manera local, utilice `node_modules/.bin/et` en su lugar). Ejecute `-i` para inicializar un archivo de variables, puede especificar un nombre distinto, pero por defecto, el archivo se llama `element-variables.scss`. También puede especificar un directorio distinto.
```shell
et -i [custom output file]
> ✔ Generator variables file
```
En el archivo `element-variables.scss` podrá encontrar todas las variables que utiliza Element para definir los estilos y estos están definidos en SCSS. Aquí un ejemplo:
```css
$--color-primary: #409EFF !default;
$--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */
$--color-primary-light-2: mix($--color-white, $--color-primary, 20%) !default; /* 66b1ff */
$--color-primary-light-3: mix($--color-white, $--color-primary, 30%) !default; /* 79bbff */
$--color-primary-light-4: mix($--color-white, $--color-primary, 40%) !default; /* 8cc5ff */
$--color-primary-light-5: mix($--color-white, $--color-primary, 50%) !default; /* a0cfff */
$--color-primary-light-6: mix($--color-white, $--color-primary, 60%) !default; /* b3d8ff */
$--color-primary-light-7: mix($--color-white, $--color-primary, 70%) !default; /* c6e2ff */
$--color-primary-light-8: mix($--color-white, $--color-primary, 80%) !default; /* d9ecff */
$--color-primary-light-9: mix($--color-white, $--color-primary, 90%) !default; /* ecf5ff */
$--color-success: #67c23a !default;
$--color-warning: #e6a23c !default;
$--color-danger: #f56c6c !default;
$--color-info: #909399 !default;
...
```
#### <strong>Modificando variables</strong>
Solo debe modificar el archivo `element-variables.scss`, por ejemplo, para cambiar el color del tema a rojo:
```CSS
$--color-primary: red;
```
#### <strong>Construyendo el tema</strong>
Después de haber modificado el archivo de variables, utilizaremos el comando `et` para construir nuestro tema. Puedes activar el modo `watch` agregando el parámetro `-w`. Y, si desea personalizar el nombre del archivo, debes agregar el parámetro `-c` seguido del nombre. Por defecto, el archivo de tema construido es colocado dentro de `./theme`. Puede especificar un directorio distinto utilizando el parámetro `-o`.
```shell
et
> ✔ build theme font
> ✔ build element theme
```
### Uso de los temas personalizados
#### <strong>Importar un tema personalizado</strong>
Importar su propio tema es igual que importar el tema por defecto, sol que esta vez se deben importar los archivos construidos con "Online Theme Roller" o "CLI tool":
```javascript
import '../theme/index.css'
import ElementUI from 'element-ui'
import Vue from 'vue'
Vue.use(ElementUI)
```
#### <strong>Importar un tema de componente bajo demanda</strong>
Si esta utilizando `babel-plugin-component` para importar bajo demanda, solo debe modificar el archivo `.babelrc` y especificar en la propiedad `styleLibraryName` la ruta en donde se encuentra localizado su tema personalizado relativo a `.babelrc`. **Nota** el carácter `~` es obligatorio:
```json
{
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "~theme"
}
]
]
}
```
Si no esta familiarizado con `babel-plugin-component`, por favor diríjase a la documentación sobre <a href="./#/en-US/component/quickstart">Como Iniciar</a>. Para más detalles, consulte el [repositorio del proyecto](https://github.com/ElementUI/element-theme) de `element-theme`.

View File

@@ -0,0 +1,491 @@
## DatePicker
Utilice Date Picker para introducir la fecha.
### Ingresar Fecha
Date Picker básico por "día".
:::demo La medida está determinada por el atributo `type` . Puede habilitar las opciones rápidas creando un objeto `picker-options` con la propiedad `shortcuts`. La fecha desactivada se ajusta mediante `disabledDate`, que es una función.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="date"
placeholder="Pick a day">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Picker with quick options</span>
<el-date-picker
v-model="value2"
type="date"
placeholder="Pick a day"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
disabledDate(time) {
return time.getTime() > Date.now();
},
shortcuts: [{
text: 'Today',
onClick(picker) {
picker.$emit('pick', new Date());
}
}, {
text: 'Yesterday',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24);
picker.$emit('pick', date);
}
}, {
text: 'A week ago',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', date);
}
}]
},
value1: '',
value2: '',
};
}
};
</script>
```
:::
### Otras mediciones
Puede elegir la semana, el mes, el año o varias fechas ampliando el componente estándar del selector de fechas.
:::demo
```html
<div class="container">
<div class="block">
<span class="demonstration">Week</span>
<el-date-picker
v-model="value1"
type="week"
format="Week WW"
placeholder="Pick a week">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Month</span>
<el-date-picker
v-model="value2"
type="month"
placeholder="Pick a month">
</el-date-picker>
</div>
</div>
<div class="container">
<div class="block">
<span class="demonstration">Year</span>
<el-date-picker
v-model="value3"
type="year"
placeholder="Pick a year">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Dates</span>
<el-date-picker
type="dates"
v-model="value4"
placeholder="Pick one or more dates">
</el-date-picker>
</div>
</div>
<script>
export default {
data() {
return {
value1: '',
value2: '',
value3: '',
value4: ''
};
}
};
</script>
```
:::
### Rango de fechas
Se soporta la selección de un rango de fechas.
:::demo En modo de rango, los paneles izquierdo y derecho están vinculados por defecto. Si desea que los dos paneles cambien los meses actuales de forma independiente, puede utilizar el atributo `unlink-panels`.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="daterange"
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With quick options</span>
<el-date-picker
v-model="value2"
type="daterange"
align="right"
unlink-panels
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'Last week',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last month',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last 3 months',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
},
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Rango de mes
Se admite la selección de un intervalo de un mes.
:::demo Cuando se encuentra en el modo de rango, los paneles izquierdo y derecho están enlazados de forma predeterminada. Si desea que los dos paneles cambien de año en curso de forma independiente, puede utilizar el atributo unlink-panels.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="monthrange"
range-separator="To"
start-placeholder="Start month"
end-placeholder="End month">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With quick options</span>
<el-date-picker
v-model="value2"
type="monthrange"
align="right"
unlink-panels
range-separator="To"
start-placeholder="Start month"
end-placeholder="End month"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'This month',
onClick(picker) {
picker.$emit('pick', [new Date(), new Date()]);
}
}, {
text: 'This year',
onClick(picker) {
const end = new Date();
const start = new Date(new Date().getFullYear(), 0);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last 6 months',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setMonth(start.getMonth() - 6);
picker.$emit('pick', [start, end]);
}
}]
},
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Valor por defecto
Si el usuario no ha escogido una fecha, muestra el calendario de hoy por defecto. Puede utilizar `default-value` para fijar otra fecha. Su valor debe ser definido por `new Date()`.
Si el tipo es `daterange`, `default-value` establece el calendario del lado izquierdo.
:::demo
```html
<template>
<div class="block">
<span class="demonstration">date</span>
<el-date-picker
v-model="value1"
type="date"
placeholder="Pick a date"
default-value="2010-10-01">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">daterange</span>
<el-date-picker
v-model="value2"
type="daterange"
align="right"
start-placeholder="Start Date"
end-placeholder="End Date"
default-value="2010-10-01">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Formatos de Date
Utilice `format` para controlar el formato del texto visualizado en el input. Utilice `value-format` para controlar el formato del valor vinculado.
Por defecto, el componente acepta y emite un objeto Date. A continuación se soportan cadenas de formato, usando UTC 2017-01-02 03:04:05 como ejemplo:
:::warning
Preste atención a la capitalización
:::
| formato | significado | nota | ejemplo |
| ----------- | ------------ | ---------------------------------------- | ------------- |
| `yyyy` | año | | 2017 |
| `M` | mes | no acepta 0 | 1 |
| `MM` | mes | | 01 |
| `W` | semana | solamente para semanas en picker's `format`; no acepta 0 | 1 |
| `WW` | semana | solamente para semanas en picker's `format` | 01 |
| `d` | día | no acepta 0 | 2 |
| `dd` | día | | 02 |
| `H` | hora | 24-hora reloj; no acepta 0 | 3 |
| `HH` | hora | 24-hora reloj | 03 |
| `h` | hora | 12-hora reloj; debe usarse con `A` o `a`; no acepta 0 | 3 |
| `hh` | hora | 12-hora reloj; debe usarse con `A` o `a` | 03 |
| `m` | minuto | no acepta 0 | 4 |
| `mm` | minuto | | 04 |
| `s` | segundo | no acepta 0 | 5 |
| `ss` | segundo | | 05 |
| `A` | AM/PM | solamente para `format`, mayúsculas | AM |
| `a` | am/pm | solamente para `format`, minúsculas | am |
| `timestamp` | JS timestamp | solamente para `value-format`; valor vinculado debe ser un `number` | 1483326245000 |
| `[MM]` | No hay caracteres de escape | Para escapar de los caracteres, colóquelos entre corchetes (ejemplo: [A] [MM]). | MM |
:::demo
```html
<template>
<div class="block">
<span class="demonstration">Emits Date object</span>
<div class="demonstration">Value: {{ value1 }}</div>
<el-date-picker
v-model="value1"
type="date"
placeholder="Pick a Date"
format="yyyy/MM/dd">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Use value-format</span>
<div class="demonstration">Value: {{ value2 }}</div>
<el-date-picker
v-model="value2"
type="date"
placeholder="Pick a Date"
format="yyyy/MM/dd"
value-format="yyyy-MM-dd">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Timestamp</span>
<div class="demonstration">Value{{ value3 }}</div>
<el-date-picker
v-model="value3"
type="date"
placeholder="Pick a Date"
format="yyyy/MM/dd"
value-format="timestamp">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value1: '',
value2: '',
value3: ''
};
}
};
</script>
```
:::
### Hora por defecto para comienzo y fin de fecha
Al seleccionar un intervalo de fechas, puede asignar la hora para la fecha de inicio y la fecha final.
:::demo Por defecto, la hora de la fecha de inicio y final es `00:00:00`. Configurar `default-time` puede cambiar la hora respectivamente. Acepta un array de hasta dos cadenas con el formato `12:00:00`. La primera cadena fija la hora para la fecha de inicio y la segunda para la fecha final.
```html
<template>
<div class="block">
<p>Component value{{ value }}</p>
<el-date-picker
v-model="value"
type="daterange"
start-placeholder="Start date"
end-placeholder="End date"
:default-time="['00:00:00', '23:59:59']">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value: ''
};
}
};
</script>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------- | ---------------------------------------- | ----------------- | ---------------------------------------- | -------------------- |
| value / v-model | valor enlazado | date(DatePicker) / array(DateRangePicker) | — | — |
| readonly | si DatePicker es solo de lectura | boolean | — | false |
| disabled | si DatePicker esta deshabilitado | boolean | — | false |
| size | tamaño del input | string | large/small/mini | — |
| editable | si el input es editable | boolean | — | true |
| clearable | si se muestra el botón de borrado | boolean | — | true |
| placeholder | placeholder cuando el modo NO es rango | string | — | — |
| start-placeholder | placeholder para la fecha de inicio en modo rango | string | — | — |
| end-placeholder | placeholder para la fecha final en modo rango | string | — | — |
| type | tipo de picker | string | year/month/date/dates/datetime/ week/datetimerange/daterange/ monthrange | date |
| format | formato en que se muestra el valor en el input | string | ver [date formats](#/es/component/date-picker#date-formats) | yyyy-MM-dd |
| align | alineación | left/center/right | left | |
| popper-class | nombre de clase personalizada para el dropdown de DatePicker | string | — | — |
| picker-options | opciones adicionales, chequee la tabla debajo | object | — | {} |
| range-separator | separador de rangos | string | — | '-' |
| default-value | opcional, valor por defecto para el calendario | Date | cualquiera aceptado por `new Date()` | — |
| default-time | opcional, los valores para las horas que se deben usar en la selección de fechas cuando se usa el modo rango | string[] | Array de dos valores, cada uno es un string del estilo `12:00:00`. El primer elemento es para la fecha de inicio y el segundo es para la fecha final. | — |
| value-format | opcional, formato del valor enlazado. Si no esta especificado, el valor enlazado será un objeto Date. | string | ver [date formats](#/es/component/date-picker#date-formats) | — |
| name | igual que `name` en el input nativo | string | — | — |
| unlink-panels | desvincular los dos paneles de fecha en el range-picker | boolean | — | false |
| prefix-icon | Clase personalizada para el icono prefijado | string | — | el-icon-date |
| clear-icon | Clase personalizada para el icono `clear` | string | — | el-icon-circle-close |
### Opciones del Picker
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ------------------------------------------------------------ | ------------------------------ | ----------------- | ----------- |
| shortcuts | { text, onClick } un array de objetos para establecer opciones de acceso directo, verifique la tabla siguiente | object[] | — | — |
| disabledDate | una función que determina si una fecha está desactivada con esa fecha como parámetro. Debería devolver un valor booleano | function | — | — |
| cellClassName | establecer nombre de clase personalizado | Function(Date) | — | — |
| firstDayOfWeek | primer día de la semana | Number | 1 to 7 | 7 |
| onPick | una función que se dispara cuando se cambia la fecha seleccionada. Solamente para `daterange` y `datetimerange`. | Function({ maxDate, minDate }) | - | - |
### Accesso directo
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ---------------------------------------- | -------- | ----------------- | ----------- |
| text | título del acceso directo | string | — | — |
| onClick | una función se dispara al hacer clic en el acceso directo, con`vm`como parámetro. Puede modificar el valor del picker emitiendo el evento `pick`. Ejemplo: `vm.$emit('pick', new Date())` | function | — | — |
### Eventos
| Nombre | Descripción | Parámetros |
| ------ | ---------------------------------------------- | ---------------------------- |
| change | se dispara cuando el usuario confirma el valor | valor enlazado al componente |
| blur | se dispara cuando el input pierde el foco | instancia del componente |
| focus | se dispara cuando el input obtiene el foco | instancia del componente |
### Métodos
| Método | Descripción | Parámetros |
| ------ | -------------------------- | ---------- |
| focus | coloca el foco en el input | — |
### Slots
| Nombre | Descripción |
| --------------- | ------------------------------------- |
| range-separator | Separador de los rangos personalizado |

View File

@@ -0,0 +1,243 @@
## DateTimePicker
Seleccionar fecha y tiempo juntos en un picker.
:::tip
DateTimePicker se deriva de DatePicker y TimePicker. Por una explicación más detallada sobre `pickerOptions` y otros atributos, puede referirse a DatePicker y TimePicker.
:::
### Fecha y hora
:::demo Puede seleccionar la fecha y la hora en un picker al mismo tiempo configurando el tipo de fecha y la hora. La forma de utilizar los atajos es la misma que con Date Picker.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="datetime"
placeholder="Select date and time">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With shortcuts</span>
<el-date-picker
v-model="value2"
type="datetime"
placeholder="Select date and time"
:picker-options="pickerOptions">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With default time</span>
<el-date-picker
v-model="value3"
type="datetime"
placeholder="Select date and time"
default-time="12:00:00">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'Today',
onClick(picker) {
picker.$emit('pick', new Date());
}
}, {
text: 'Yesterday',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24);
picker.$emit('pick', date);
}
}, {
text: 'A week ago',
onClick(picker) {
const date = new Date();
date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', date);
}
}]
},
value1: '',
value2: '',
value3: ''
};
}
};
</script>
```
:::
### Alcance de fecha y tiempo
:::demo Puede seleccionar la fecha y el rango de tiempo ajustando `type` a `datetimerange`.
```html
<template>
<div class="block">
<span class="demonstration">Default</span>
<el-date-picker
v-model="value1"
type="datetimerange"
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">With shortcuts</span>
<el-date-picker
v-model="value2"
type="datetimerange"
:picker-options="pickerOptions"
range-separator="To"
start-placeholder="Start date"
end-placeholder="End date"
align="right">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
pickerOptions: {
shortcuts: [{
text: 'Last week',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last month',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: 'Last 3 months',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
}]
},
value1: [new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
value2: ''
};
}
};
</script>
```
:::
### Valor de la hora por defecto para la fecha de inicio y la fecha final
:::demo Cuando se selecciona el rango de fechas en el panel con el tipo datetimerange, 00:00:00:00 se usará como el valor de tiempo predeterminado para la fecha de inicio y fin. Podemos controlarlo con el atributo default-time. default-time acepta una matriz de hasta dos cadenas. La primera posición controla el valor de tiempo de la fecha de inicio y la segunda el valor de tiempo de la fecha de fin.
```html
<template>
<div class="block">
<span class="demonstration">Start date time 12:00:00</span>
<el-date-picker
v-model="value1"
type="datetimerange"
start-placeholder="Start Date"
end-placeholder="End Date"
:default-time="['12:00:00']">
</el-date-picker>
</div>
<div class="block">
<span class="demonstration">Start date time 12:00:00, end date time 08:00:00</span>
<el-date-picker
v-model="value2"
type="datetimerange"
align="right"
start-placeholder="Start Date"
end-placeholder="End Date"
:default-time="['12:00:00', '08:00:00']">
</el-date-picker>
</div>
</template>
<script>
export default {
data() {
return {
value1: '',
value2: ''
};
}
};
</script>
```
:::
### Atributos
| Atributos | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------------ | ---------------------------------------- | ----------------- | ---------------------------------------- | -------------------- |
| value / v-model | valor enlazado | date(DateTimePicker) / array(DateTimeRangePicker) | — | — |
| readonly | si DatePicker es solo de lectura | boolean | — | false |
| disabled | si DatePicker esta deshabilitada | boolean | — | false |
| editable | Si la entrada es editable | boolean | — | true |
| clearable | Si mostrar el botón de `clear` | boolean | — | true |
| size | tamaño del input | string | large/small/mini | — |
| placeholder | placeholder cuando el modo NO es Range | string | — | — |
| start-placeholder | placeholder para el inicio de fecha en el modo Range | string | — | — |
| end-placeholder | placeholder para el fin de fecha en el modo Range | string | — | — |
| time-arrow-control | si se puede modificar el `time` utilizando botones con flechas | boolean | — | false |
| type | tipo del picker | string | year/month/date/datetime/ week/datetimerange/daterange | date |
| format | formato de valor mostrado en el input | string | ver [date formats](#/es/component/date-picker#date-formats) | yyyy-MM-dd HH:mm:ss |
| align | alineación | left/center/right | left | |
| popper-class | nombre de clase personalizado para el Dropdown de DatePicker | string | — | — |
| picker-options | opciones adicionales, Comprueba la tabla de mas abajo | object | — | {} |
| range-separator | separador de rango | string | - | '-' |
| default-value | opcional, fecha predeterminada del calendario | Fecha | cualquier cosa aceptada por `new Date()` — | |
| default-time | el valor de tiempo por defecto después de elegir una fecha | non-range: string / range: string[] | non-range: Una cadena de texto como `12:00:00`, range: array de dos strings, el primero es para la fecha de inicio y el segundo para la fecha final. 00:00:00 se utilizará si no se especifica | — |
| value-format | opcional, formato de valor de enlazado. Si no se especifica, el valor de enlazado será un objeto Date | cadena | ver [date formats](#/es/component/date-picker#date-formats) | — |
| name | igual que `name` en la entrada nativa | string | — | — |
| unlink-panels | desconectar dos date-panels en range-picker | boolean | — | false |
| prefix-icon | Clase personalizada para el icono prefijado | string | — | el-icon-date |
| clear-icon | Clase personalizada para el icono `clear` | string | — | el-icon-circle-close |
| validate-event | si se debe disparar la validación | boolean | - | true |
### Picker Options
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ---------------------------------------- | -------- | ----------------- | ----------- |
| shortcuts | un array de objetos { text, onClick } para establecer las opciones de acceso directo, verifique la tabla debajo | objeto[] | — | — |
| disabledDate | una función que determina si una fecha está desactivada con esa fecha como parámetro. Debería devolver un booleano | función | — | — |
| cellClassName | establecer nombre de clase personalizado | Function(Date) | — | — |
| firstDayOfWeek | primera día de semana | Número | 1 to 7 | 7 |
### Accesos directos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ------------------------------------------------------------ | -------- | ----------------- | ----------- |
| text | título del acceso directo | string | — | — |
| onClick | la función se dispara cuando se hace clic en el acceso directo, con el `vm` como parámetro. Puede modificar el valor del picker emitiendo el evento`pick`. Ejemplo: `vm.$emit('pick', new Date())` | function | — | — |
### Eventos
| Nombre de evento | Descripción | Parámetros |
| ---------------- | ---------------------------------------- | ----------------------------- |
| change | Se dispara cuando el usuario confirma el valor | valor enlazado del componente |
| blur | Se dispara cuando el input pierde el foco | instancia del componente |
| focus | Se dispara cuando el input obtiene el foco | instancia del componente |
### Métodos
| Método | Descripción | Parámetros |
| ------ | ---------------- | ---------- |
| focus | foco en el input | — |

249
examples/docs/es/dialog.md Normal file
View File

@@ -0,0 +1,249 @@
## Dialog
Informar a usuarios preservando el estado de la página actual.
### Uso Básico
Dialog abre una caja de diálogo, y es bastante personalizable.
:::demo Establezca el atributo `visible` con un booleano, y el Dialog se muestra cuando es `true`. El diálogo tiene dos partes: `body` y `footer`, este último requiere un slot llamado `footer`. El atributo `title` es opcional (vacío por defecto) y sirve para definir un título. Por último, este ejemplo muestra cómo se utiliza `before-close`.
```html
<el-button type="text" @click="dialogVisible = true">click to open the Dialog</el-button>
<el-dialog
title="Tips"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<span>This is a message</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">Cancel</el-button>
<el-button type="primary" @click="dialogVisible = false">Confirm</el-button>
</span>
</el-dialog>
<script>
export default {
data() {
return {
dialogVisible: false
};
},
methods: {
handleClose(done) {
this.$confirm('Are you sure to close this dialog?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
```
:::
:::tip
`before-close` sólo funciona cuando el usuario hace clic en el icono de cerrar o en el fondo. Si tiene botones que cierran el cuadro de diálogo en el slot llamado `footer`, puede agregar lo que haría `before-close` en el manejador de eventos de los botones.
:::
### Personalizaciones
El contenido del Diálogo puede ser cualquier cosa, incluso una tabla o un formulario. Este ejemplo muestra cómo usar Element Table y Form con Dialog
:::demo
```html
<!-- Table -->
<el-button type="text" @click="dialogTableVisible = true">open a Table nested Dialog</el-button>
<el-dialog title="Shipping address" :visible.sync="dialogTableVisible">
<el-table :data="gridData">
<el-table-column property="date" label="Date" width="150"></el-table-column>
<el-table-column property="name" label="Name" width="200"></el-table-column>
<el-table-column property="address" label="Address"></el-table-column>
</el-table>
</el-dialog>
<!-- Form -->
<el-button type="text" @click="dialogFormVisible = true">open a Form nested Dialog</el-button>
<el-dialog title="Shipping address" :visible.sync="dialogFormVisible">
<el-form :model="form">
<el-form-item label="Promotion name" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Zones" :label-width="formLabelWidth">
<el-select v-model="form.region" placeholder="Please select a zone">
<el-option label="Zone No.1" value="shanghai"></el-option>
<el-option label="Zone No.2" value="beijing"></el-option>
</el-select>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">Cancel</el-button>
<el-button type="primary" @click="dialogFormVisible = false">Confirm</el-button>
</span>
</el-dialog>
<script>
export default {
data() {
return {
gridData: [{
date: '2016-05-02',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-04',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-01',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-03',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}],
dialogTableVisible: false,
dialogFormVisible: false,
form: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
formLabelWidth: '120px'
};
}
};
</script>
```
:::
### Diálogo anidado
Si un diálogo está anidado en otro diálogo, se requiere append-to-body.
:::demo Normalmente no recomendamos el uso de Dialog anidado. Si necesita que se muestren múltiples diálogos en la página, puede simplemente aplanarlos para que sean hermanos entre sí. Si debe anidar un Diálogo dentro de otro Diálogo, establezca `append-to-body` del Diálogo anidado como true, y lo añadirá al cuerpo en lugar de su nodo padre, para que ambos Diálogos puedan ser correctamente renderizados.
```html
<template>
<el-button type="text" @click="outerVisible = true">open the outer Dialog</el-button>
<el-dialog title="Outer Dialog" :visible.sync="outerVisible">
<el-dialog
width="30%"
title="Inner Dialog"
:visible.sync="innerVisible"
append-to-body>
</el-dialog>
<div slot="footer" class="dialog-footer">
<el-button @click="outerVisible = false">Cancel</el-button>
<el-button type="primary" @click="innerVisible = true">open the inner Dialog</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
data() {
return {
outerVisible: false,
innerVisible: false
};
}
}
</script>
```
:::
### Contenido centrado
El contenido de Diálogo se puede centrar.
:::demo Ajuste `center` en `true` para centrar el encabezado y el pie de página del cuadro de diálogo horizontalmente. `center` sólo afecta al encabezado y pie de página de Dialog. El cuerpo de Dialog puede ser cualquier cosa, así que a veces no se ve bien cuando está centrado. Necesitas escribir algún CSS si deseas centrar el cuerpo también.
```html
<el-button type="text" @click="centerDialogVisible = true">Click to open the Dialog</el-button>
<el-dialog
title="Warning"
:visible.sync="centerDialogVisible"
width="30%"
center>
<span>It should be noted that the content will not be aligned in center by default</span>
<span slot="footer" class="dialog-footer">
<el-button @click="centerDialogVisible = false">Cancel</el-button>
<el-button type="primary" @click="centerDialogVisible = false">Confirm</el-button>
</span>
</el-dialog>
<script>
export default {
data() {
return {
centerDialogVisible: false
};
}
};
</script>
```
:::
:::tip
El contenido de Dialog se renderiza en modo lazy, lo que significa que la ranura por defecto no se renderiza en el DOM hasta que se abre por primera vez. Por lo tanto, si necesita realizar una manipulación DOM o acceder a un componente mediante ref, hágalo en el callback del evento `open`.
:::
:::tip
Si la variable ligada a `visible` se gestiona en el Vuex store, el `.sync` no puede funcionar correctamente. En este caso, elimine el modificador `.sync`, escuche los eventos de `open` y `close` Dialog, y confirme las mutaciones Vuex para actualizar el valor de esa variable en los manejadores de eventos.
:::
### Atributo
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| --------------------- | ---------------------------------------- | ---------------------------------------- | ----------------- | ----------- |
| visible | visibilidad del Diálogo, apoya el modificador .sync | boolean | — | false |
| title | título de Diálogo. También se puede pasar con un slot con nombre (ver la tabla siguiente) | string | — | — |
| width | anchura de Diálogo | string | — | 50% |
| fullscreen | si el diálogo ocupa pantalla completa | boolean | — | false |
| top | valor de `margin-top` del Diálogo CSS | string | — | 15vh |
| modal | si se muestra una máscara | boolean | — | true |
| modal-append-to-body | si adjuntar modal al elemento de cuerpo. Si es falso,el modal se agregará al elemento principal de Diálogo | boolean | — | true |
| append-to-body | Si adjuntar el cuadro de diálogo al cuerpo | boolean | — | false |
| lock-scroll | Si el scroll del cuerpo está desactivado mientras se muestra el cuadro de diálogo | boolean | — | true |
| custom-class | nombres de clase personalizada para el Diálogo | string | — | — |
| close-on-click-modal | si el Diálogo puede ser cerrado haciendo clic en la máscara | boolean | — | true |
| close-on-press-escape | si el Diálogo puede ser cerrado presionando ESC | boolean | — | true |
| show-close | si mostrar un botón de cerrar | boolean | — | true |
| before-close | una devolución de llamada antes de que se cierre el cuadro de diálogo, y evitar cerrar el cuadro de diálogo | función(done) `done`se usa para cerrar el diálog | — | — |
| center | si alinear el encabezado y el pie de página en el centro | boolean | — | false |
| destroy-on-close | Destruir elementos en Dialog cuando se cierra | boolean | — | false |
### Slots
| Nombre | Descripción |
| ------ | -------------------------------------- |
| — | contenido de Diálogo |
| title | contenido del título de Diálogo |
| footer | contenido del pie de página de Diálogo |
### Eventos
| Nombre de Evento | Descripción | Parámetros |
| ---------------- | ---------------------------------------- | ---------- |
| open | se activa cuando se abre el cuadro de Diálogo | — |
| opened | se activa cuando la animación de apertura del Dialog termina. | — |
| close | se dispara cuando el Diálogo se cierra | — |
| closed | se activa cuando finaliza la animación de cierre del Diálog | — |

View File

@@ -0,0 +1,61 @@
## Divider
La línea divisoria que separa el contenido.
### Uso básico
Divide el texto de los diferentes párrafos.
:::demo
```html
<template>
<div>
<span>I sit at my window this morning where the world like a passer-by stops for a moment, nods to me and goes.</span>
<el-divider></el-divider>
<span>There little thoughts are the rustle of leaves; they have their whisper of joy in my mind.</span>
</div>
</template>
```
:::
### Contenido personalizado
Puede personalizar el contenido en la línea divisoria.
:::demo
```html
<template>
<div>
<span>What you are you do not see, what you see is your shadow. </span>
<el-divider content-position="left">Rabindranath Tagore</el-divider>
<span>I cannot choose the best. The best chooses me.</span>
<el-divider><i class="el-icon-star-on"></i></el-divider>
<span>My wishes are fools, they shout across thy song, my Master. Let me but listen.</span>
<el-divider content-position="right">Rabindranath Tagore</el-divider>
</div>
</template>
```
:::
### División vertical
:::demo
```html
<template>
<div>
<span>Rain</span>
<el-divider direction="vertical"></el-divider>
<span>Home</span>
<el-divider direction="vertical"></el-divider>
<span>Grass</span>
</div>
</template>
```
:::
### Divider Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|------------- |---------------- |---------------- |---------------------- |-------- |
| direction | indica la dirección del separador | string | horizontal / vertical | horizontal |
| content-position | personaliza el contenido en la línea divisoria | String | left / right / center | center |

305
examples/docs/es/drawer.md Normal file
View File

@@ -0,0 +1,305 @@
## Drawer
A veces, `Dialog` no siempre satisface nuestros requisitos, digamos que tiene un formulario masivo, o necesita espacio para mostrar algo como `terminos & condiciones`, `Drawer` tiene una API casi idéntica a `Dialog`, pero introduce una experiencia de usuario diferente.
### Uso básico
Llamada de un drawer temporal, desde varias direcciones
:::demo Debe establecer `visible` para `Drawer` como lo hace `Dialog` para controlar la visibilidad. `visible` es del tipo `boolean`. `Drawer` tiene partes: `title` & `body`, el `title` es un slot con nombre, también puede establecer el título a través de un atributo llamado `title`, por defecto a una cadena vacía, la parte `body` es el área principal de `Drawer`, que contiene contenido definido por el usuario. Al abrir, `Drawer` se expande desde la **esquina derecha a la izquierda** cuyo tamaño es **30%** de la ventana del navegador por defecto. Puede cambiar ese comportamiento predeterminado estableciendo los atributos `direction` y `size`. Este caso de demostración también muestra cómo utilizar la API `before-close`, consulte la sección Atributos para obtener más detalles.
```html
<el-radio-group v-model="direction">
<el-radio label="ltr">left to right</el-radio>
<el-radio label="rtl">right to left</el-radio>
<el-radio label="ttb">top to bottom</el-radio>
<el-radio label="btt">bottom to top</el-radio>
</el-radio-group>
<el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
open
</el-button>
<el-drawer
title="I am the title"
:visible.sync="drawer"
:direction="direction"
:before-close="handleClose">
<span>Hi, there!</span>
</el-drawer>
<script>
export default {
data() {
return {
drawer: false,
direction: 'rtl',
};
},
methods: {
handleClose(done) {
this.$confirm('Are you sure you want to close this?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
```
:::
### Sin titulo
Si no necesitas el titulo lo puedes eliminar del drawer.
:::demo Asigne **false** al atributo `withHeader`, se puede eliminar el atributo title del drawer, de esa manera el drawer tendrá mas espacio para el contenido. Por razones de accesibilidad se recomienda asignar siempre un contenido valido al atributo `title`.
```html
<el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
open
</el-button>
<el-drawer
title="I am the title"
:visible.sync="drawer"
:with-header="false">
<span>Hi there!</span>
</el-drawer>
<script>
export default {
data() {
return {
drawer: false,
};
}
};
</script>
```
:::
### Personalizar el contenido
Al igual que `Dialog`, `Drawer` puede hacer muchas interacciones diversas.
:::demo
```html
<el-button type="text" @click="table = true">Open Drawer with nested table</el-button>
<el-button type="text" @click="dialog = true">Open Drawer with nested form</el-button>
<el-drawer
title="I have a nested table inside!"
:visible.sync="table"
direction="rtl"
size="50%">
<el-table :data="gridData">
<el-table-column property="date" label="Date" width="150"></el-table-column>
<el-table-column property="name" label="Name" width="200"></el-table-column>
<el-table-column property="address" label="Address"></el-table-column>
</el-table>
</el-drawer>
<el-drawer
title="I have a nested form inside!"
:before-close="handleClose"
:visible.sync="dialog"
direction="ltr"
custom-class="demo-drawer"
ref="drawer"
>
<div class="demo-drawer__content">
<el-form :model="form">
<el-form-item label="Name" :label-width="formLabelWidth">
<el-input v-model="form.name" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Area" :label-width="formLabelWidth">
<el-select v-model="form.region" placeholder="Please select activity area">
<el-option label="Area1" value="shanghai"></el-option>
<el-option label="Area2" value="beijing"></el-option>
</el-select>
</el-form-item>
</el-form>
<div class="demo-drawer__footer">
<el-button @click="cancelForm">Cancel</el-button>
<el-button type="primary" @click="$refs.drawer.closeDrawer()" :loading="loading">{{ loading ? 'Submitting ...' : 'Submit' }}</el-button>
</div>
</div>
</el-drawer>
<script>
export default {
data() {
return {
table: false,
dialog: false,
loading: false,
gridData: [{
date: '2016-05-02',
name: 'Peter Parker',
address: 'Queens, New York City'
}, {
date: '2016-05-04',
name: 'Peter Parker',
address: 'Queens, New York City'
}, {
date: '2016-05-01',
name: 'Peter Parker',
address: 'Queens, New York City'
}, {
date: '2016-05-03',
name: 'Peter Parker',
address: 'Queens, New York City'
}],
form: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
formLabelWidth: '80px',
timer: null,
};
},
methods: {
handleClose(done) {
if (this.loading) {
return;
}
this.$confirm('Do you want to submit?')
.then(_ => {
this.loading = true;
this.timer = setTimeout(() => {
done();
// animation takes time
setTimeout(() => {
this.loading = false;
}, 400);
}, 2000);
})
.catch(_ => {});
},
cancelForm() {
this.loading = false;
this.dialog = false;
clearTimeout(this.timer);
}
}
}
</script>
```
:::
### Drawer anidados
También puede tener varias capas de `Drawer` al igual que con `Dialog`.
:::demo Si necesita varios drawer en diferentes capas, debe establecer el atributo `append-to-body` en **true**
```html
<el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
open
</el-button>
<el-drawer
title="I'm outer Drawer"
:visible.sync="drawer"
size="50%">
<div>
<el-button @click="innerDrawer = true">Click me!</el-button>
<el-drawer
title="I'm inner Drawer"
:append-to-body="true"
:before-close="handleClose"
:visible.sync="innerDrawer">
<p>_(:зゝ∠)_</p>
</el-drawer>
</div>
</el-drawer>
<script>
export default {
data() {
return {
drawer: false,
innerDrawer: false,
};
},
methods: {
handleClose(done) {
this.$confirm('You still have unsaved data, proceed?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
```
:::
:::tip
El contenido dentro del Drawer debe ser renderizado de forma perezosa, lo que significa que el contenido dentro del Drawer no afectará al rendimiento inicial del renderizado, por lo que cualquier operación DOM debe realizarse a través de `ref' o después de que se emita el evento `open'.
:::
:::tip
El Drawer proporciona una API llamada "destroyOnClose", que es una variable de bandera que indica que debe destruir el contenido hijo dentro del Drawer después de que se haya cerrado. Puede utilizar esta API cuando necesite que su ciclo de vida "mounted" sea llamado cada vez que se abra el Cajón.
:::
:::tip
Si la variable `visible` se gestiona en el almacén de Vuex, el `.sync` no puede funcionar correctamente. En este caso, elimine el modificador `.sync`, escuche los eventos `open` y `close` de Drawer, y envíe mutaciones Vuex para actualizar el valor de esa variable en los manejadores de eventos.
:::
### Atributos de Drawer
| Parámetros | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| append-to-body | Los controles deberían insertar Drawer en el elemento DocumentBody, los Drawer anidados deben asignar este parámetro a **true** | boolean | — | false |
| before-close | Si está configurado, el procedimiento de cierre se detendrá. | function(done), done es un tipo de función que acepta un booleano como parámetro, una llamada hecha con true o sin parámetro abortará el procedimiento de cierre. | — | — |
| close-on-press-escape | Indica si el Drawer puede cerrarse pulsando ESC | boolean | — | true |
| custom-class | Nombre extra de clase para Drawer | string | — | — |
| destroy-on-close | Indica si los children deben ser destruidos después de cerrar el Drawer. | boolean | - | false |
| modal | Mostrará una capa de sombra | boolean | — | true |
| modal-append-to-body | Indica si se debe insertar una capa de sombreado en el elemento DocumentBody | boolean | — | true |
| direction | Dirección de apertura del Drawer | Direction | rtl / ltr / ttb / btt | rtl |
| show-close | Se mostrará el botón de cerrar en la parte superior derecha del Drawer | boolean | — | true |
| size | Tamaño del Drawer. Si el Drawer está en modo horizontal, afecta a la propiedad width, de lo contrario afecta a la propiedad height, cuando el tamaño es tipo `number`, describe el tamaño por unidad de píxeles; cuando el tamaño es tipo `string`, se debe usar con notación `x%`, de lo contrario se interpretará como unidad de píxeles. | number / string | - | '30%' |
| title | El título del Drawer, también se puede establecer por slot con nombre, las descripciones detalladas se pueden encontrar en el formulario de slot. | string | — | — |
| visible | Si se muestra el Drawer, también soporta la notación `.sync` | boolean | — | false |
| wrapperClosable | Indica si el usuario puede cerrar el Drawer haciendo clic en la capa de sombreado. | boolean | - | true |
| withHeader | Indica si la sección header existirá, por defecto es true, cuando es false no tienen efecto, ambos, `title attribute` y `title slot` | boolean | - | true |
### Drawer Slot's
| Nombre | Descripción |
|------|--------|
| — | El contenido del Drawer |
| title | El titulo de la sección del Drawer |
### Métodos Drawer
| Nombre | Descripción |
| ---- | --- |
| closeDrawer | Para cerrar el Drawer, este método llamará `before-close`. |
### Eventos Drawer
| Nombre | Descripción | Parámetros |
|---------- |-------- |---------- |
| open | Se activa antes de que comience la animación de apertura del Drawer. | — |
| opened | Se activa cuando finaliza la animación de apertura del Drawer. | — |
| close | Se activa antes de que comience la animación de cierre del Drawer. | — |
| closed | Se activa después de que finaliza la animación de cierre del Drawer. | — |

View File

@@ -0,0 +1,305 @@
## Dropdown
Menú conmutable para visualizar listas de enlaces y acciones.
### Uso básico
Pase el ratón por el menú desplegable para desplegarlo y obtener más acciones.
:::demo El elemento desencadenante se representa con el slot predeterminado, y la parte desplegable se representa con el slot llamado dropdown. Por defecto, la lista desplegable se muestra cuando se pasa el ratón por encima del elemento desencadenante sin necesidad de hacer clic en él.
```html
<el-dropdown>
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item disabled>Action 4</el-dropdown-item>
<el-dropdown-item divided>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
```
:::
### Elemento detonante
Utilizando un botón para activar la lista desplegable.
:::demo Utilice `split-button` para dividir el elemento detonante en un grupo de botones, siendo el botón izquierdo un botón normal y el botón derecho el objetivo real de la detonación. Si desea insertar una línea de separación entre la posición tres y la posición cuatro, sólo añada un divisor de clase a la posición cuatro.
```html
<el-dropdown>
<el-button type="primary">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</el-button>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
<el-dropdown-item>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown split-button type="primary" @click="handleClick">
Dropdown List
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
<el-dropdown-item>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown {
vertical-align: top;
}
.el-dropdown + .el-dropdown {
margin-left: 15px;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
<script>
export default {
methods: {
handleClick() {
alert('button click');
}
}
}
</script>
```
:::
### Cómo detonar el evento
Haga clic en el elemento detonante o sobre él.
:::demo Utilice el atributo `trigger`. Por defecto, es `hover`.
```html
<el-row class="block-col-2">
<el-col :span="12">
<span class="demonstration">hover to trigger</span>
<el-dropdown>
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item icon="el-icon-plus">Action 1</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus">Action 2</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus-outline">Action 3</el-dropdown-item>
<el-dropdown-item icon="el-icon-check">Action 4</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-check">Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-col>
<el-col :span="12">
<span class="demonstration">click to trigger</span>
<el-dropdown trigger="click">
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item icon="el-icon-plus">Action 1</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus">Action 2</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-plus-outline">Action 3</el-dropdown-item>
<el-dropdown-item icon="el-icon-check">Action 4</el-dropdown-item>
<el-dropdown-item icon="el-icon-circle-check">Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</el-col>
</el-row>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
.demonstration {
display: block;
color: #8492a6;
font-size: 14px;
margin-bottom: 20px;
}
</style>
```
:::
### Ocultamiento del menú
Use `hide-on-click` para definir si el menú se cierra al hacer clic.
:::demo El menú predeterminado se cerrará cuando haga clic en los elementos del menú, y se puede desactivar configurando `hide-on-click` como false.
```html
<el-dropdown :hide-on-click="false">
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item disabled>Action 4</el-dropdown-item>
<el-dropdown-item divided>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
```
:::
### Evento command
Al hacer clic en cada elemento desplegable se detona un evento cuyo parámetro es asignado por cada elemento.
:::demo
```html
<el-dropdown @command="handleCommand">
<span class="el-dropdown-link">
Dropdown List<i class="el-icon-arrow-down el-icon--right"></i>
</span>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item command="a">Action 1</el-dropdown-item>
<el-dropdown-item command="b">Action 2</el-dropdown-item>
<el-dropdown-item command="c">Action 3</el-dropdown-item>
<el-dropdown-item command="d" disabled>Action 4</el-dropdown-item>
<el-dropdown-item command="e" divided>Action 5</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<style>
.el-dropdown-link {
cursor: pointer;
color: #409EFF;
}
.el-icon-arrow-down {
font-size: 12px;
}
</style>
<script>
export default {
methods: {
handleCommand(command) {
this.$message('click on item ' + command);
}
}
}
</script>
```
:::
### Tamaños
Además del tamaño predeterminado, el componente Dropdown proporciona tres tamaños adicionales para que pueda elegir entre diferentes escenarios
:::demo Utilice el atributo `size` para establecer tamaños adicionales con `medium`, `small` o `mini`.
```html
<el-dropdown split-button type="primary">
Default
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown size="medium" split-button type="primary">
Medium
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown size="small" split-button type="primary">
Small
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<el-dropdown size="mini" split-button type="primary">
Mini
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>Action 1</el-dropdown-item>
<el-dropdown-item>Action 2</el-dropdown-item>
<el-dropdown-item>Action 3</el-dropdown-item>
<el-dropdown-item>Action 4</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
```
:::
### Dropdown atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------- | ---------------------------------------- | ------- | ---------------------------------------- | ----------- |
| type | tipo de botón de menú, consulte Componente`Button`, sólo funciona cuando `split-button` es true. | string | — | — |
| size | tamaño del menú, también funciona en `split-button` | string | medium / small / mini | — |
| split-button | si se visualiza un grupo de botones | boolean | — | false |
| placement | colocación del menú | string | top/top-start/top-end/bottom/bottom-start/bottom-end | bottom-end |
| trigger | cómo detonar | string | hover/click | hover |
| hide-on-click | si se oculta el menú después de hacer clic en el elemento | boolean | — | true |
| show-timeout | Tiempo de retardo antes de mostrar un dropdown (solamente trabaja cuando se dispara `hover`) | number | — | 250 |
| hide-timeout | Tiempo de retardo antes de ocultar un dropdown (solamente trabaja cuando se dispara `hover`) | number | — | 150 |
| tabindex | [tabindex](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex) de Dropdown | number | — | 0 |
### Dropdown Slots
| Nombre | Descripción |
|------|--------|
| — | contenido del Dropdown. Aviso: Debe ser un elemento html dom válido (ej. `<span>, <button>` etc.) o `el-component`, para adjuntar el listener trigger |
| dropdown | contenido del menu Dropdown, normalmente es un elemento `<el-dropdown-menu>` |
### Dropdown Eventos
| Nombre | Descripción | Parámetros |
| -------------- | ------------------------------------------------------------ | ------------------------------------------------ |
| click | si `split-button` es `true`, se activa al hacer clic en el botón izquierdo | — |
| command | activa cuando se hace clic en un elemento desplegable | el comando enviado desde el elemento desplegable |
| visible-change | se activa cuando aparece/desaparece el desplegable | true cuando aparece, y false de otro modo |
### Dropdown Menú Ítem Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ---------------------------------------- | -------------------- | ----------------- | ----------- |
| command | un comando que se enviará al `command` callback del Dropdown | string/number/object | — | — |
| disabled | si el elemento está desactivado | boolean | — | false |
| divided | si se visualiza un divisor | boolean | — | false |
| icon | nombre de la clase del icono | string | — | — |

668
examples/docs/es/form.md Normal file
View File

@@ -0,0 +1,668 @@
## Form
Form consiste en `input`, `radio`, `select`, `checkbox`, etcétera. Con el formulario, usted puede recopilar, verificar y enviar datos.
### Form básico
Incluye todo tipo de entradas, tales como `input`, `select`, `radio` y `checkbox`.
:::demo En cada componente `form`, necesita un campo `form-item` para que sea el contenedor del ítem.
```html
<el-form ref="form" :model="form" label-width="120px">
<el-form-item label="Activity name">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="form.region" placeholder="please select your zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Activity time">
<el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="form.date1" style="width: 100%;"></el-date-picker>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="form.date2" style="width: 100%;"></el-time-picker>
</el-col>
</el-form-item>
<el-form-item label="Instant delivery">
<el-switch v-model="form.delivery"></el-switch>
</el-form-item>
<el-form-item label="Activity type">
<el-checkbox-group v-model="form.type">
<el-checkbox label="Online activities" name="type"></el-checkbox>
<el-checkbox label="Promotion activities" name="type"></el-checkbox>
<el-checkbox label="Offline activities" name="type"></el-checkbox>
<el-checkbox label="Simple brand exposure" name="type"></el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item label="Resources">
<el-radio-group v-model="form.resource">
<el-radio label="Sponsor"></el-radio>
<el-radio label="Venue"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="Activity form">
<el-input type="textarea" v-model="form.desc"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">Create</el-button>
<el-button>Cancel</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
form: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
}
}
},
methods: {
onSubmit() {
console.log('submit!');
}
}
}
</script>
```
:::
:::tip
[W3C](https://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2) reglamenta que
> <i>Cuando sólo hay un campo de entrada de texto de una sola línea en un formulario, el agente usuario debe aceptar <b>Enter</b> en ese campo como una solicitud para enviar el formulario.</i>
Para prevenir este comportamiento, puede agregar `@submit.native.prevent` on `<el-form>`.
:::
### Formulario inline
Cuando el espacio vertical es limitado y la forma es relativamente simple, puede ponerlo en una unica línea.
:::demo Establezca el atributo `inline` como `true` y el formulario sera inline.
```html
<el-form :inline="true" :model="formInline" class="demo-form-inline">
<el-form-item label="Approved by">
<el-input v-model="formInline.user" placeholder="Approved by"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="formInline.region" placeholder="Activity zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">Query</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
formInline: {
user: '',
region: ''
}
}
},
methods: {
onSubmit() {
console.log('submit!');
}
}
}
</script>
```
:::
### Alineamiento
Dependiendo de su diseño, hay varias maneras diferentes de alinear el elemento de la etiqueta.
:::demo El atributo `label-position` decide cómo se alinean las etiquetas, puede estar `top` o `left`. Cuando se establece en `top`, las etiquetas se colocarán en la parte superior del campo de formulario.
```html
<el-radio-group v-model="labelPosition" size="small">
<el-radio-button label="left">Left</el-radio-button>
<el-radio-button label="right">Right</el-radio-button>
<el-radio-button label="top">Top</el-radio-button>
</el-radio-group>
<div style="margin: 20px;"></div>
<el-form :label-position="labelPosition" label-width="100px" :model="formLabelAlign">
<el-form-item label="Name">
<el-input v-model="formLabelAlign.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-input v-model="formLabelAlign.region"></el-input>
</el-form-item>
<el-form-item label="Activity form">
<el-input v-model="formLabelAlign.type"></el-input>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
labelPosition: 'right',
formLabelAlign: {
name: '',
region: '',
type: ''
}
};
}
}
</script>
```
:::
### Validación
El componente `form` le permite verificar sus datos, ayudándole a encontrar y corregir errores.
:::demo Sólo tiene que añadir el atributo `rules` en el componente `Form`, pasar las reglas de validación y establecer el atributo `prop` para `Form-Item` como una clave específica que necesita ser validada. Ver más información en [async-validator](https://github.com/yiminghe/async-validator).
```html
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
<el-form-item label="Activity name" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone" prop="region">
<el-select v-model="ruleForm.region" placeholder="Activity zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Activity time" required>
<el-col :span="11">
<el-form-item prop="date1">
<el-date-picker type="date" placeholder="Pick a date" v-model="ruleForm.date1" style="width: 100%;"></el-date-picker>
</el-form-item>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-form-item prop="date2">
<el-time-picker placeholder="Pick a time" v-model="ruleForm.date2" style="width: 100%;"></el-time-picker>
</el-form-item>
</el-col>
</el-form-item>
<el-form-item label="Instant delivery" prop="delivery">
<el-switch v-model="ruleForm.delivery"></el-switch>
</el-form-item>
<el-form-item label="Activity type" prop="type">
<el-checkbox-group v-model="ruleForm.type">
<el-checkbox label="Online activities" name="type"></el-checkbox>
<el-checkbox label="Promotion activities" name="type"></el-checkbox>
<el-checkbox label="Offline activities" name="type"></el-checkbox>
<el-checkbox label="Simple brand exposure" name="type"></el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item label="Resources" prop="resource">
<el-radio-group v-model="ruleForm.resource">
<el-radio label="Sponsorship"></el-radio>
<el-radio label="Venue"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="Activity form" prop="desc">
<el-input type="textarea" v-model="ruleForm.desc"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">Create</el-button>
<el-button @click="resetForm('ruleForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
ruleForm: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
},
rules: {
name: [
{ required: true, message: 'Please input Activity name', trigger: 'blur' },
{ min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' }
],
region: [
{ required: true, message: 'Please select Activity zone', trigger: 'change' }
],
date1: [
{ type: 'date', required: true, message: 'Please pick a date', trigger: 'change' }
],
date2: [
{ type: 'date', required: true, message: 'Please pick a time', trigger: 'change' }
],
type: [
{ type: 'array', required: true, message: 'Please select at least one activity type', trigger: 'change' }
],
resource: [
{ required: true, message: 'Please select activity resource', trigger: 'change' }
],
desc: [
{ required: true, message: 'Please input activity form', trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
```
:::
### Reglas personalizadas de validación
Este ejemplo muestra cómo personalizar sus propias reglas de validación para finalizar una verificación de contraseña de dos pasos.
:::demo Aquí utilizamos el `status-icon` para reflejar el resultado de la validación como un icono.
```html
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
<el-form-item label="Password" prop="pass">
<el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Confirm" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="Age" prop="age">
<el-input v-model.number="ruleForm.age"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">Submit</el-button>
<el-button @click="resetForm('ruleForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
var checkAge = (rule, value, callback) => {
if (!value) {
return callback(new Error('Please input the age'));
}
setTimeout(() => {
if (!Number.isInteger(value)) {
callback(new Error('Please input digits'));
} else {
if (value < 18) {
callback(new Error('Age must be greater than 18'));
} else {
callback();
}
}
}, 1000);
};
var validatePass = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password'));
} else {
if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass');
}
callback();
}
};
var validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('Please input the password again'));
} else if (value !== this.ruleForm.pass) {
callback(new Error('Two inputs don\'t match!'));
} else {
callback();
}
};
return {
ruleForm: {
pass: '',
checkPass: '',
age: ''
},
rules: {
pass: [
{ validator: validatePass, trigger: 'blur' }
],
checkPass: [
{ validator: validatePass2, trigger: 'blur' }
],
age: [
{ validator: checkAge, trigger: 'blur' }
]
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
```
:::
:::tip
Se debe llamar a la función de validación de llamada de retorno personalizada. Ver uso más avanzado en [async-validator](https://github.com/yiminghe/async-validator).
:::
### Eliminar o agregar validaciones dinámicamente
:::demo Además de pasar todas las reglas de validación al mismo tiempo en el componente `form`, también puede pasar las reglas de validación o borrar reglas en un único campo de formulario de forma dinámica.
```html
<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="120px" class="demo-dynamic">
<el-form-item
prop="email"
label="Email"
:rules="[
{ required: true, message: 'Please input email address', trigger: 'blur' },
{ type: 'email', message: 'Please input correct email address', trigger: ['blur', 'change'] }
]"
>
<el-input v-model="dynamicValidateForm.email"></el-input>
</el-form-item>
<el-form-item
v-for="(domain, index) in dynamicValidateForm.domains"
:label="'Domain' + index"
:key="domain.key"
:prop="'domains.' + index + '.value'"
:rules="{
required: true, message: 'domain can not be null', trigger: 'blur'
}"
>
<el-input v-model="domain.value"></el-input><el-button @click.prevent="removeDomain(domain)">Delete</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('dynamicValidateForm')">Submit</el-button>
<el-button @click="addDomain">New domain</el-button>
<el-button @click="resetForm('dynamicValidateForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
dynamicValidateForm: {
domains: [{
key: 1,
value: ''
}],
email: ''
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
},
removeDomain(item) {
var index = this.dynamicValidateForm.domains.indexOf(item);
if (index !== -1) {
this.dynamicValidateForm.domains.splice(index, 1);
}
},
addDomain() {
this.dynamicValidateForm.domains.push({
key: Date.now(),
value: ''
});
}
}
}
</script>
```
:::
### Validación numérica
:::demo La validación numérica necesita un modificador `.number` añadido en el enlace `v-model` de entrada, sirve para transformar el valor de la cadena al número proporcionado por Vuejs.
```html
<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
<el-form-item
label="age"
prop="age"
:rules="[
{ required: true, message: 'age is required'},
{ type: 'number', message: 'age must be a number'}
]"
>
<el-input type="age" v-model.number="numberValidateForm.age" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('numberValidateForm')">Submit</el-button>
<el-button @click="resetForm('numberValidateForm')">Reset</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
numberValidateForm: {
age: ''
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
```
:::
:::tip
Cuando un `el-form-item` está anidado en otro `el-form-item`, su ancho de etiqueta será 0. Si es necesario, puede establecer el ancho de etiqueta en ese `el-form-item`.
:::
### Tamaño del control
Todos los componentes de un formulario heredan su atributo `size`. De manera similar, FormItem también tiene un atributo `size`.
:::demo Aún así, puede ajustar el `size` de cada componente si no desea que herede su tamaño de From o FormItem.
```html
<el-form ref="form" :model="sizeForm" label-width="120px" size="mini">
<el-form-item label="Activity name">
<el-input v-model="sizeForm.name"></el-input>
</el-form-item>
<el-form-item label="Activity zone">
<el-select v-model="sizeForm.region" placeholder="please select your zone">
<el-option label="Zone one" value="shanghai"></el-option>
<el-option label="Zone two" value="beijing"></el-option>
</el-select>
</el-form-item>
<el-form-item label="Activity time">
<el-col :span="11">
<el-date-picker type="date" placeholder="Pick a date" v-model="sizeForm.date1" style="width: 100%;"></el-date-picker>
</el-col>
<el-col class="line" :span="2">-</el-col>
<el-col :span="11">
<el-time-picker placeholder="Pick a time" v-model="sizeForm.date2" style="width: 100%;"></el-time-picker>
</el-col>
</el-form-item>
<el-form-item label="Activity type">
<el-checkbox-group v-model="sizeForm.type">
<el-checkbox-button label="Online activities" name="type"></el-checkbox-button>
<el-checkbox-button label="Promotion activities" name="type"></el-checkbox-button>
</el-checkbox-group>
</el-form-item>
<el-form-item label="Resources">
<el-radio-group v-model="sizeForm.resource" size="medium">
<el-radio border label="Sponsor"></el-radio>
<el-radio border label="Venue"></el-radio>
</el-radio-group>
</el-form-item>
<el-form-item size="large">
<el-button type="primary" @click="onSubmit">Create</el-button>
<el-button>Cancel</el-button>
</el-form-item>
</el-form>
<script>
export default {
data() {
return {
sizeForm: {
name: '',
region: '',
date1: '',
date2: '',
delivery: false,
type: [],
resource: '',
desc: ''
}
};
},
methods: {
onSubmit() {
console.log('submit!');
}
}
};
</script>
```
:::
### Form Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------------- | ---------------------------------------- | ------- | --------------------- | ----------- |
| model | Datos del componente | object | — | — |
| rules | Reglas de validación | object | — | — |
| inline | Si el form es inline | boolean | — | false |
| label-position | Posición de la etiqueta | string | left / right / top | right |
| label-width | anchura de la etiqueta, por ejemplo, "50px". Todos sus elementos de formulario hijo directo heredarán este valor. El valor `auto` está soportado. | string | — | — |
| label-suffix | sufijo de la etiqueta | string | — | — |
| hide-required-asterisk | si los campos obligatorios deben tener un asterisco rojo (estrella) al lado de sus etiquetas | boolean | — | false |
| show-message | si mostrar o no el mensaje de error | boolean | — | true |
| inline-message | si desea visualizar el mensaje de error inline con la posición del form item | boolean | — | false |
| status-icon | si desea visualizar un icono que indique el resultado de la validación | boolean | — | false |
| validate-on-rule-change | si se dispara la validación cuando el prop `rules` cambia | boolean | — | true |
| size | el tamaño de los componentes en este form | string | medium / small / mini | — |
| disabled | si se desactivan todos los componentes del formulario. Si esta en `true` no puede ser cambiado por el prop `disabled` individual de los componentes. | boolean | — | false |
### Form Métodos
| Método | Descripción | Parámetros |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| validate | el método para validar todo el formulario. Recibe una llamada como parámetro. Después de la validación, la llamada de retorno se ejecutará con dos parámetros: un booleano que indica si la validación ha pasado, y un objeto que contiene todos los campos que fallaron en la validación. Devuelve una promesa si se omite el return | Function(callback: Function(boolean, object)) |
| validateField | validar uno o varios elementos de formulario | Function(props: string \| array, callback: Function(errorMessage: string)) |
| resetFields | restablece todos los campos y elimina el resultado de validación | — |
| clearValidate | borra el mensaje de validación para determinados campos. El parámetro es un prop name o un array de props names de los items del formulario cuyos mensajes de validación se eliminarán. Si se omiten, se borrarán todos los mensajes de validación de los campos. | Function(props: string \| array) |
### Eventos Form
| Nombre | Descripción | Parámetros |
| -------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| validate | se dispara después de validar un ítem del formulario | la propiedad (`prop name`) nombre del ítem del form que se esta validando, si la validación paso o no, y el mensaje de error si existe. |
### Form-Item Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ------------------------------------------------------------ | ------- | ------------------------------------------- | ----------- |
| prop | un clave del modelo. En el uso del método `validate` y `resetFields`, el atributo es obligatorio. | string | Clave del modelo que se ha pasado a `form` | |
| label | etiqueta | string | — | — |
| label-width | ancho de la etiqueta, Ejemplo: '50px'. El valor `auto` esta soportado | string | — | — |
| required | si el campo es obligatorio o no, estará determinado por las reglas de validación si se omite. | boolean | — | false |
| rules | reglas de validación del form | object | — | — |
| error | mensaje de error de campo, establezca su valor y el campo validará el error y mostrará este mensaje inmediatamente. | string | — | — |
| show-message | si mostrar o no el mensaje de error | boolean | — | true |
| inline-message | mensaje de validación estilo inline | boolean | — | false |
| size | Tamaño de los componentes en este form item | string | medium / small / mini | - |
### Form-Item Slot
| Nombre | Descripción |
| ------ | ------------------------ |
| — | contenido del Form Item |
| label | contenido de la etiqueta |
### Form-Item Scoped Slot
| Name | Description |
| ----- | ------------------------------------------------------------ |
| error | Contenido personalizado para mostrar el mensaje de validación. El parámetro del scope es { error } |
### Form-Item Método
| Método | Descripción | Parámetros |
| ------------- | ----------------------------------------------------------- | ---------- |
| resetField | restablecer campo actual y eliminar resultado de validación | — |
| clearValidate | elimina el estado de la validación de un campo | - |

226
examples/docs/es/i18n.md Normal file
View File

@@ -0,0 +1,226 @@
## Internacionalización
El idioma predeterminado de Element es el chino. Si se desea utilizar otro idioma, será necesario realizar alguna configuración de i18n. En su fichero de entrada, si está importando Element por completo:
```javascript
import Vue from 'vue'
import ElementUI from 'element-ui'
import locale from 'element-ui/lib/locale/lang/en'
Vue.use(ElementUI, { locale })
```
O si está importando Element a petición:
```javascript
import Vue from 'vue'
import { Button, Select } from 'element-ui'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'
// configure language
locale.use(lang)
// import components
Vue.component(Button.name, Button)
Vue.component(Select.name, Select)
```
El paquete de idioma chino se importa por defecto, incluso si se esta usando otro idioma. Pero con `NormalModuleReplacementPlugin` proporcionado por el webpack puede reemplazar la localización predeterminada:
webpack.config.js
```javascript
{
plugins: [
new webpack.NormalModuleReplacementPlugin(/element-ui[\/\\]lib[\/\\]locale[\/\\]lang[\/\\]zh-CN/, 'element-ui/lib/locale/lang/en')
]
}
```
## Compatible con `vue-i18n@5.x`
Element es compatible con [vue-i18n@5.x](https://github.com/kazupon/vue-i18n), lo que facilita aún más la conmutación multilenguaje.
```javascript
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Element from 'element-ui'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
Vue.use(Element)
Vue.config.lang = 'zh-cn'
Vue.locale('zh-cn', zhLocale)
Vue.locale('en', enLocale)
```
## Compatible con otros plugins i18n
Es posible que Element no sea compatible con otros plugins i18n que no sean vue-i18n, pero puede personalizar la forma en que Element procesa i18n.
```javascript
import Vue from 'vue'
import Element from 'element-ui'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(Element, {
i18n: function (path, options) {
// ...
}
})
```
## Compatible con `vue-i18n@6.x`
Necesita manejarlo manualmente para ser compatible con `6.x`.
```javascript
import Vue from 'vue'
import Element from 'element-ui'
import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
Vue.use(VueI18n)
const messages = {
en: {
message: 'hello',
...enLocale // Or use `Object.assign({ message: 'hello' }, enLocale)`
},
zh: {
message: '你好',
...zhLocale // Or use `Object.assign({ message: '你好' }, zhLocale)`
}
}
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: 'en', // set locale
messages, // set locale messages
})
Vue.use(Element, {
i18n: (key, value) => i18n.t(key, value)
})
new Vue({ i18n }).$mount('#app')
```
## Personalización de i18n en componentes bajo petición
```js
import Vue from 'vue'
import DatePicker from 'element/lib/date-picker'
import VueI18n from 'vue-i18n'
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import ElementLocale from 'element-ui/lib/locale'
Vue.use(VueI18n)
Vue.use(DatePicker)
const messages = {
en: {
message: 'hello',
...enLocale
},
zh: {
message: '你好',
...zhLocale
}
}
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: 'en', // set locale
messages, // set locale messages
})
ElementLocale.i18n((key, value) => i18n.t(key, value))
```
## Importar via CDN
```html
<script src="//unpkg.com/vue"></script>
<script src="//unpkg.com/element-ui"></script>
<script src="//unpkg.com/element-ui/lib/umd/locale/en.js"></script>
<script>
ELEMENT.locale(ELEMENT.lang.en)
</script>
```
Compatible con `vue-i18n`
```html
<script src="//unpkg.com/vue"></script>
<script src="//unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
<script src="//unpkg.com/element-ui"></script>
<script src="//unpkg.com/element-ui/lib/umd/locale/zh-CN.js"></script>
<script src="//unpkg.com/element-ui/lib/umd/locale/en.js"></script>
<script>
Vue.locale('en', ELEMENT.lang.en)
Vue.locale('zh-cn', ELEMENT.lang.zhCN)
</script>
```
Actualmente Element está disponible en los siguientes idiomas:
<ul class="language-list">
<li>Simplified Chinese (zh-CN)</li>
<li>English (en)</li>
<li>German (de)</li>
<li>Portuguese (pt)</li>
<li>Spanish (es)</li>
<li>Danish (da)</li>
<li>French (fr)</li>
<li>Norwegian (nb-NO)</li>
<li>Traditional Chinese (zh-TW)</li>
<li>Italian (it)</li>
<li>Korean (ko)</li>
<li>Japanese (ja)</li>
<li>Dutch (nl)</li>
<li>Vietnamese (vi)</li>
<li>Russian (ru-RU)</li>
<li>Turkish (tr-TR)</li>
<li>Brazilian Portuguese (pt-br)</li>
<li>Farsi (fa)</li>
<li>Thai (th)</li>
<li>Indonesian (id)</li>
<li>Bulgarian (bg)</li>
<li>Polish (pl)</li>
<li>Finnish (fi)</li>
<li>Swedish (sv-SE)</li>
<li>Greek (el)</li>
<li>Slovak (sk)</li>
<li>Catalunya (ca)</li>
<li>Czech (cs-CZ)</li>
<li>Ukrainian (ua)</li>
<li>Turkmen (tk)</li>
<li>Tamil (ta)</li>
<li>Latvian (lv)</li>
<li>Afrikaans (af-ZA)</li>
<li>Estonian (ee)</li>
<li>Slovenian (sl)</li>
<li>Arabic (ar)</li>
<li>Hebrew (he)</li>
<li>Lithuanian (lt)</li>
<li>Mongolian (mn)</li>
<li>Kazakh (kz)</li>
<li>Hungarian (hu)</li>
<li>Romanian (ro)</li>
<li>Kurdish (ku)</li>
<li>Uighur (ug-CN)</li>
<li>Khmer (km)</li>
<li>Serbian (sr)</li>
<li>Vasco (eu)</li>
<li>Kirguizstán (kg)</li>
<li>Armenio (hy)</li>
<li>Croatian (hr)</li>
<li>Esperanto (eo)</li>
</ul>
Si su idioma de destino no está incluido, puede contribuir: simplemente añada [aqui](https://github.com/ElemeFE/element/tree/dev/src/locale/lang) otra configuración de idioma y cree un pull request.

29
examples/docs/es/icon.md Normal file
View File

@@ -0,0 +1,29 @@
## Icon
Element proporciona un conjunto de iconos propios.
### Uso básico
Simplemente asigna el nombre de la clase a `el-icon-iconName`.
:::demo
```html
<i class="el-icon-edit"></i>
<i class="el-icon-share"></i>
<i class="el-icon-delete"></i>
<el-button type="primary" icon="el-icon-search">Search</el-button>
```
:::
### Iconos
<ul class="icon-list">
<li v-for="name in $icon" :key="name">
<span>
<i :class="'el-icon-' + name"></i>
<span class="icon-name">{{'el-icon-' + name}}</span>
</span>
</li>
</ul>

165
examples/docs/es/image.md Normal file
View File

@@ -0,0 +1,165 @@
## Image
Además de las características nativas de img, soporte de carga perezosa, marcador de posición personalizado y fallo de carga, etc.
### Uso básico
:::demo Indica cómo se debe cambiar el tamaño de la imagen para que se ajuste a su contenedor por ajuste, igual que el ajuste de objeto nativo. [object-fit](https://developer.mozilla.org/es/docs/Web/CSS/object-fit)。
```html
<div class="demo-image">
<div class="block" v-for="fit in fits" :key="fit">
<span class="demonstration">{{ fit }}</span>
<el-image
style="width: 100px; height: 100px"
:src="url"
:fit="fit"></el-image>
</div>
</div>
<script>
export default {
data() {
return {
fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
}
}
}
</script>
```
:::
### Placeholder
:::demo Personalice el placeholder del contenido mientras la imagen aun no ha sido cargada vía `slot = placeholder`
```html
<div class="demo-image__placeholder">
<div class="block">
<span class="demonstration">Default</span>
<el-image :src="src"></el-image>
</div>
<div class="block">
<span class="demonstration">Custom</span>
<el-image :src="src">
<div slot="placeholder" class="image-slot">
Loading<span class="dot">...</span>
</div>
</el-image>
</div>
</div>
<script>
export default {
data() {
return {
src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg'
}
}
}
</script>
```
:::
### Fallo de carga
:::demo Personalice el contenido cuando ocurra algún error al cargar la imagen vía `slot = error`
```html
<div class="demo-image__error">
<div class="block">
<span class="demonstration">Default</span>
<el-image></el-image>
</div>
<div class="block">
<span class="demonstration">Custom</span>
<el-image>
<div slot="error" class="image-slot">
<i class="el-icon-picture-outline"></i>
</div>
</el-image>
</div>
</div>
```
:::
### Lazy Load
:::demo Use lazy load vía `lazy = true`. La imagen se cargará hasta que se desplace a la vista cuando esté configurada. Puede indicar el contenedor de scroll que añade el oyente de scroll vía `scroll-container`. Si no está definido, será el contenedor padre más cercano cuya propiedad overflow es auto o scroll.
```html
<div class="demo-image__lazy">
<el-image v-for="url in urls" :key="url" :src="url" lazy></el-image>
</div>
<script>
export default {
data() {
return {
urls: [
'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg',
'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg',
'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9583jpeg.jpeg',
'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg',
'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg',
'https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg',
'https://fuss10.elemecdn.com/2/11/6535bcfb26e4c79b48ddde44f4b6fjpeg.jpeg'
]
}
}
}
</script>
```
:::
### Vista previa de la imagen
:::demo permitir una vista previa grande de la imagen configurando la prop `previewSrcList`.
```html
<div class="demo-image__preview">
<el-image
style="width: 100px; height: 100px"
:src="url"
:preview-src-list="srcList">
</el-image>
</div>
<script>
export default {
data() {
return {
url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
srcList: [
'https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg',
'https://fuss10.elemecdn.com/1/8e/aeffeb4de74e2fde4bd74fc7b4486jpeg.jpeg'
]
}
}
}
</script>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------- |---------- |------------- |-------- |
| src | origen de la imagen, igual que en nativo | string | — | - |
| fit | Indica como la imagen debe adaptarse al contenedor, lo mismo que [object-fit](https://developer.mozilla.org/es/docs/Web/CSS/object-fit) | string | fill / contain / cover / none / scale-down | - |
| alt | alt nativo | string | - | - |
| referrer-policy | referrerPolicy nativo | string | - | - |
| lazy | si se usara lazy load | boolean | — | false |
| scroll-container | El contenedor para añadir el scroll listener cuando se utiliza lazy load | string / HTMLElement | — | El contenedor padre más cercano cuya propiedad de desbordamiento es auto o scroll |
| preview-src-list | permitir una vista previa grande de la imagen | Array | — | - |
| z-index | establecer el z-index de la vista previa de la imagen | Number | — | 2000 |
### Eventos
| Nombre del evento | Descripción | Parámetros |
|---------- |-------- |---------- |
| load | Igual que el load nativo | (e: Event) |
| error | Igual que el error nativo | (e: Error) |
### Slots
| Nombre del slot | Descripción |
|---------|-------------|
| placeholder | Se activa cuando la imagen se carga |
| error | Se activa cuando la carga de la imagen falla |

View File

@@ -0,0 +1,88 @@
## InfiniteScroll
Cargar más datos mientras se llega al final de la página
### Uso básico
Añada `v-infinite-scroll` a la lista para ejecutar automáticamente el método de carga cuando se desplace hacia abajo.
:::demo
```html
<template>
<ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto">
<li v-for="i in count" class="infinite-list-item">{{ i }}</li>
</ul>
</template>
<script>
export default {
data () {
return {
count: 0
}
},
methods: {
load () {
this.count += 2
}
}
}
</script>
```
:::
### Deshabilite Loading
:::demo
```html
<template>
<div class="infinite-list-wrapper" style="overflow:auto">
<ul
class="list"
v-infinite-scroll="load"
infinite-scroll-disabled="disabled">
<li v-for="i in count" class="list-item">{{ i }}</li>
</ul>
<p v-if="loading">Loading...</p>
<p v-if="noMore">No more</p>
</div>
</template>
<script>
export default {
data () {
return {
count: 10,
loading: false
}
},
computed: {
noMore () {
return this.count >= 20
},
disabled () {
return this.loading || this.noMore
}
},
methods: {
load () {
this.loading = true
setTimeout(() => {
this.count += 2
this.loading = false
}, 2000)
}
}
}
</script>
```
:::
### Atributos
| Atributos | Descripción | Tipo | Valores aceptados | Por defecto |
| -------------- | ------------------------------ | --------- | ------------------------------------ | ------- |
| infinite-scroll-disabled | si esta disabled | boolean | - |false |
| infinite-scroll-delay | retraso en mili segundos | number | - |200 |
| infinite-scroll-distance| distancia de activación (px) | number |- |0 |
| infinite-scroll-immediate |Si se debe ejecutar el método de carga inmediatamente, en caso de que el contenido no se pueda rellenar en el estado inicial. | boolean | - |true |

View File

@@ -0,0 +1,202 @@
## InputNumber
Input de valores numéricos con un rango personalizable.
### Uso básico
:::demo Vincule una variable con `v-model` en el elemento `<el-input-number>` y estará listo.
```html
<template>
<el-input-number v-model="num" @change="handleChange" :min="1" :max="10"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
};
},
methods: {
handleChange(value) {
console.log(value)
}
}
};
</script>
```
:::
### Disabled
:::demo El atributo `disabled` acepta un valor `boolean`, y si el valor es `true`, el componente queda deshabilitado. Si sólo necesita controlar el valor dentro de un rango, puede añadir un atributo `min` para establecer el valor mínimo y un valor `max` para establecer el valor máximo. Por defecto, el valor mínimo es `0`.
```html
<template>
<el-input-number v-model="num" :disabled="true"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
}
}
};
</script>
```
:::
### Steps
Le permite definir el nivel de incremento de los saltos.
:::demo Añada el atributo `step` para establecer el salto.
```html
<template>
<el-input-number v-model="num" :step="2"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 5
}
}
};
</script>
```
:::
### Step estrictamente
:::demo El atributo `step-strictly` acepta `boolean`. Si este atributo es `true`, el valor de entrada sólo puede ser múltiplo de step.
```html
<template>
<el-input-number v-model="num" :step="2" step-strictly></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 2
}
}
};
</script>
```
:::
### Precisión
:::demo El atributo `precision` aplica presición al valor del value.
```html
<template>
<el-input-number v-model="num" :precision="2" :step="0.1" :max="10"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
}
}
};
</script>
```
:::
:::tip
El valor de `precision` debe ser un numero entero positivo que no debe ser inferior a los decimales del `step`.
:::
### Tamaño
Utilice el atributo `size` para establecer tamaños adicionales con `medium`, `small` o `mini`.
:::demo
```html
<template>
<el-input-number v-model="num1"></el-input-number>
<el-input-number size="medium" v-model="num2"></el-input-number>
<el-input-number size="small" v-model="num3"></el-input-number>
<el-input-number size="mini" v-model="num4"></el-input-number>
</template>
<script>
export default {
data() {
return {
num1: 1,
num2: 1,
num3: 1,
num4: 1
}
}
};
</script>
```
:::
### Posición de los controles
:::demo Establezca `controls-position` para decidir la posición de los botones de control.
```html
<template>
<el-input-number v-model="num" controls-position="right" @change="handleChange" :min="1" :max="10"></el-input-number>
</template>
<script>
export default {
data() {
return {
num: 1
};
},
methods: {
handleChange(value) {
console.log(value);
}
}
};
</script>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------- | ---------------------------------------- | ------- | ----------------- | ----------- |
| value / v-model | valor vinculado | number | — | 0 |
| min | el valor mínimo permitido | number | — | `-Infinity` |
| max | el valor máximo permitido | number | — | `Infinity` |
| step | incremento (salto) | number | — | 1 |
| step-strictly | si el valor del input puede ser solo un múltiplo de step | boolean | — | false |
| precision | precisión del valor del input | number | — | — |
| size | tamaño del componente | string | large/small | — |
| disabled | si el componente esta deshabilitado | boolean | — | false |
| controls | si se activan los botones de control | boolean | — | true |
| controls-position | posición de los botones de control | string | right | - |
| name | lo mismo que `name` en un input nativo | string | — | — |
| label | texto de la etiqueta | string | — | — |
| placeholder | placeholder en el input | string | - | - |
### Eventos
| Nombre | Descripción | Parámetros |
| ------ | ---------------------------------------- | ------------------ |
| change | se produce cuando el valor cambia | currentValue, oldValue |
| blur | se produce cuando el componente pierde el foco | (event: Event) |
| focus | se produce cuando el componente obtiene el foco | (event: Event) |
### Métodos
| Método | Descripción | Parámetro |
| ------ | ------------------------------------ | --------- |
| focus | coloca el foco en el elemento actual | - |
| select | selecciona el contenido del input | - |

683
examples/docs/es/input.md Normal file
View File

@@ -0,0 +1,683 @@
## Input
Ingresa datos usando el ratón o teclado.
:::warning
Input es un componente controlado, **siempre muestra el valor de enlace Vue**.
Bajo circunstancias normales, el evento "input" debe ser manejado. Su handler debe actualizar el valor de enlace del componente (o usar `v-model`). De lo contrario, el valor del cuadro de entrada no cambiará.
No admite modificadores `v-model`.
:::
### Uso básico
:::demo
```html
<el-input placeholder="Please input" v-model="input"></el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Disabled
:::demo Deshabilite el Input con el atributo `disabled`.
```html
<el-input
placeholder="Please input"
v-model="input"
:disabled="true">
</el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Limpiable
:::demo Marque que el input puede ser limpiable con el atributo `clearable`.
```html
<el-input
placeholder="Please input"
v-model="input"
clearable>
</el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Password box
:::demo Haga un input de contraseña conmutable con el atributo `show-password`.
```html
<el-input placeholder="Please input password" v-model="input" show-password></el-input>
<script>
export default {
data() {
return {
input: ''
}
}
}
</script>
```
:::
### Input con icono
Añada un icono para indicar el tipo de Input.
:::demo Para añadir iconos en el Input, puede utilizar los atributos `prefix-icon` y `suffix-icon` . Además, los slots con nombre `prefix` y `suffix` también funcionan.
```html
<div class="demo-input-suffix">
<span class="demo-input-label">Using attributes</span>
<el-input
placeholder="Pick a date"
suffix-icon="el-icon-date"
v-model="input1">
</el-input>
<el-input
placeholder="Type something"
prefix-icon="el-icon-search"
v-model="input2">
</el-input>
</div>
<div class="demo-input-suffix">
<span class="demo-input-label">Using slots</span>
<el-input
placeholder="Pick a date"
v-model="input3">
<i slot="suffix" class="el-input__icon el-icon-date"></i>
</el-input>
<el-input
placeholder="Type something"
v-model="input4">
<i slot="prefix" class="el-input__icon el-icon-search"></i>
</el-input>
</div>
<style>
.demo-input-label {
display: inline-block;
width: 130px;
}
</style>
<script>
export default {
data() {
return {
input1: '',
input2: '',
input3: '',
input4: ''
}
}
}
</script>
```
:::
### Textarea
Re dimensiona para introducir varias líneas de información de texto. Agregue el atributo `type="textarea"` para cambiar el `input` al tipo nativo `textarea`.
:::demo Controle la altura ajustando el prop `rows`.
```html
<el-input
type="textarea"
:rows="2"
placeholder="Please input"
v-model="textarea">
</el-input>
<script>
export default {
data() {
return {
textarea: ''
}
}
}
</script>
```
:::
### Textarea tamaño automático
El ajuste del prop `autosize` en el tipo de Input textarea hace que la altura se ajuste automáticamente en función del contenido. Se puede proporcionar opciones en un objeto para auto dimensionar y especificar el número mínimo y máximo de líneas que el textarea puede ajustar automáticamente.
:::demo
```html
<el-input
type="textarea"
autosize
placeholder="Please input"
v-model="textarea1">
</el-input>
<div style="margin: 20px 0;"></div>
<el-input
type="textarea"
:autosize="{ minRows: 2, maxRows: 4}"
placeholder="Please input"
v-model="textarea2">
</el-input>
<script>
export default {
data() {
return {
textarea1: '',
textarea2: ''
}
}
}
</script>
```
:::
### Mezclando elementos con input
Añade un elemento antes o después del input, generalmente una etiqueta o un botón.
:::demo Utilice el `slot` para seleccionar si el elemento se colocara antes (prepend) o después (append) del Input.
```html
<div>
<el-input placeholder="Please input" v-model="input1">
<template slot="prepend">Http://</template>
</el-input>
</div>
<div style="margin-top: 15px;">
<el-input placeholder="Please input" v-model="input2">
<template slot="append">.com</template>
</el-input>
</div>
<div style="margin-top: 15px;">
<el-input placeholder="Please input" v-model="input3" class="input-with-select">
<el-select v-model="select" slot="prepend" placeholder="Select">
<el-option label="Restaurant" value="1"></el-option>
<el-option label="Order No." value="2"></el-option>
<el-option label="Tel" value="3"></el-option>
</el-select>
<el-button slot="append" icon="el-icon-search"></el-button>
</el-input>
</div>
<style>
.el-select .el-input {
width: 110px;
}
.input-with-select .el-input-group__prepend {
background-color: #fff;
}
</style>
<script>
export default {
data() {
return {
input1: '',
input2: '',
input3: '',
select: ''
}
}
}
</script>
```
:::
### Tamaño
:::demo Añada el atributo `size` para cambiar el tamaño del Input. Además del tamaño predeterminado, hay otras tres opciones: `large`, `small` y `mini`.
```html
<div class="demo-input-size">
<el-input
placeholder="Please Input"
v-model="input1">
</el-input>
<el-input
size="medium"
placeholder="Please Input"
v-model="input2">
</el-input>
<el-input
size="small"
placeholder="Please Input"
v-model="input3">
</el-input>
<el-input
size="mini"
placeholder="Please Input"
v-model="input4">
</el-input>
</div>
<script>
export default {
data() {
return {
input1: '',
input2: '',
input3: '',
input4: ''
}
}
}
</script>
```
:::
### Autocompletado
Puede obtener algunas sugerencias basadas en la entrada actual.
:::demo El componente Autocomplete proporciona sugerencias de entrada. El atributo `fetch-suggestions` es un método que devuelve la entrada sugerida. En este ejemplo, `querySearch(queryString, cb)` devuelve las sugerencias al componente mediante `cb(data)` cuando están listas.
```html
<el-row class="demo-autocomplete">
<el-col :span="12">
<div class="sub-title">list suggestions when activated</div>
<el-autocomplete
class="inline-input"
v-model="state1"
:fetch-suggestions="querySearch"
placeholder="Please Input"
@select="handleSelect"
></el-autocomplete>
</el-col>
<el-col :span="12">
<div class="sub-title">list suggestions on input</div>
<el-autocomplete
class="inline-input"
v-model="state2"
:fetch-suggestions="querySearch"
placeholder="Please Input"
:trigger-on-focus="false"
@select="handleSelect"
></el-autocomplete>
</el-col>
</el-row>
<script>
export default {
data() {
return {
links: [],
state1: '',
state2: ''
};
},
methods: {
querySearch(queryString, cb) {
var links = this.links;
var results = queryString ? links.filter(this.createFilter(queryString)) : links;
// call callback function to return suggestions
cb(results);
},
createFilter(queryString) {
return (link) => {
return (link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
};
},
loadAll() {
return [
{ "value": "vue", "link": "https://github.com/vuejs/vue" },
{ "value": "element", "link": "https://github.com/ElemeFE/element" },
{ "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
{ "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
{ "value": "vuex", "link": "https://github.com/vuejs/vuex" },
{ "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
{ "value": "babel", "link": "https://github.com/babel/babel" }
];
},
handleSelect(item) {
console.log(item);
}
},
mounted() {
this.links = this.loadAll();
}
}
</script>
```
:::
### Template personalizado
Personalice cómo se muestran las sugerencias.
:::demo Utilice `scoped slot` para personalizar los elementos de sugerencias. En el scope, puede acceder al objeto de sugerencia mediante la clave `item`.
```html
<el-autocomplete
popper-class="my-autocomplete"
v-model="state"
:fetch-suggestions="querySearch"
placeholder="Please input"
@select="handleSelect">
<i
class="el-icon-edit el-input__icon"
slot="suffix"
@click="handleIconClick">
</i>
<template slot-scope="{ item }">
<div class="value">{{ item.value }}</div>
<span class="link">{{ item.link }}</span>
</template>
</el-autocomplete>
<style>
.my-autocomplete {
li {
line-height: normal;
padding: 7px;
.value {
text-overflow: ellipsis;
overflow: hidden;
}
.link {
font-size: 12px;
color: #b4b4b4;
}
}
}
</style>
<script>
export default {
data() {
return {
links: [],
state: ''
};
},
methods: {
querySearch(queryString, cb) {
var links = this.links;
var results = queryString ? links.filter(this.createFilter(queryString)) : links;
// call callback function to return suggestion objects
cb(results);
},
createFilter(queryString) {
return (link) => {
return (link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
};
},
loadAll() {
return [
{ "value": "vue", "link": "https://github.com/vuejs/vue" },
{ "value": "element", "link": "https://github.com/ElemeFE/element" },
{ "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
{ "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
{ "value": "vuex", "link": "https://github.com/vuejs/vuex" },
{ "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
{ "value": "babel", "link": "https://github.com/babel/babel" }
];
},
handleSelect(item) {
console.log(item);
},
handleIconClick(ev) {
console.log(ev);
}
},
mounted() {
this.links = this.loadAll();
}
}
</script>
```
:::
### Búsqueda remota
Búsqueda de datos desde el servidor.
:::demo
```html
<el-autocomplete
v-model="state"
:fetch-suggestions="querySearchAsync"
placeholder="Please input"
@select="handleSelect"
></el-autocomplete>
<script>
export default {
data() {
return {
links: [],
state: '',
timeout: null
};
},
methods: {
loadAll() {
return [
{ "value": "vue", "link": "https://github.com/vuejs/vue" },
{ "value": "element", "link": "https://github.com/ElemeFE/element" },
{ "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
{ "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
{ "value": "vuex", "link": "https://github.com/vuejs/vuex" },
{ "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
{ "value": "babel", "link": "https://github.com/babel/babel" }
];
},
querySearchAsync(queryString, cb) {
var links = this.links;
var results = queryString ? links.filter(this.createFilter(queryString)) : links;
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
cb(results);
}, 3000 * Math.random());
},
createFilter(queryString) {
return (link) => {
return (link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
};
},
handleSelect(item) {
console.log(item);
}
},
mounted() {
this.links = this.loadAll();
}
};
</script>
```
:::
### Limitar el tamaño
:::demo `maxlength` y `minlength` son atributos de la entrada nativa, declaran un límite en el número de caracteres que un usuario puede introducir. La configuración de la pro `maxlength` para un tipo de entrada de texto o de área de texto puede limitar la longitud del valor de entrada y le permite mostrar el recuento de palabras al establecer `show-word-limit` a `true` al mismo tiempo.
```html
<el-input
type="text"
placeholder="Please input"
v-model="text"
maxlength="10"
show-word-limit
>
</el-input>
<div style="margin: 20px 0;"></div>
<el-input
type="textarea"
placeholder="Please input"
v-model="textarea"
maxlength="30"
show-word-limit
>
</el-input>
<script>
export default {
data() {
return {
text: '',
textarea: ''
}
}
}
</script>
```
:::
### Input atributos
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| type | tipo de input | string | text, textarea y otros [tipos de entrada nativos](https://developer.mozilla.org/es/docs/Web/HTML/Elemento/input#Form_%3Cinput%3E_types) | text |
| value / v-model | valor enlazado | boolean / string / number | — | — |
| maxlength | igual que `maxlength` en el input nativo | number | — | — |
| minlength | igual que `minlength` en el input nativo | number | — | — |
| show-word-limit | Si se muestra el contador de palabras, solamente funciona con los tipos `text` o `textarea` | boolean | — | false |
| placeholder | placeholder del Input | string | — | — |
| clearable | si debe mostrar el botón de limpieza | boolean | — | false |
| show-password | si debe mostrar la posibilidad de conmutación de password input | boolean | — | false |
| disabled | si esta deshabilitado | boolean | — | false |
| size | tamaño del input, esto no funciona cuando `type` no es textarea | string | medium / small / mini | — |
| prefix-icon | clase del icono de prefijo | string | — | — |
| suffix-icon | clase del icono de sufijo | string | — | — |
| rows | número de filas, sólo funciona cuando `type` es `textarea`. | number | — | 2 |
| autosize | si textarea tiene una altura adaptativa, sólo funciona cuando el`type` es `textarea`. Puede aceptar un objeto, p. ej. { minRows: 2, maxRows: 6 } | boolean / object | — | false |
| autocomplete | igual que `autocomplete` en el input nativo | string | on/off | off |
| auto-complete | @DEPRECATED en el próximo cambio mayor de versión | string | on/off | off |
| name | igual que `name` en el input nativo | string | — | — |
| readonly | igual que `readonly` en el input nativo | boolean | — | false |
| max | igual que `max` en el input nativo | — | — | — |
| min | igual que `min` en el input nativo | — | — | — |
| step | igual que `step` en el input nativo | — | — | — |
| resize | control para el dimensionamiento | string | none, both, horizontal, vertical | — |
| autofocus | igual que `autofocus` en el input nativo | boolean | — | false |
| form | igual que `form` en el input nativo | string | — | — |
| label | texto de la etiqueta | string | — | — |
| tabindex | orden de tabulación para el Input | string | - | - |
### Input slots
| Nombre | Descripción |
| ------- | ------------------------------------ |
| prefix | contenido como prefijo del input |
| suffix | contenido como sufijo del input |
| prepend | contenido antes del input |
| append | contenido a añadir después del input |
### Input eventos
| Nombre | Descripción | Parámetros |
| ------ | ------------------------------------------------------------ | ------------------------- |
| blur | Se dispara cuando se pierde el foco | (event: Event) |
| focus | Se dispara cuando se obtiene el foco | (event: Event) |
| change | se activa cuando cambia el valor de entrada | (value: string \| number) |
| change | se activa solo cuando el cuadro de entrada pierde el foco o el usuario presiona Enter | (value: string \| number) |
| input | se activa cuando cambia el valor de entrada | (value: string \| number) |
| clear | se dispara cuando la entrada es borrada por el botón generado por el atributo `clearable`. | — |
### Input Métodos
| Método | Descripción | Parámetros |
| ------ | ----------------------------- | ---------- |
| focus | coloca el foco en el elemento | — |
| blur | quita el foco del elemento | — |
| select | selecciona el texto del input | — |
### Autocomplete Atributos
| Atributo | Descripción | Tipo | Opciones | Por defecto |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | -------------------------------------------------------------- | ------------ |
| placeholder | el placeholder del Autocomplete | string | — | — |
| disabled | si el Autocompete esta deshabilitado | boolean | — | false |
| value-key | nombre del campo del objeto de sugerencia del input para la visualización | string | — | value |
| icon | nombre del icono | string | — | — |
| value | valor enlazado | string | — | — |
| debounce | retardo al escribir, en milisegundos | number | — | 300 |
| placement | ubicación del menú emergente | string | top / top-start / top-end / bottom / bottom-start / bottom-end | bottom-start |
| fetch-suggestions | un método para obtener las sugerencias del input. Cuando las sugerencias estén listas, invocar `callback(data:[])` para devolverlas a Autocomplete | Function(queryString, callback) | — | — |
| popper-class | nombre personalizado de clase para el dropdown de autocomplete | string | — | — |
| trigger-on-focus | si se deben mostrar sugerencias cuando el input obtiene el foco | boolean | — | true |
| name | igual que `name` en el input nativo | string | — | — |
| select-when-unmatched | si se emite un evento `select` al pulsar enter cuando no hay coincidencia de Autocomplete | boolean | — | false |
| label | texto de la etiqueta | string | — | — |
| prefix-icon | prefix icon class | string | — | — |
| suffix-icon | suffix icon class | string | — | — |
| hide-loading | si se debe ocultar el icono de loading en la búsqueda remota | boolean | — | false |
| popper-append-to-body | si añadir el desplegable al cuerpo. Si la posición del menú desplegable es incorrecta, puede intentar establecer este prop a false | boolean | - | true |
| validate-event | si se debe lanzar la validación de formulario | boolean | - | true |
| highlight-first-item | si se debe resaltar el primer elemento en las sugerencias de búsqueda remota de forma predeterminada | boolean | - | false |
### Autocomplete Slots
| Nombre | Descripción |
| ------- | ------------------------------------ |
| prefix | contenido como prefijo del input |
| suffix | contenido como sufijo del input |
| prepend | contenido antes del input |
| append | contenido a añadir después del input |
### Autocomplete Scoped Slot
| Nombre | Descripción |
| ------ | ------------------------------------------------------------ |
| — | Contenido personalizado para el input de sugerencias. El parámetro del scope es { ítem } |
### Autocomplete Eventos
| Nombre | Descripción | Parámetros |
| ------ | ----------------------------------------------- | ------------------------------------------ |
| select | se dispara cuando se hace clic a una sugerencia | sugerencia en la que se está haciendo clic |
| change | se activa cuando cambia el valor de entrada | (value: string \| number) |
### Autocomplete Método
| Método | Descripción | Parámetros |
| ------ | ----------------------------- | ---------- |
| focus | coloca el foco en el elemento | — |

View File

@@ -0,0 +1,34 @@
## Instalación
### npm
Instalar mediante npm es la forma recomendada ya que se integra fácilmente con [webpack](https://webpack.js.org/).
```shell
npm i element-ui -S
```
### CDN
Obtenga la última versión desde [unpkg.com/element-ui](https://unpkg.com/element-ui/) , e importe el JavaScript y los archivos CSS en su página.
```html
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
```
##Tip
Recomendamos a nuestros usuarios congelar la versión de Element cuando usas un CDN. Por favor, refiérase a [unpkg.com](https://unpkg.com) para más información.
### Hello world
Si esta usando un CDN, una página con Hello-World es fácil con Element. [Online Demo](https://codepen.io/ziyoung/pen/rRKYpd)
<iframe height="265" style="width: 100%;" scrolling="no" title="Element demo" src="//codepen.io/ziyoung/embed/rRKYpd/?height=265&theme-id=light&default-tab=html,result" frameborder="no" allowtransparency="true" allowfullscreen="true">
See the Pen <a href='https://codepen.io/ziyoung/pen/rRKYpd/'>Element demo</a> by hetech
(<a href='https://codepen.io/ziyoung'>@ziyoung</a>) on <a href='https://codepen.io'>CodePen</a>.
</iframe>
Si esta usando npm y desea combinarlo con webpack, por favor continué a la siguiente página: [Quick Start](/#/es/component/quickstart)

359
examples/docs/es/layout.md Normal file
View File

@@ -0,0 +1,359 @@
## Layout
Rápido y fácilmente crea un layout básico con 24 columnas.
### Layout básico
Crea un layout básico usando columnas.
:::demo Con `row` y `col`, puede fácilmente manipular el layout usando el atributo `span`.
```html
<el-row>
<el-col :span="24"><div class="grid-content bg-purple-dark"></div></el-col>
</el-row>
<el-row>
<el-col :span="12"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="12"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<el-row>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<el-row>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Espaciado de columnas
El espaciado de columnas está soportado.
:::demo Row provee el atributo `gutter` para especificar el espacio entre columnas y su valor por defecto es 0.
```html
<el-row :gutter="20">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Layout híbrido
Crea un complejo layout híbrido combinando el básico de 1/24 columnas.
:::demo
```html
<el-row :gutter="20">
<el-col :span="16"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="16"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="4"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Offset de columnas
Puedes especificar offsets para las columnas.
:::demo Puedes especificar el offset para una columna mediante el atributo `offset` de Col.
```html
<el-row :gutter="20">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6" :offset="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row :gutter="20">
<el-col :span="12" :offset="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Alineación
Usa flex layout para un alineamiento flexible de columnas.
:::demo Puede habilitar flex layout asignando el atributo `type` a 'flex', y definir el layout de elementos hijos asignando el atributo `justify` con los valores start, center, end, space-between o space-around.
```html
<el-row type="flex" class="row-bg">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="center">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="end">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="space-between">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<el-row type="flex" class="row-bg" justify="space-around">
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :span="6"><div class="grid-content bg-purple"></div></el-col>
</el-row>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.row-bg {
padding: 10px 0;
background-color: #f9fafc;
}
</style>
```
:::
### Responsive Layout
Tomando el ejemplo de Bootstrap responsive design, existen 5 breakpoints: xs, sm, md, lg y xl.
:::demo
```html
<el-row :gutter="10">
<el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple"></div></el-col>
<el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple-light"></div></el-col>
<el-col :xs="4" :sm="6" :md="8" :lg="9" :xl="11"><div class="grid-content bg-purple"></div></el-col>
<el-col :xs="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple-light"></div></el-col>
</el-row>
<style>
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
</style>
```
:::
### Clases útiles para ocultar elementos
Adicionalmente, Element provee una serie de clases para ocultar elementos dadas ciertas condiciones. Estas clases pueden se agregadas a cualquier elemento del DOM o un elemento propio. Necesita importar el siguiente archivo CSS para usar estas clases:
```js
import 'element-ui/lib/theme-chalk/display.css';
```
Las clases son:
- `hidden-xs-only` - oculto en viewports extra pequeños solamente
- `hidden-sm-only` - oculto en viewports pequeños solamente
- `hidden-sm-and-down` - oculto en viewports pequeños y menores
- `hidden-sm-and-up` - oculto en viewports pequeños y superiores
- `hidden-md-only` - oculto en viewports medios solamente
- `hidden-md-and-down` - oculto en viewports medios y menores
- `hidden-md-and-up` - oculto en viewports medios y mayores
- `hidden-lg-only` - ocultos en viewports grandes solamente
- `hidden-lg-and-down` - ocultos en viewports grandes y menores
- `hidden-lg-and-up` - ocultos en viewports grandes y superiores
- `hidden-xl-only` - oculto en viewports extra grandes solamente
### Atributos Row
| Atributos | Descripción | Tipo | Valores aceptados | Valor por defecto |
| --------- | ---------------------------------------- | ------ | ---------------------------------------- | ----------------- |
| gutter | espaciado de la grilla | number | — | 0 |
| type | modo del layout , puedes usar flex, funciona en navegadores modernos | string | — | — |
| justify | alineación horizontal del layout flex | string | start/end/center/space-around/space-between | start |
| align | alineación vertical del layout flex | string | top/middle/bottom | top |
| tag | tag de elemento propio | string | * | div |
### Atributos Col
| Atributos | Descripción | Tipo | Valores aceptados | Valor por defecto |
| --------- | ------------------------------------------------------------ | ----------------------------------------- | ----------------- | ----------------- |
| span | número de columnas que abarca la cuadrícula | number | — | 24 |
| offset | especifica el espacio en el lado izquierdo del grill | number | — | 0 |
| push | número de columnas que la grilla se mueve hacia la derecha | number | — | 0 |
| pull | número de columnas que la grilla se mueve hacia la izquierda | number | — | 0 |
| xs | `<768px` Columnas responsive u objeto con propiedades de la columna | number/object (e.g. {span: 4, offset: 4}) | — | — |
| sm | `≥768px` Columnas responsive u objeto con propiedades de la columna | number/object (e.g. {span: 4, offset: 4}) | — | — |
| md | `≥992px` Columnas responsive u objeto con propiedades de la columna | number/object (e.g. {span: 4, offset: 4}) | — | — |
| lg | `≥1200px` Columnas responsive u objeto con propiedades de la columna | number/object (e.g. {span: 4, offset: 4}) | — | — |
| xl | `≥1920px` Columnas responsive u objeto con propiedades de la columna | number/object (e.g. {span: 4, offset: 4}) | — | — |
| tag | tag de elemento propio | string | * | div |

77
examples/docs/es/link.md Normal file
View File

@@ -0,0 +1,77 @@
## Link
Texto con hipervínculo
### Básico
Texto con hipervínculo básico
:::demo
```html
<div>
<el-link href="https://element.eleme.io" target="_blank">default</el-link>
<el-link type="primary">primary</el-link>
<el-link type="success">success</el-link>
<el-link type="warning">warning</el-link>
<el-link type="danger">danger</el-link>
<el-link type="info">info</el-link>
</div>
```
:::
### Deshabilitar
Deshabilita el hipervínculo
:::demo
```html
<div>
<el-link disabled>default</el-link>
<el-link type="primary" disabled>primary</el-link>
<el-link type="success" disabled>success</el-link>
<el-link type="warning" disabled>warning</el-link>
<el-link type="danger" disabled>danger</el-link>
<el-link type="info" disabled>info</el-link>
</div>
```
:::
### Subrayado
Subrayado del hipervínculo
:::demo
```html
<div>
<el-link :underline="false">Without Underline</el-link>
<el-link>With Underline</el-link>
</div>
```
:::
### Icono
Hipervínculo con icono
:::demo
```html
<div>
<el-link icon="el-icon-edit">Edit</el-link>
<el-link>Check<i class="el-icon-view el-icon--right"></i> </el-link>
</div>
```
:::
### Atributos
| Atributo | Descripción | Tipo | Opciones | Por defecto |
| --------- | ---------------------------------------------------- | ------- | ------------------------------------------- | ----------- |
| type | tipo | string | primary / success / warning / danger / info | default |
| underline | si el hipervínculo estará subrayado | boolean | — | true |
| disabled | si el componente esta deshabilitado | boolean | — | false |
| href | lo mismo que el valor nativo del hipervínculo `href` | string | — | - |
| icon | nombre de clase del icono | string | — | - |

209
examples/docs/es/loading.md Normal file
View File

@@ -0,0 +1,209 @@
## Cargando
Se muestra la animación mientras se cargan los datos.
### Cargando dentro de un contenedor
Muestra una animación en un contenedor (como en una tabla) mientras se cargan los datos.
:::demo Element provee dos maneras para invocar el componente de Cargando: por directiva y por servicio. Para la directiva personalizada `v-loading`, solo necesitas enlazarlo a un valor `Boolean`. Por defecto, la máscara de carga se agregará al elemento donde se usa la directiva. Al agregar el modificador `body`, la máscara se agrega al elemento body.
```html
<template>
<el-table
v-loading="loading"
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="Fecha"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="Nombre"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="Dirección">
</el-table-column>
</el-table>
</template>
<style>
body {
margin: 0;
}
</style>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-02',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-04',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-01',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}],
loading: true
};
}
};
</script>
```
:::
### Personalización
Puede personalizar el texto de carga, spinner de carga y color de fondo.
:::demo Agregue el atributo `element-loading-text` al elemento en el que `v-loading` está vinculado, y su valor se mostrará debajo del spinner. Del mismo modo, `element-loading-spinner` y `element-loading-background` son para personalizar el nombre de la clase del spinner y el color de fondo.
```html
<template>
<el-table
v-loading="loading"
element-loading-text="Loading..."
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0.8)"
:data="tableData"
style="width: 100%">
<el-table-column
prop="date"
label="Fecha"
width="180">
</el-table-column>
<el-table-column
prop="name"
label="Nombre"
width="180">
</el-table-column>
<el-table-column
prop="address"
label="Dirección">
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [{
date: '2016-05-02',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-04',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}, {
date: '2016-05-01',
name: 'John Smith',
address: 'No.1518, Jinshajiang Road, Putuo District'
}],
loading: true
};
}
};
</script>
```
:::
### Cargando a pantalla completa
Muestra una animación de pantalla completa mientras se cargan los datos
:::demo Cuando se utiliza como una directiva, la carga a pantalla completa requiere el modificador `fullscreen`, y este puede ser agregado al `body`. En este caso, si desea deshabilitar el desplazamiento en `body`, puede agregar otro modificador `lock`. Cuando se utiliza como un servicio, el componente puede ser mostrado a pantalla completa por defecto.
```html
<template>
<el-button
type="primary"
@click="openFullScreen1"
v-loading.fullscreen.lock="fullscreenLoading">
Como directiva
</el-button>
<el-button
type="primary"
@click="openFullScreen2">
Como servicio
</el-button>
</template>
<script>
export default {
data() {
return {
fullscreenLoading: false
}
},
methods: {
openFullScreen1() {
this.fullscreenLoading = true;
setTimeout(() => {
this.fullscreenLoading = false;
}, 2000);
},
openFullScreen2() {
const loading = this.$loading({
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
setTimeout(() => {
loading.close();
}, 2000);
}
}
}
</script>
```
:::
### Servicio
Puede invocar el componente con un servicio. Importe el servicio:
```javascript
import { Loading } from 'element-ui';
```
Invocar:
```javascript
Loading.service(options);
```
El parámetro `options` es la configuración del componente, y estos detalles pueden ser encontrados en la siguiente table. `LoadingService` devuelve una instancia del componente, y puede cerrarlo invocando el método `close`:
```javascript
let loadingInstance = Loading.service(options);
loadingInstance.close();
```
Tenga en cuenta que, en este caso, el componente a pantalla completa es una instancia única. Si un nuevo componente de pantalla completa es invocado antes de que se cierre la existente, se devolverá la instancia existente en lugar de crear la otra instancia:
```javascript
let loadingInstance1 = Loading.service({ fullscreen: true });
let loadingInstance2 = Loading.service({ fullscreen: true });
console.log(loadingInstance1 === loadingInstance2); // true
```
Llamar al método `close` en cualquiera de estas puede cerrarlo.
Si Element es importado completamente, un método global `$loading` puede ser registrado a Vue.prototype. Puede invocarlo como esto: `this.$loading(options)`, y también devuelve una instancia del componente.
### Opciones
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------- | ---------------------------------------- | ------------- | ----------------- | ------------- |
| target | el nodo del DOM que el componente debe cubrir. Acepta un objecto DOM o una cadena. Si está es una cadena, este será pasado a `document.querySelector` para obtener el correspondiente nodo del DOM | object/string | — | document.body |
| body | igual que el modificador `body` de `v-loading` | boolean | — | false |
| fullscreen | igual que el modificador `fullscreen` de `v-loading` | boolean | — | true |
| lock | igual que el modificador `lock` de `v-loading` | boolean | — | false |
| text | texto de cargando que se muestra debajo del spinner | string | — | — |
| spinner | nombre de clase del spinner personalizado | string | — | — |
| background | color de fondo de la máscara | string | — | — |
| customClass | nombre de clase personalizada para el componente | string | — | — |

300
examples/docs/es/menu.md Normal file
View File

@@ -0,0 +1,300 @@
## NavMenu
Menú que provee la navegación para tu sitio.
### Top bar
Top bar NavMenu puede ser usado en distinto escenarios.
:::demo Por defecto el menú es vertical, pero puede hacerlo horizontal asignando a la propiedad `mode` el valor 'horizontal'. Además, puede utilizar el componente de submenú para crear un menú de segundo nivel. Menú provee `background-color`, `text-color` y `active-text-color` para customizar los colores.
```html
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
<el-menu-item index="1">Processing Center</el-menu-item>
<el-submenu index="2">
<template slot="title">Workspace</template>
<el-menu-item index="2-1">item one</el-menu-item>
<el-menu-item index="2-2">item two</el-menu-item>
<el-menu-item index="2-3">item three</el-menu-item>
<el-submenu index="2-4">
<template slot="title">item four</template>
<el-menu-item index="2-4-1">item one</el-menu-item>
<el-menu-item index="2-4-2">item two</el-menu-item>
<el-menu-item index="2-4-3">item three</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="3" disabled>Info</el-menu-item>
<el-menu-item index="4"><a href="https://www.ele.me" target="_blank">Orders</a></el-menu-item>
</el-menu>
<div class="line"></div>
<el-menu
:default-active="activeIndex2"
class="el-menu-demo"
mode="horizontal"
@select="handleSelect"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<el-menu-item index="1">Processing Center</el-menu-item>
<el-submenu index="2">
<template slot="title">Workspace</template>
<el-menu-item index="2-1">item one</el-menu-item>
<el-menu-item index="2-2">item two</el-menu-item>
<el-menu-item index="2-3">item three</el-menu-item>
<el-submenu index="2-4">
<template slot="title">item four</template>
<el-menu-item index="2-4-1">item one</el-menu-item>
<el-menu-item index="2-4-2">item two</el-menu-item>
<el-menu-item index="2-4-3">item three</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="3" disabled>Info</el-menu-item>
<el-menu-item index="4"><a href="https://www.ele.me" target="_blank">Orders</a></el-menu-item>
</el-menu>
<script>
export default {
data() {
return {
activeIndex: '1',
activeIndex2: '1'
};
},
methods: {
handleSelect(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
```
:::
### Side bar
NavMenu vertical con sub-menús.
:::demo Puede utilizar el componente `el-menu-item-group` para crear un grupo de menú, y el nombre del grupo estará determinado por la propiedad `title` o la propiedad `slot`.
```html
<el-row class="tac">
<el-col :span="12">
<h5>Default colors</h5>
<el-menu
default-active="2"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span>Navigator One</span>
</template>
<el-menu-item-group title="Group One">
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item one</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">item four</template>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span>Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<i class="el-icon-document"></i>
<span>Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span>Navigator Four</span>
</el-menu-item>
</el-menu>
</el-col>
<el-col :span="12">
<h5>Custom colors</h5>
<el-menu
default-active="2"
class="el-menu-vertical-demo"
@open="handleOpen"
@close="handleClose"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span>Navigator One</span>
</template>
<el-menu-item-group title="Group One">
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item one</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<template slot="title">item four</template>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span>Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<i class="el-icon-document"></i>
<span>Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span>Navigator Four</span>
</el-menu-item>
</el-menu>
</el-col>
</el-row>
<script>
export default {
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
```
:::
### Collapse
NavMenu vertical puede ser colapsado.
:::demo
```html
<el-radio-group v-model="isCollapse" style="margin-bottom: 20px;">
<el-radio-button :label="false">expand</el-radio-button>
<el-radio-button :label="true">collapse</el-radio-button>
</el-radio-group>
<el-menu default-active="2" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose" :collapse="isCollapse">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-location"></i>
<span slot="title">Navigator One</span>
</template>
<el-menu-item-group>
<span slot="title">Group One</span>
<el-menu-item index="1-1">item one</el-menu-item>
<el-menu-item index="1-2">item two</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-submenu index="1-4">
<span slot="title">item four</span>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-submenu>
</el-submenu>
<el-menu-item index="2">
<i class="el-icon-menu"></i>
<span slot="title">Navigator Two</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<i class="el-icon-document"></i>
<span slot="title">Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<i class="el-icon-setting"></i>
<span slot="title">Navigator Four</span>
</el-menu-item>
</el-menu>
<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
width: 200px;
min-height: 400px;
}
</style>
<script>
export default {
data() {
return {
isCollapse: true
};
},
methods: {
handleOpen(key, keyPath) {
console.log(key, keyPath);
},
handleClose(key, keyPath) {
console.log(key, keyPath);
}
}
}
</script>
```
:::
### Atributos Menú
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ----------------- | ---------------------------------------- | ------- | --------------------- | ----------- |
| mode | modo de presentación del menú | string | horizontal / vertical | vertical |
| collapse | si el menú está colapsado (solo en modo vertical) | boolean | — | false |
| background-color | color de fondo del menú (formato hexadecimal) | string | — | #ffffff |
| text-color | color de texto del menú (formato hexadecimal) | string | — | #303133 |
| active-text-color | color del texto del menu-item activo (formato hexadecimal) | string | — | #409EFF |
| default-active | índice del menu-item activo | string | — | — |
| default-openeds | arreglo que contiene las llaves del sub-menus activo | Array | — | — |
| unique-opened | si solo un submenu puede ser activo | boolean | — | false |
| menu-trigger | como dispara eventos sub-menus, solo funciona cuando `mode` es 'horizontal' | string | hover / click | hover |
| router | si el modo `vue-router` está activado. Si es verdadero, el índice será usado como 'path' para activar la ruta | boolean | — | false |
| collapse-transition | si se debe permitir collapse transition | boolean | — | true |
### Métodos Menu
| Métodos de evento | Descripción | Parámetros |
| ---------------- | ----------------------------- | -------------------------------------- |
| open | abre un sub-menu específico | index: índice del sub-menu para abrir |
| close | cierra un sub-menu específico | index: índice del sub-menu para cerrar |
### Eventos Menu
| Nombre de evento | Descripción | Parámetros |
| ---------------- | ---------------------------------------- | ---------------------------------------- |
| select | callback ejecutado cuando el menú es activado | index: índice del menú activado, indexPath: index path del menú activado |
| open | callback ejecutado cuando sub-menu se expande | index: índice del sub-menu expandido, indexPath: index path del sub-menu expandido |
| close | callback ejecutado cuando sub-menu colapsa | index: índice del sub-menu colapsado, indexPath: index path del menú colapsado |
### Eventos Menu-Item
| Nombre de evento | Descripción | Parámetros |
| ---------------- | ---------------------------------------- | -------------------------- |
| click | callback ejecutado cuando se hace click sobre menu-item | el: instancia de menu-item |
### Atributos SubMenu
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------ | ---------------------------------------- | ------ | ----------------- | ----------- |
| index | identificador único | string/null | — | null |
| popper-class | nombre personalizado de la clase del menú popup | string | — | — |
| show-timeout | tiempo de espera antes de mostrar un submenú | number | — | 300 |
| hide-timeout | tiempo de espera antes de ocultar un submenú | number | — | 300 |
| disabled | si esta `disabled` el sub-menu | boolean | — | false |
| popper-append-to-body | si se debe agregar el menú emergente al cuerpo. Si la posición del menú es incorrecta, puede intentar ajustar este prop | boolean | - | level one Submenu: true / other Submenus: false |
### Atributos Menu-Item
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ------------------- | ------ | ----------------- | ----------- |
| index | identificador único | string | — | — |
| route | Objeto Vue Router | object | — | — |
| disabled | si esta `disabled` | boolean | — | false |
### Atributos Menu-Group
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| -------- | ---------------- | ------ | ----------------- | ----------- |
| title | título del grupo | string | — | — |

View File

@@ -0,0 +1,331 @@
## MessageBox
Un conjunto de cajas modales simulando un sistema de message box, principalmente para alertar información, confirmar operaciones y mostrar mensajes de aviso.
:::tip
Por diseño los message box nos proveen de simulaciones de sistemas como los componentes `alert`, `confirm` y `prompt`entonces su contenido debería ser simple. para contenido mas complejo, por favor utilice el componente Dialog.
:::
### Alert
Alert interrumpe las operaciones realizadas hasta que el usuario confirme la alerta.
:::demo Desplegar una alerta utilizando el método `$alert`. Simula el sistema `alert`, y no puede ser cerrado al presionar la tecla ESC o al dar clic fuera de la caja. En este ejemplo, dos parámetros son recibidos `message` y `title`. Vale la pena mencionar que cuando la caja es cerrada, regresa un objeto `Promise` para su procesamiento posteriormente. Si no estas seguro si el navegador soporta `Promise`, deberías importar una librería de terceros de polyfill o utilizar callbacks.
```html
<template>
<el-button type="text" @click="open">Click to open the Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$alert('This is a message', 'Title', {
confirmButtonText: 'OK',
callback: action => {
this.$message({
type: 'info',
message: `action: ${ action }`
});
}
});
}
}
}
</script>
```
:::
### Confirm
Confirm es utilizado para preguntar al usuario y recibir una confirmación.
:::demo Llamando al método `$confirm` para abrir el componente confirm, y simula el sistema `confirm`. También podemos personalizar a gran medida el componente Message Box al mandar un tercer atributo llamado `options` que es literalmente un objeto. El atributo `type` indica el tipo de mensaje, y su valor puede ser `success`, `error`, `info` y `warning`. Se debe tener en cuenta que el segundo atributo `title` debe ser de tipo `string`, y si es de tipo `object`, sera manejado como el atributo `options`. Aquí utilizamos `Promise` para manejar posteriormente el proceso.
```html
<template>
<el-button type="text" @click="open">Click to open the Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$confirm('This will permanently delete the file. Continue?', 'Warning', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
this.$message({
type: 'success',
message: 'Delete completed'
});
}).catch(() => {
this.$message({
type: 'info',
message: 'Delete canceled'
});
});
}
}
}
</script>
```
:::
### Prompt
Prompt es utilizado cuando se requiere entrada de información del usuario.
:::demo Llamando al método `$prompt` desplegamos el componente prompt, y simula el sistema `prompt`.Puedes utilizar el parámetro `inputPattern` para especificar tu propio patrón RegExp. Utiliza el parámetro `inputValidator` para especificar el método de validación, y debería regresar un valor de tipo `Boolean` o `String`. Al regresar `false` o `String` significa que la validación a fallado, y la cadena regresada se usara como `inputErrorMessage`. Ademas, puedes personalizar el atributo placeholder del input box con el parámetro `inputPlaceholder`.
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$prompt('Please input your e-mail', 'Tip', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
inputErrorMessage: 'Invalid Email'
}).then(({ value }) => {
this.$message({
type: 'success',
message: 'Your email is:' + value
});
}).catch(() => {
this.$message({
type: 'info',
message: 'Input canceled'
});
});
}
}
}
</script>
```
:::
### Personalización
Puede ser personalizado para mostrar diversos contenidos.
:::demo Los tres métodos mencionados anteriormente son un rempaquetado del método `$msgbox`. En este ejemplo se realiza una llamada al método `$msgbox` directamente utilizando el atributo `showCancelButton`, el cual es utilizado para indicar si el botón cancelar es mostrado en pantalla. Además podemos utilizar el atributo `cancelButtonClass` para agregar un estilo personalizado y el atributo `cancelButtonText` para personalizar el texto del botón (el botón de confirmación también cuenta con estos campos, y podrá encontrar una lista completa de estos atributos al final de esta documentación). Este ejemplo también utiliza el atributo `beforeClose`. Es un método que es disparado cuando una instancia del componente MessageBox es cerrada, y su ejecución detendrá el cierre de la instancia. Tiene tres parámetros: `action`, `instance` y `done`. Al utilizarla te permite manipular la instancia antes de que sea cerrada, e.g. activando `loading` para el botón de confirmación; puede invocar el método `done` para cerrar la instancia del componente MessageBox (si el método `done` no es llamado dentro del atributo `beforeClose`, la instancia no podrá cerrarse).
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
const h = this.$createElement;
this.$msgbox({
title: 'Message',
message: h('p', null, [
h('span', null, 'Message can be '),
h('i', { style: 'color: teal' }, 'VNode')
]),
showCancelButton: true,
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
beforeClose: (action, instance, done) => {
if (action === 'confirm') {
instance.confirmButtonLoading = true;
instance.confirmButtonText = 'Loading...';
setTimeout(() => {
done();
setTimeout(() => {
instance.confirmButtonLoading = false;
}, 300);
}, 3000);
} else {
done();
}
}
}).then(action => {
this.$message({
type: 'info',
message: 'action: ' + action
});
});
},
}
}
</script>
```
:::
:::tip
El contenido de MessageBox puede ser `VNode`, permitiéndonos pasar componentes personalizados. Al abrir el MessageBox, Vue compara el nuevo `VNode` con el viejo `VNode`, y luego averigua cómo actualizar eficientemente la interfaz de usuario, de modo que es posible que los componentes no se vuelvan a procesar completamente ([#8931](https://github.com/ElemeFE/element/issues/8931)). En este caso, se puede añadir una clave única a `VNode` cada vez que se abre MessageBox: [ejemplo](https://jsfiddle.net/zhiyang/ezmhq2ef).
:::
### Utiliza cadenas HTML
`message` soporta cadenas HTML.
:::demo Establezca el valor de `dangerouslyUseHTMLString` a true y `message` sera tratado como una cadena HTML.
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$alert('<strong>This is <i>HTML</i> string</strong>', 'HTML String', {
dangerouslyUseHTMLString: true
});
}
}
}
</script>
```
:::
:::warning
Aunque la propiedad `message` soporta cadenas HTML, realizar arbitrariamente render dinámico de HTML en nuestro sitio web puede ser muy peligroso ya que puede conducir fácilmente a [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). Entonces cuando `dangerouslyUseHTMLString` esta activada, asegúrese que el contenido de `message` sea de confianza, y **nunca** asignar `message` a contenido generado por el usuario.
:::
### Distinguir entre cancelar y cerrar
En algunos casos, hacer clic en el botón Cancelar y en el botón Cerrar puede tener diferentes significados.
:::demo Por defecto, los parámetros de `Promise's reject callback` y `callback` son `cancel` cuando el usuario cancela (haciendo clic en el botón de cancelación) y cierra (haciendo clic en el botón de cerrar o en la capa de máscara, pulsando la tecla ESC) el MessageBox. Si `distinguishCancelAndClose` está ajustado a `true`, los parámetros de las dos operaciones anteriores son `cancel` y `close` respectivamente.
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$confirm('You have unsaved changes, save and proceed?', 'Confirm', {
distinguishCancelAndClose: true,
confirmButtonText: 'Save',
cancelButtonText: 'Discard Changes'
})
.then(() => {
this.$message({
type: 'info',
message: 'Changes saved. Proceeding to a new route.'
});
})
.catch(action => {
this.$message({
type: 'info',
message: action === 'cancel'
? 'Changes discarded. Proceeding to a new route.'
: 'Stay in the current route'
})
});
}
}
}
</script>
```
:::
### Contenido centrado
El contenido del componente MessageBox puede ser centrado.
:::demo Establecer `center` a `true` centrara el contenido
```html
<template>
<el-button type="text" @click="open">Click to open Message Box</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$confirm('This will permanently delete the file. Continue?', 'Warning', {
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning',
center: true
}).then(() => {
this.$message({
type: 'success',
message: 'Delete completed'
});
}).catch(() => {
this.$message({
type: 'info',
message: 'Delete canceled'
});
});
}
}
}
</script>
```
:::
### Métodos Globales
Si Element fue importado completamente, agregara los siguientes métodos globales para Vue.prototype: `$msgbox`, `$alert`, `$confirm` y `$prompt`. Así que en una instancia de Vue puedes llamar el método `MessageBox` como lo que hicimos en esta pagina. Los parámetros son:
- `$msgbox(options)`
- `$alert(message, title, options)` or `$alert(message, options)`
- `$confirm(message, title, options)` or `$confirm(message, options)`
- `$prompt(message, title, options)` or `$prompt(message, options)`
### Importación local
Si prefieres importar `MessageBox` cuando lo necesites (on demand):
```javascript
import { MessageBox } from 'element-ui';
```
Los métodos correspondientes: `MessageBox`, `MessageBox.alert`, `MessageBox.confirm` y `MessageBox.prompt`. Los parámetros son los mismos que los anteriores.
### Opciones
| Atributo | Descripción | Tipo | Valores Permitidos | Por defecto |
| ------------------------ | ---------------------------------------- | ---------------------------------------- | -------------------------------- | ---------------------------------------- |
| title | titulo del componente MessageBox | string | — | — |
| message | contenido del componente MessageBox | string | — | — |
| dangerouslyUseHTMLString | utilizado para que `message` sea tratado como una cadena HTML | boolean | — | false |
| type | tipo de mensaje , utilizado para mostrar el icono | string | success / info / warning / error | — |
| iconClass | clase personalizada para el icono, sobrescribe `type` | string | — | — |
| customClass | nombre de la clase personalizada para el componente MessageBox | string | — | — |
| callback | MessageBox callback al cerrar si no desea utilizar Promise | function(action), donde la accion puede ser 'confirm', 'cancel' o 'close', e `instance` es la instancia del componente MessageBox. Puedes acceder a los metodos y atributos de esa instancia | — | — |
| beforeClose | callback llamado antes de cerrar el componente MessageBox, y previene que el componente MessageBox se cierre | function(action, instance, done), donde `action` pueden ser 'confirm', 'cancel' o 'close'; `instance` es la instancia del componente MessageBox, Puedes acceder a los metodos y atributos de esa instancia; `done` es para cerrar la instancia | — | — |
| distinguishCancelAndClose | si se debe distinguir entre cancelar y cerrar | boolean | — | false |
| lockScroll | utilizado para bloquear el desplazamiento del contenido del MessageBox prompts | boolean | — | true |
| showCancelButton | utilizado para mostrar un botón cancelar | boolean | — | false (true cuando es llamado con confirm y prompt) |
| showConfirmButton | utilizado para mostrar un botón confirmar | boolean | — | true |
| cancelButtonText | contenido de texto del botón cancelar | string | — | Cancel |
| confirmButtonText | contenido de texto del botón confirmar | string | — | OK |
| cancelButtonClass | nombre de la clase personalizada del botón cancelar | string | — | — |
| confirmButtonClass | nombre de la clase personalizada del botón confirmar | string | — | — |
| closeOnClickModal | utilizado para que que el componente MessageBox pueda ser cerrado al dar clic en la mascara | boolean | — | true (false cuando es llamado con alert) |
| closeOnPressEscape | utilizado para que que el componente MessageBox pueda ser cerrado al presionar la tecla ESC | boolean | — | true (false cuando es llamado con alert) |
| closeOnHashChange | utilizado para cerra el componente MessageBox cuando hash cambie | boolean | — | true |
| showInput | utilizado para mostrar el componente input | boolean | — | false (true cuando es llamado con prompt) |
| inputPlaceholder | placeholder para el componente input | string | — | — |
| inputType | tipo del componente input | string | — | text |
| inputValue | valor inicial del componente input | string | — | — |
| inputPattern | regexp del componente input | regexp | — | — |
| inputValidator | función de validación del componente input. Debe regresar un valor de tipo boolean o string. Si regresa un valor tipo string, sera asignado a inputErrorMessage | function | — | — |
| inputErrorMessage | mensaje de error cuando la validación falla | string | — | Illegal input |
| center | utilizado para alinear el contenido al centro | boolean | — | false |
| roundButton | utilizado para redondear el botón | boolean | — | false |

220
examples/docs/es/message.md Normal file
View File

@@ -0,0 +1,220 @@
## Message
Utilizado para mostrar retroalimentación después de una actividad. La diferencia con el componente Notification es que este ultimo es utilizado para mostrar una notificación pasiva a nivel de sistema.
### Uso básico
Se muestra en la parte superior de la pagina y desaparece después de 3 segundos.
:::demo La configuración del componente Message es muy similar al del componente notification, así que parte de las opciones no serán explicadas en detalle aquí. Puedes consultar la tabla de opciones en la parte inferior combinada con la documentación del componente notification para comprenderla. Element a registrado un método `$message` para poder invocarlo. Message puede tomar una cadena o un Vnode como parámetro, y lo mostrara como el cuerpo principal.
```html
<template>
<el-button :plain="true" @click="open">Show message</el-button>
<el-button :plain="true" @click="openVn">VNode</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$message('This is a message.');
},
openVn() {
const h = this.$createElement;
this.$message({
message: h('p', null, [
h('span', null, 'Message can be '),
h('i', { style: 'color: teal' }, 'VNode')
])
});
}
}
}
</script>
```
:::
### Tipos
Utilizados para mostrar retroalimentación de Success, Warning, Message y Error activities.
:::demo Cuando necesite mas personalización, el componente Message también puede tomar un objeto como parámetro. Por ejemplo, estableciendo el valor de `type` puede definir diferentes tipos, el predeterminado es `info`. En tales casos el cuerpo principal se pasa como el valor de `message`. También, hay registrados métodos para los diferentes tipos, así que, puedes llamarlos sin necesidad de pasar un tipo como `open4`.
```html
<template>
<el-button :plain="true" @click="open2">success</el-button>
<el-button :plain="true" @click="open3">warning</el-button>
<el-button :plain="true" @click="open1">message</el-button>
<el-button :plain="true" @click="open4">error</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$message('This is a message.');
},
open2() {
this.$message({
message: 'Congrats, this is a success message.',
type: 'success'
});
},
open3() {
this.$message({
message: 'Warning, this is a warning message.',
type: 'warning'
});
},
open4() {
this.$message.error('Oops, this is a error message.');
}
}
}
</script>
```
:::
### Closable
Un botón para cerrar que puede ser agregado.
:::demo Un componente Message predeterminado no se puede cerrar manualmente. Si necesitas un componente message que pueda cerrarse, puedes establecer el campo `showClose`. Ademas, al igual que las notificaciones, message tiene un atributo `duration` que puede ser controlado. Por defecto la duración es de 3000 ms, y no desaparecerá al llegar a `0`.
```html
<template>
<el-button :plain="true" @click="open1">message</el-button>
<el-button :plain="true" @click="open2">success</el-button>
<el-button :plain="true" @click="open3">warning</el-button>
<el-button :plain="true" @click="open4">error</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$message({
showClose: true,
message: 'This is a message.'
});
},
open2() {
this.$message({
showClose: true,
message: 'Congrats, this is a success message.',
type: 'success'
});
},
open3() {
this.$message({
showClose: true,
message: 'Warning, this is a warning message.',
type: 'warning'
});
},
open4() {
this.$message({
showClose: true,
message: 'Oops, this is a error message.',
type: 'error'
});
}
}
}
</script>
```
:::
### Texto centrado
Utiliza el atributo `center` para centrar el texto.
:::demo
```html
<template>
<el-button :plain="true" @click="openCenter">Centered text</el-button>
</template>
<script>
export default {
methods: {
openCenter() {
this.$message({
message: 'Centered text',
center: true
});
}
}
}
</script>
```
:::
### Utiliza cadenas HTML
`message` soporta cadenas HTML.
:::demo Establece la propiedad `dangerouslyUseHTMLString` en true y `message` sera tratado como una cadena HTML.
```html
<template>
<el-button :plain="true" @click="openHTML">Use HTML String</el-button>
</template>
<script>
export default {
methods: {
openHTML() {
this.$message({
dangerouslyUseHTMLString: true,
message: '<strong>This is <i>HTML</i> string</strong>'
});
}
}
}
</script>
```
:::
:::warning
Aunque la propiedad `message` soporta cadenas HTML, realizar arbitrariamente render dinámico de HTML en nuestro sitio web puede ser muy peligroso ya que puede conducir fácilmente a [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). Entonces cuando `dangerouslyUseHTMLString` esta activada, asegúrese que el contenido de `message` sea de confianza, y **nunca** asignar `message` a contenido generado por el usuario.
:::
### Métodos Globales
Element ha agregado un método global llamado `$message` para Vue.prototype. Entonces en una instancia de vue puede llamar a `Message` como lo hicimos en esta pagina.
### Importación local
Import `Message`:
```javascript
import { Message } from 'element-ui';
```
En este caso debería llamar al método `Message(options)`. También se han registrado métodos para los diferentes tipos, e.g. `Message.success(options)`. Puede llamar al método `Message.closeAll()` para cerrar manualmente todas las instancias.
### Opciones
| Atributo | Descripción | Tipo | Valores permitidos | Por defecto |
| ------------------------ | ---------------------------------------- | -------------- | -------------------------- | ----------- |
| message | texto del mensaje | string / VNode | — | — |
| type | tipo del mensaje | string | success/warning/info/error | info |
| iconClass | clase personalizada para el icono, sobrescribe `type` | string | — | — |
| dangerouslyUseHTMLString | utilizado para que `message` sea tratado como cadena HTML | boolean | — | false |
| customClass | nombre de clase personalizado para el componente Message | string | — | — |
| duration | muestra la duración,en mili segundos. si se establece en 0, este no se apagara automáticamente | number | — | 3000 |
| showClose | utilizado para mostrar un botón para cerrar | boolean | — | false |
| center | utilizado para centrar el texto | boolean | — | false |
| onClose | función callback ejecutada cuando se cierra con una instancia de mensaje como parámetro | function | — | — |
| offset | La distancia desde la parte superior del viewport | number | — | 20 |
### Métodos
`Message` y `this.$message` regresan una instancia del componente Message. Para cerrar manualmente la instancia, puede llamar al método `close`.
| Método | Descripción |
| ------ | ---------------------------- |
| close | cierra el componente Message |

View File

@@ -0,0 +1,318 @@
## Notification
Muestra un mensaje de notificación global en una esquina de la página.
### Uso básico
:::demo Element ha registrado el método`$notify` y recibe un objeto como parámetro. En el caso más sencillo, puede establecer el campo de `title` y el campo de ` message` para el título y el cuerpo de la notificación. De forma predeterminada, la notificación se cierra automáticamente después de 4500ms, pero configurando `duration` se puede controlar su duración. Específicamente, si está configurado en `0`, no se cerrará automáticamente. Tenga en cuenta que `duration` recibe un `Number` en mili segundos.
```html
<template>
<el-button
plain
@click="open1">
Closes automatically
</el-button>
<el-button
plain
@click="open2">
Won't close automatically
</el-button>
</template>
<script>
export default {
methods: {
open1() {
const h = this.$createElement;
this.$notify({
title: 'Title',
message: h('i', { style: 'color: teal' }, 'This is a reminder')
});
},
open2() {
this.$notify({
title: 'Prompt',
message: 'This is a message that does not automatically close',
duration: 0
});
}
}
}
</script>
```
:::
### Tipos de notificaciones
Proporcionamos cuatro tipos: success, warning, info y error.
:::demo Element proporciona cuatro tipos de notificación: `success`, `warning`, `info` y `error`. Se definen por el campo `type` y se ignorarán otros valores. También se han registrado métodos para estos tipos que se pueden invocar directamente como en el ejemplo `open3` y `open4` sin pasar un campo `type`.
```html
<template>
<el-button
plain
@click="open1">
Success
</el-button>
<el-button
plain
@click="open2">
Warning
</el-button>
<el-button
plain
@click="open3">
Info
</el-button>
<el-button
plain
@click="open4">
Error
</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$notify({
title: 'Success',
message: 'This is a success message',
type: 'success'
});
},
open2() {
this.$notify({
title: 'Warning',
message: 'This is a warning message',
type: 'warning'
});
},
open3() {
this.$notify.info({
title: 'Info',
message: 'This is an info message'
});
},
open4() {
this.$notify.error({
title: 'Error',
message: 'This is an error message'
});
}
}
}
</script>
```
:::
### Posición personalizada
La notificación puede surgir de cualquier rincón que uno desee.
:::demo El atributo `position` define desde qué esquina se desliza la notificación. Puede ser `top-right`, `top-left`, `bottom-right` o `bottom-left`. Predeterminado: `top-right`.
```html
<template>
<el-button
plain
@click="open1">
Top Right
</el-button>
<el-button
plain
@click="open2">
Bottom Right
</el-button>
<el-button
plain
@click="open3">
Bottom Left
</el-button>
<el-button
plain
@click="open4">
Top Left
</el-button>
</template>
<script>
export default {
methods: {
open1() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the top right corner'
});
},
open2() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the bottom right corner',
position: 'bottom-right'
});
},
open3() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the bottom left corner',
position: 'bottom-left'
});
},
open4() {
this.$notify({
title: 'Custom Position',
message: 'I\'m at the top left corner',
position: 'top-left'
});
}
}
}
</script>
```
:::
### Desplazamiento
Personalizar el desplazamiento de notificación desde el borde de la pantalla.
:::demo Configure el atributo `offset` para personalizar el desplazamiento de la notificación desde el borde de la pantalla. Tenga en cuenta que cada instancia de la notificación del mismo momento debe tener el mismo desplazamiento.
```html
<template>
<el-button
plain
@click="open">
Notification with offset
</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$notify.success({
title: 'Success',
message: 'This is a success message',
offset: 100
});
}
}
}
</script>
```
:::
### Usando cadenas HTML
`message` soporta cadenas HTML.
:::demo Configure `dangerouslyUseHTMLString` a true y `message` se tratará como una cadena HTML.
```html
<template>
<el-button
plain
@click="open">
Use HTML String
</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$notify({
title: 'HTML String',
dangerouslyUseHTMLString: true,
message: '<strong>This is <i>HTML</i> string</strong>'
});
}
}
}
</script>
```
:::
:::warning
Aunque la propiedad `message` soporta cadenas HTML, el renderizado dinámico de HTML arbitrario en su sitio web puede ser muy peligroso porque puede conducir fácilmente a [ataques XSS](https://en.wikipedia.org/wiki/Cross-site_scripting). Por lo tanto, cuando `dangerouslyUseHTMLString` está a true, por favor asegúrese de que el contenido del mensaje es confiable, y **nunca** asigne `message` al contenido proporcionado por el usuario.
:::
### Ocultar boton de cerrar
Es posible ocultar el botón de cerrar
:::demo Configure el atributo `showClose` como `false` para que el usuario no pueda cerrar la notificación.
```html
<template>
<el-button
plain
@click="open">
Hide close button
</el-button>
</template>
<script>
export default {
methods: {
open() {
this.$notify.success({
title: 'Info',
message: 'This is a message without close button',
showClose: false
});
}
}
}
</script>
```
:::
### Método global
Element ha añadido un método global `$notify` para Vue.prototype. Así que en una instancia de vue se puede llamar `Notification` como lo hacemos en esta página.
### Importar localmente
Importar `Notification`:
```javascript
import { Notification } from 'element-ui';
```
En este caso, debe llamar a `Notification(options)`. También se han registrado métodos para diferentes tipos, e.j. `Notification.success(options)`. Puede llamar al método `Notification.closeAll()` para cerrar manualmente todas las instancias.
### Opciones
| Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
| ------------------------ | ------------------------------------------------------------ | ---------------- | ------------------------------------------- | ----------- |
| title | titulo | string | — | — |
| message | mensaje | string/Vue.VNode | — | — |
| dangerouslyUseHTMLString | si `message` es tratado como una cadena HTML | boolean | — | false |
| type | tipo de notificación | string | success/warning/info/error | — |
| iconClass | clase personalizada de icono. Será anulado por `type` | string | — | — |
| customClass | nombre de clase personalizado para la notificación | string | — | — |
| duration | duración antes de cerrar. Si no se quiere que se cierre automáticamente este valor debe estar a 0 | number | — | 4500 |
| position | posición personalizada | string | top-right/top-left/bottom-right/bottom-left | top-right |
| showClose | si se muestra el botón de cerrar | boolean | — | true |
| onClose | función que se ejecuta cuando la notificación se cierra | function | — | — |
| onClick | función que se ejecuta cuando se hace clic en la notificación | function | — | — |
| offset | desplazamiento desde el borde superior de la pantalla. Cada instancia de notificación del mismo momento debe tener siempre el mismo desplazamiento. | number | — | 0 |
### Métodos
`Notification` y `this.$notify` devuelven la instancia de la notificación actual. Para cerrar manualmente la instancia, se puede llamar `close` para ello.
| Método | Descripción |
| ------ | ---------------------- |
| close | cierra la notificación |

View File

@@ -0,0 +1,39 @@
## PageHeader
Si la ruta de la página es simple, se recomienda utilizar PageHeader en lugar de Breadcrumb.
### Básico
:::demo
```html
<el-page-header @back="goBack" content="detail">
</el-page-header>
<script>
export default {
methods: {
goBack() {
console.log('go back');
}
}
}
</script>
```
:::
### Atributos
| Atributos | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |------------------------------ | ------ |
| title | titulo principal | string | — | Back |
| content | contenido | string | — | — |
### Eventos
| Nombre evento | Descripción | Parámetros |
|----------- |-------------- |----------- |
| back | se activa cuando se hace clic en el lado derecho | — |
### Slots
| Nombre del slot | Descripción |
| --------------- | ----------- |
| title | titulo |
| content | contenido |

Some files were not shown because too many files have changed in this diff Show More