Merge branch 'es-doc' into es-doc

pull/8123/head
杨奕 2017-11-16 18:30:12 +08:00 committed by GitHub
commit 8d6950faaa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
73 changed files with 1909 additions and 1391 deletions

View File

@ -6,7 +6,7 @@
"expect": true, "expect": true,
"sinon": true "sinon": true
}, },
"plugins": ['vue'], "plugins": ['vue','json'],
"extends": 'elemefe', "extends": 'elemefe',
"parserOptions": { "parserOptions": {
"ecmaFeatures": { "ecmaFeatures": {

View File

@ -8,7 +8,7 @@ We are excited that you are interested in contributing to Element. Before submit
## Issue Guidelines ## Issue Guidelines
- Issues are exclusively for bug reports, feature requests and design-related topics. Other questions may be closed directly. If any questions come up when you are using Element, please hit [Gitter](https://gitter.im/ElemeFE/element) for help. - Issues are exclusively for bug reports, feature requests and design-related topics. Other questions may be closed directly. If any questions come up when you are using Element, please hit [Gitter](https://gitter.im/element-en/Lobby) for help.
- Before submitting an issue, please check if similar problems have already been issued. - Before submitting an issue, please check if similar problems have already been issued.

View File

@ -1,5 +1,15 @@
## Changelog ## Changelog
### 2.0.4
*2017-11-10*
- Improved accessibility for Cascader, Dropdown, Message, Notification, Popover, Tooltip and Tree
- Fixed Container resize when the width of viewport decreases, #8042
- Fixed Tree's `updateKeyChildren` incorrectly deleting child nodes, #8100
- Fixed bordered CheckboxButton's height when nested in a Form, #8100
- Fixed Menu's parsing error for custom colors, #8153 (by @zhouyixiang)
### 2.0.3 ### 2.0.3
*2017-11-03* *2017-11-03*

View File

@ -1,5 +1,15 @@
## 更新日志 ## 更新日志
### 2.0.4
*2017-11-10*
- 提升 Cascader、Dropdown、Message、Notification、Popover、Tooltip、Tree 的可访问性
- 修复当视口变窄时 Container 无法同步更新其宽度的问题,#8042
- 修复 Tree 的 `updateKeyChildren` 在删除子节点时的行为错误,#8100
- 修复带有边框的 CheckboxButton 在 Form 中高度错误的问题,#8100
- 修复 Menu 在解析自定义颜色时的错误,#8153by @zhouyixiang
### 2.0.3 ### 2.0.3
*2017-11-03* *2017-11-03*

42
FAQ.md
View File

@ -36,27 +36,6 @@
请阅读 Vue 文档 [Render Function](http://vuejs.org/v2/guide/render-function.html) 的相关内容。注意,使用 JSX 来写 Render Function 的话,需要安装 `babel-plugin-transform-vue-jsx`,并参照其[文档](https://github.com/vuejs/babel-plugin-transform-vue-jsx)进行配置。 请阅读 Vue 文档 [Render Function](http://vuejs.org/v2/guide/render-function.html) 的相关内容。注意,使用 JSX 来写 Render Function 的话,需要安装 `babel-plugin-transform-vue-jsx`,并参照其[文档](https://github.com/vuejs/babel-plugin-transform-vue-jsx)进行配置。
</details> </details>
<details>
<summary>如何使用第三方图标库?</summary>
只要修改第三方图标库的前缀(具体方法参阅第三方库的文档),并编写相应的 CSS即可在 Element 中像使用内置图标一样使用第三方图标。例如,将第三方库的前缀改为 `el-icon-my`,然后在其 CSS 文件中添加:
```css
[class^="el-icon-my"], [class*=" el-icon-my"] {
font-family:"your-font-family" !important;
/* 以下内容参照第三方图标库本身的规则 */
font-size: inherit;
font-style:normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
```
具体使用时,和 Element 内置的图标用法一样。比如在 `el-input` 中:
```html
<el-input icon="my-xxx" />
```
</details>
<details> <details>
<summary>所有组件的任意属性都支持 `.sync` 修饰符吗?</summary> <summary>所有组件的任意属性都支持 `.sync` 修饰符吗?</summary>
@ -129,27 +108,6 @@ The parameter `row` is the data object of corresponding row.
Please refer to [Render Function](http://vuejs.org/v2/guide/render-function.html) in Vue's documentation. In addition, if you are writing render functions with JSX, `babel-plugin-transform-vue-jsx` is required. See [here](https://github.com/vuejs/babel-plugin-transform-vue-jsx) for its configurations. Please refer to [Render Function](http://vuejs.org/v2/guide/render-function.html) in Vue's documentation. In addition, if you are writing render functions with JSX, `babel-plugin-transform-vue-jsx` is required. See [here](https://github.com/vuejs/babel-plugin-transform-vue-jsx) for its configurations.
</details> </details>
<details>
<summary>How do I use third-party icon font library with Element?</summary>
You just need to modify the class name prefix of the third-party library (see their docs for how to do it), and write some CSS, then you can use them just like you use Element built-in icons. For example, change the prefix to `el-icon-my`, and then add the following to its CSS:
```css
[class^="el-icon-my"], [class*=" el-icon-my"] {
font-family:"your-font-family" !important;
/* The following is based on original CSS rules of third-party library */
font-size: inherit;
font-style:normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
```
Now you can use them as you do with built-in icons. For example, in `el-input`:
```html
<el-input icon="my-xxx" />
```
</details>
<details> <details>
<summary>Can I use `.sync` modifier on every attribute?</summary> <summary>Can I use `.sync` modifier on every attribute?</summary>

View File

@ -191,7 +191,6 @@
const lang = location.hash.replace('#', '').split('/')[1] || 'zh-CN'; const lang = location.hash.replace('#', '').split('/')[1] || 'zh-CN';
const localize = lang => { const localize = lang => {
console.log(lang);
switch (lang) { switch (lang) {
case 'zh-CN': case 'zh-CN':
use(zhLocale); use(zhLocale);
@ -232,6 +231,7 @@
const preferGithub = localStorage.getItem('PREFER_GITHUB'); const preferGithub = localStorage.getItem('PREFER_GITHUB');
if (href.indexOf('element-cn') > -1 || preferGithub) return; if (href.indexOf('element-cn') > -1 || preferGithub) return;
setTimeout(() => { setTimeout(() => {
if (this.lang !== 'zh-CN') return;
this.$confirm('建议大陆用户访问部署在国内的站点,是否跳转?', '提示') this.$confirm('建议大陆用户访问部署在国内的站点,是否跳转?', '提示')
.then(() => { .then(() => {
location.href = location.href.replace('element.', 'element-cn.'); location.href = location.href.replace('element.', 'element-cn.');
@ -249,12 +249,12 @@
this.suggestJump(); this.suggestJump();
} }
setTimeout(() => { setTimeout(() => {
const notified = localStorage.getItem('RELEASE_NOTIFIED'); const notified = localStorage.getItem('ES_NOTIFIED');
if (!notified) { if (!notified && this.lang !== 'zh-CN') {
const h = this.$createElement; const h = this.$createElement;
const title = this.lang === 'zh-CN' const title = this.lang === 'zh-CN'
? '2.0 正式发布' ? '帮助我们完成西班牙语文档'
: '2.0 available now'; : 'Help us with Spanish docs';
const messages = this.lang === 'zh-CN' const messages = this.lang === 'zh-CN'
? ['点击', '这里', '查看详情'] ? ['点击', '这里', '查看详情']
: ['Click ', 'here', ' to learn more']; : ['Click ', 'here', ' to learn more'];
@ -266,13 +266,13 @@
h('a', { h('a', {
attrs: { attrs: {
target: '_blank', target: '_blank',
href: `https://github.com/ElemeFE/element/issues/${ this.lang === 'zh-CN' ? '7755' : '7756' }` href: 'https://github.com/ElemeFE/element/issues/8074'
} }
}, messages[1]), }, messages[1]),
messages[2] messages[2]
]), ]),
onClose() { onClose() {
localStorage.setItem('RELEASE_NOTIFIED', 1); localStorage.setItem('ES_NOTIFIED', 1);
} }
}); });
} }

View File

@ -101,6 +101,7 @@
value8: '', value8: '',
value9: [], value9: [],
value10: [], value10: [],
value11: [],
loading: false, 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"] 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"]
}; };
@ -320,7 +321,7 @@ You can clear Select using a clear icon.
Multiple select uses tags to display selected options. 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. :::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 ```html
<template> <template>
<el-select v-model="value5" multiple placeholder="Select"> <el-select v-model="value5" multiple placeholder="Select">
@ -331,6 +332,20 @@ Multiple select uses tags to display selected options.
:value="item.value"> :value="item.value">
</el-option> </el-option>
</el-select> </el-select>
<el-select
v-model="value11"
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> </template>
<script> <script>
@ -650,6 +665,7 @@ If the binding value of Select is an object, make sure to assign `value-key` as
| value-key | unique identity key name for value, required when value is an object | string | — | value | | value-key | unique identity key name for value, required when value is an object | string | — | value |
| size | size of Input | string | large/small/mini | — | | size | size of Input | string | large/small/mini | — |
| clearable | whether single select can be cleared | boolean | — | false | | clearable | whether single 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 | | 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 | — | — | | name | the name attribute of select input | string | — | — |
| placeholder | placeholder | string | — | Select | | placeholder | placeholder | string | — | Select |

View File

@ -3,8 +3,8 @@
module.exports = { module.exports = {
data() { data() {
return { return {
checkList: ['selected and disabled','Option A'], checkList: ['seleccionado y deshabilitado','Opción A'],
// checkList2: ['Option A'], // checkList2: ['Opción A'],
checked: true, checked: true,
checked1: false, checked1: false,
checked2: true, checked2: true,
@ -45,18 +45,18 @@
## Checkbox ## Checkbox
A group of options for multiple choices. Un grupo de opciones para manejar múltiples elecciones.
### Basic usage ### Uso básico
Checkbox can be used alone to switch between two states. Checkbox puede ser usado para alternar entre dos estados.
:::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. :::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 ```html
<template> <template>
<!-- `checked` should be true or false --> <!-- `checked` debe ser true o false -->
<el-checkbox v-model="checked">Option</el-checkbox> <el-checkbox v-model="checked">Opción</el-checkbox>
</template> </template>
<script> <script>
export default { export default {
@ -70,16 +70,16 @@ Checkbox can be used alone to switch between two states.
``` ```
::: :::
### Disabled State ### Estado Deshabilitado
Disabled state for checkbox. Estado deshabilitado para el checkbox.
::: demo Set the `disabled` attribute. ::: demo Setear el atributo `disabled`.
```html ```html
<template> <template>
<el-checkbox v-model="checked1" disabled>Option</el-checkbox> <el-checkbox v-model="checked1" disabled>Opción</el-checkbox>
<el-checkbox v-model="checked2" disabled>Option</el-checkbox> <el-checkbox v-model="checked2" disabled>Opción</el-checkbox>
</template> </template>
<script> <script>
export default { export default {
@ -94,20 +94,20 @@ Disabled state for checkbox.
``` ```
::: :::
### Checkbox group ### Grupo de Checkboxes
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. Es usado por multiples checkboxes los cuales están enlazados a un grupo, indica si una opción está seleccionada verificando si esta está marcada.
:::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. :::demo El elemento `checkbox-group` puede manejar multiples 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 ```html
<template> <template>
<el-checkbox-group v-model="checkList"> <el-checkbox-group v-model="checkList">
<el-checkbox label="Option A"></el-checkbox> <el-checkbox label="Opción A"></el-checkbox>
<el-checkbox label="Option B"></el-checkbox> <el-checkbox label="Opción B"></el-checkbox>
<el-checkbox label="Option C"></el-checkbox> <el-checkbox label="Opción C"></el-checkbox>
<el-checkbox label="disabled" disabled></el-checkbox> <el-checkbox label="disabled" disabled></el-checkbox>
<el-checkbox label="selected and disabled" disabled></el-checkbox> <el-checkbox label="Seleccionado y deshabilitado" disabled></el-checkbox>
</el-checkbox-group> </el-checkbox-group>
</template> </template>
@ -115,7 +115,7 @@ It is used for multiple checkboxes which are bound in one group, and indicates w
export default { export default {
data () { data () {
return { return {
checkList: ['selected and disabled','Option A'] checkList: ['Seleccionado y deshabilitado','Opción A']
}; };
} }
}; };
@ -123,15 +123,15 @@ It is used for multiple checkboxes which are bound in one group, and indicates w
``` ```
::: :::
### Indeterminate ### Indeterminado
The `indeterminate` property can help you to achieve a 'check all' effect. La propiedad `indeterminate` puede ser usada para generar el efecto de marcar todos (check all).
:::demo :::demo
```html ```html
<template> <template>
<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">Check all</el-checkbox> <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">Marcar todos</el-checkbox>
<div style="margin: 15px 0;"></div> <div style="margin: 15px 0;"></div>
<el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange"> <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
<el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox> <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
@ -164,9 +164,9 @@ The `indeterminate` property can help you to achieve a 'check all' effect.
``` ```
::: :::
### Minimum / Maximum items checked ### Cantidad Mínima / Máxima de elementos seleccionados
The `min` and `max` properties can help you to limit the number of checked items. Las propiedades `min` y `max` pueden limitar la cantidad de elementos seleccionados.
:::demo :::demo
@ -193,11 +193,11 @@ The `min` and `max` properties can help you to limit the number of checked items
``` ```
::: :::
### Button style ### Estilo tipo Botón
Checkbox with button styles. Checkbox con estilo tipo Botón.
:::demo You just need to change `el-checkbox` element into `el-checkbox-button` element. We also provide `size` attribute. :::demo Sólo debes cambiar el elemento `el-checkbox` por el elemento `el-checkbox-button`. También proveemos el atributo `size`.
```html ```html
<template> <template>
<div> <div>
@ -239,29 +239,29 @@ Checkbox with button styles.
``` ```
::: :::
### With borders ### Con bordes
:::demo The `border` attribute adds a border to Checkboxes. :::demo El atributo `border` agrega un borde a los Checkboxes.
```html ```html
<template> <template>
<div> <div>
<el-checkbox v-model="checked3" label="Option1" border></el-checkbox> <el-checkbox v-model="checked3" label="Opción1" border></el-checkbox>
<el-checkbox v-model="checked4" label="Option2" border></el-checkbox> <el-checkbox v-model="checked4" label="Opción2" border></el-checkbox>
</div> </div>
<div style="margin-top: 20px"> <div style="margin-top: 20px">
<el-checkbox v-model="checked5" label="Option1" border size="medium"></el-checkbox> <el-checkbox v-model="checked5" label="Opción1" border size="medium"></el-checkbox>
<el-checkbox v-model="checked6" label="Option2" border size="medium"></el-checkbox> <el-checkbox v-model="checked6" label="Opción2" border size="medium"></el-checkbox>
</div> </div>
<div style="margin-top: 20px"> <div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup5" size="small"> <el-checkbox-group v-model="checkboxGroup5" size="small">
<el-checkbox label="Option1" border></el-checkbox> <el-checkbox label="Opción1" border></el-checkbox>
<el-checkbox label="Option2" border disabled></el-checkbox> <el-checkbox label="Opción2" border disabled></el-checkbox>
</el-checkbox-group> </el-checkbox-group>
</div> </div>
<div style="margin-top: 20px"> <div style="margin-top: 20px">
<el-checkbox-group v-model="checkboxGroup6" size="mini" disabled> <el-checkbox-group v-model="checkboxGroup6" size="mini" disabled>
<el-checkbox label="Option1" border></el-checkbox> <el-checkbox label="Opción1" border></el-checkbox>
<el-checkbox label="Option2" border></el-checkbox> <el-checkbox label="Opción2" border></el-checkbox>
</el-checkbox-group> </el-checkbox-group>
</div> </div>
</template> </template>
@ -283,45 +283,45 @@ Checkbox with button styles.
``` ```
::: :::
### Checkbox Attributes ### Atributos de Checkbox
| Attribute | Description | Type | Options | Default| | Atributo | Descripción | Tipo | Opciones | Por defecto|
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| label | value of the Checkbox when used inside a `checkbox-group` | string / number / boolean | — | — | | label | valor del Checkbox si es usado dentro de un tag `checkbox-group` | string / number / boolean | — | — |
| true-label | value of the Checkbox if it's checked | string / number | — | — | | true-label | valor del Checkbox si está marcado | string / number | — | — |
| false-label | value of the Checkbox if it's not checked | string / number | — | — | | false-label | valor del Checkbox si no está marcado | string / number | — | — |
| disabled | whether the Checkbox is disabled | boolean | — | false | | disabled | especifica si el Checkbox está deshabilitado | boolean | — | false |
| border | whether to add a border around Checkbox | boolean | — | false | | border | especifica si agrega un borde alrededor del Checkbox | boolean | — | false |
| size | size of the Checkbox, only works when `border` is true | string | medium / small / mini | — | | size | tamaño del Checkbox, sólo funciona si `border` es true | string | medium / small / mini | — |
| name | native 'name' attribute | string | — | — | | name | atributo 'name' nativo | string | — | — |
| checked | if the Checkbox is checked | boolean | — | false | | checked | especifica si el Checkbox está marcado | boolean | — | false |
| indeterminate | same as `indeterminate` in native checkbox | boolean | — | false | | indeterminate | similar a `indeterminate` en el checkbox nativo | boolean | — | false |
### Checkbox Events ### Eventos de Checkbox
| Event Name | Description | Parameters | | Nombre | Descripción | Parametros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| change | triggers when the binding value changes | the updated value | | change | se ejecuta cuando el valor enlazado cambia | el valor actualizado |
### Checkbox-group Attributes ### Atributos de Checkbox-group
| Attribute | Description | Type | Options | Default| | Atributo | Descripción | Tipo | Opciones | Por Defecto|
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
|size | size of checkbox buttons or bordered checkboxes | string | medium / small / mini | — | |size | tamaño de los checkboxes de tipo botón o los checkboxes con border | string | medium / small / mini | — |
| disabled | whether the nesting checkboxes are disabled | boolean | — | false | | disabled | especifica si los checkboxes anidados están deshabilitados | boolean | — | false |
| min | minimum number of checkbox checked | number | — | — | | min | cantidad mínima de checkboxes que deben ser marcados | number | — | — |
| max | maximum number of checkbox checked | number | — | — | | max | cantidad máxima de checkboxes que pueden ser marcados | number | — | — |
|text-color | font color when button is active | string | — | #ffffff | |text-color | color de fuente cuando el botón está activo | string | — | #ffffff |
|fill | border and background color when button is active | string | — | #409EFF | |fill | color de border y de fondo cuando el botón está activo | string | — | #409EFF |
### Checkbox-group Events ### Eventos de Checkbox-group
| Event Name | Description | Parameters | | Nombre de Evento | Descripción | Parametros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| change | triggers when the binding value changes | the updated value | | change | se ejecuta cuando el valor enlazado cambia | el valor actualizado |
### Checkbox-button Attributes ### Atributos de Checkbox-button
| Attribute | Description | Type | Options | Default| | Atributo | Descripción | Tipo | Opciones | Por defecto|
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| label | value of the checkbox when used inside a `checkbox-group` | string / number / boolean | — | — | | label | valor del checkbox cuando es usado dentro de un `checkbox-group` | string / number / boolean | — | — |
| true-label | value of the checkbox if it's checked | string / number | — | — | | true-label | valor del checkbox si este está marcado | string / number | — | — |
| false-label | value of the checkbox if it's not checked | string / number | — | — | | false-label | valor del checkbox si este no está marcado | string / number | — | — |
| disabled | whether the checkbox is disabled | boolean | — | false | | disabled | especifica si el checkbox está deshabilitado | boolean | — | false |
| name | native 'name' attribute | string | — | — | | name | atributo 'name' del checbox nativo | string | — | — |
| checked | if the checkbox is checked | boolean | — | false | | checked | si el checkbox está marcado | boolean | — | false |

View File

@ -26,11 +26,11 @@
## Collapse ## Collapse
Use Collapse to store contents. Use Collapse para almacenar contenidos.
### Basic usage ### Uso básico
You can expand multiple panels Puedes expandir varios paneles
:::demo :::demo
```html ```html
@ -65,11 +65,11 @@ You can expand multiple panels
``` ```
::: :::
### Accordion ### Acordeón
In accordion mode, only one panel can be expanded at once En modo acordeón sólo un panel puede ser expandido a la vez
:::demo Activate accordion mode using the `accordion` attribute. :::demo Activa el modo acordeón usado el atributo `accordion`.
```html ```html
<el-collapse v-model="activeName" accordion> <el-collapse v-model="activeName" accordion>
<el-collapse-item title="Consistency" name="1"> <el-collapse-item title="Consistency" name="1">
@ -102,9 +102,9 @@ In accordion mode, only one panel can be expanded at once
``` ```
::: :::
### Custom title ### Título personalizado
Besides using the `title` attribute, you can customize panel title with named slots, which makes adding custom content, e.g. icons, possible. Además de usar el atributo `title`, se puede personalizar el título del panel con named slots, esto hace posible agregar contenido personalizado, por ejemplo: iconos.
:::demo :::demo
```html ```html
@ -133,19 +133,20 @@ Besides using the `title` attribute, you can customize panel title with named sl
``` ```
::: :::
### Collapse Attributes ### Atributos de Collapse
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por Defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| accordion | whether to activate accordion mode | boolean | — | false | | accordion | especifica si activa el modo acordeón | boolean | — | false |
| value | currently active panel | string (accordion mode)/array (non-accordion mode) | — | — | | value | panel activo | string (modo acordeón)/array (No modo acordeón) | — | — |
### Collapse Events ### Eventos de Collapse
| Event Name | Description | Parameters | | Nombre de Evento | Descripción | Parametros |
|---------|---------|---------| |---------|---------|---------|
| change | triggers when active panels change | activeNames: array (non-accordion mode)/string (accordion mode) | | change | se dispara cuando los paneles activos cambian | activeNames: array (No modo acordeón)/string (modo acordeón) |
### Collapse Item Attributes
| Attribute | Description | Type | Accepted Values | Default | ### Atributos de Collapse Item
| Atributo | Descripción | Tipo | Valores aceptados | Por Defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| name | unique identification of the panel | string/number | — | — | | name | identificador único del panel | string/number | — | — |
| title | title of the panel | string | — | — | | title | título del panel | string | — | — |

View File

@ -42,18 +42,18 @@
## ColorPicker ## ColorPicker
ColorPicker is a color selector supporting multiple color formats. ColorPicker es un selector de color que soporta varios formatos de color.
### Basic usage ### Uso básico
:::demo ColorPicker requires a string typed variable to be bound to v-model. :::demo ColorPicker requiere una variable de tipo string para ser enlazada a v-model.
```html ```html
<div class="block"> <div class="block">
<span class="demonstration">With default value</span> <span class="demonstration">Especifica valor por defecto</span>
<el-color-picker v-model="color1"></el-color-picker> <el-color-picker v-model="color1"></el-color-picker>
</div> </div>
<div class="block"> <div class="block">
<span class="demonstration">With no default value</span> <span class="demonstration">No especifica valor por defecto</span>
<el-color-picker v-model="color2"></el-color-picker> <el-color-picker v-model="color2"></el-color-picker>
</div> </div>
@ -72,7 +72,7 @@ ColorPicker is a color selector supporting multiple color formats.
### Alpha ### Alpha
:::demo ColorPicker supports alpha channel selecting. To activate alpha selecting, just add the `show-alpha` attribute. :::demo ColorPicker soporta selección de canales alpha. Para activarlo sólo agrega el atributo `show-alpha`.
```html ```html
<el-color-picker v-model="color3" show-alpha></el-color-picker> <el-color-picker v-model="color3" show-alpha></el-color-picker>
@ -109,17 +109,17 @@ ColorPicker is a color selector supporting multiple color formats.
``` ```
::: :::
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| disabled | whether to disable the ColorPicker | boolean | — | false | | disabled | especifica si se deshabilita el ColorPicker | boolean | — | false |
| size | size of ColorPicker | string | — | medium / small / mini | | size | tamaño del ColorPicker | string | — | medium / small / mini |
| show-alpha | whether to display the alpha slider | boolean | — | false | | show-alpha | especifica si se muestra el control deslizante para el valor alpha | 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) | | 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 | custom class name for ColorPicker's dropdown | string | — | — | | popper-class | nombre de clase para el dropdown del ColorPicker | string | — | — |
### Events ### Eventos
| Event Name | Description | Parameters | | Nombre de Evento | Descripción | Parametros |
|---------|--------|---------| |---------|--------|---------|
| change | triggers when input value changes | color value | | change | se dispara cuando el valor del input cambia | valor del color |
| active-change | triggers when the current active color changes | active color value | | active-change | se dispara cuando el actual color activo cambia | valor del color activo |

View File

@ -9,7 +9,7 @@
color: #333; color: #333;
} }
#common-layouts + .demo-container { #disenos-comunes + .demo-container {
.el-header, .el-footer { .el-header, .el-footer {
text-align: center; text-align: center;
} }
@ -57,76 +57,78 @@
}; };
</script> </script>
## Container ## Contenedor
Container components for scaffolding basic structure of the page: Componentes contenedores para iniciar una estructura básica de un sitio:
`<el-container>`: wrapper container. When nested with a `<el-header>` or `<el-footer>`, all its child elements will be vertically arranged. Otherwise horizontally. `<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>`: container for headers. `<el-header>`: Contenedor para cabeceras.
`<el-aside>`: container for side sections (usually a side nav). `<el-aside>`: Contenedor para secciones laterales (generalmente, una barra lateral).
`<el-main>`: container for main sections. `<el-main>`: Contenedor para sección principal.
`<el-footer>`: container for footers. `<el-footer>`: Contenedor para pie de página.
:::tip :::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>`. Estos componentes utilizan flex para el diseño, así que asegúrate que el navegador lo soporte. 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>`.
::: :::
### Common layouts ### Diseños comunes
::: demo ::: demo
```html ```html
<el-container> <el-container>
<el-header>Header</el-header> <el-header>Cabecera</el-header>
<el-main>Main</el-main> <el-main>Principal</el-main>
</el-container> </el-container>
<el-container> <el-container>
<el-header>Header</el-header> <el-header>Cabecera</el-header>
<el-main>Main</el-main> <el-main>Principal</el-main>
<el-footer>Footer</el-footer> <el-footer>Pie de página</el-footer>
</el-container> </el-container>
<el-container> <el-container>
<el-aside width="200px">Aside</el-aside> <el-aside width="200px">Barra lateral</el-aside>
<el-main>Main</el-main> <el-main>Principal</el-main>
</el-container> </el-container>
<el-container> <el-container>
<el-header>Header</el-header> <el-header>Cabecera</el-header>
<el-container> <el-container>
<el-aside width="200px">Aside</el-aside> <el-aside width="200px">Barra lateral</el-aside>
<el-main>Main</el-main> <el-main>Principal</el-main>
</el-container> </el-container>
</el-container> </el-container>
<el-container> <el-container>
<el-header>Header</el-header> <el-header>Cabecera</el-header>
<el-container> <el-container>
<el-aside width="200px">Aside</el-aside> <el-aside width="200px">Barra lateral</el-aside>
<el-container> <el-container>
<el-main>Main</el-main> <el-main>Principal</el-main>
<el-footer>Footer</el-footer> <el-footer>Pie de página</el-footer>
</el-container> </el-container>
</el-container> </el-container>
</el-container> </el-container>
<el-container> <el-container>
<el-aside width="200px">Aside</el-aside> <el-aside width="200px">Barra lateral</el-aside>
<el-container> <el-container>
<el-header>Header</el-header> <el-header>Cabecera</el-header>
<el-main>Main</el-main> <el-main>Principal</el-main>
</el-container> </el-container>
</el-container> </el-container>
<el-container> <el-container>
<el-aside width="200px">Aside</el-aside> <el-aside width="200px">Barra lateral</el-aside>
<el-container> <el-container>
<el-header>Header</el-header> <el-header>Cabecera</el-header>
<el-main>Main</el-main> <el-main>Principal</el-main>
<el-footer>Footer</el-footer> <el-footer>Pie de página</el-footer>
</el-container> </el-container>
</el-container> </el-container>
@ -168,7 +170,7 @@ These components use flex for layout, so please make sure your browser supports
``` ```
::: :::
### Example ### Ejemplo
::: demo ::: demo
```html ```html
@ -278,22 +280,22 @@ These components use flex for layout, so please make sure your browser supports
``` ```
::: :::
### Container Attributes ### Atributos de contenedor
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| direction | layout direction for child elements | string | horizontal / vertical | vertical when nested with `el-header` or `el-footer`; horizontal otherwise | | 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 |
### Header Attributes ### Atributos de cabecera
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| height | height of the header | string | — | 60px | | height | altura de la cabecera | string | — | 60px |
### Aside Attributes ### Atributos de barra lateral
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| width | width of the side section | string | — | 300px | | width | ancho de la barra lateral | string | — | 300px |
### Footer Attributes ### Atributos de pie de página
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| height | height of the footer | string | — | 60px | | height | altura del pie de página | string | — | 60px |

View File

@ -1,25 +1,25 @@
## Custom theme ## Tema personalizado
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 three ways to change the style variables. Element utiliza la metodología BEM en CSS con la finalidad de que puedas sobrescribir los estilos fácilmente. Pero, si necesitas 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, por ello, te proporcionamos 3 maneras de modificar los estilos.
### Changing theme color ### Cambiando el color del tema
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. Si lo que buscas 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.
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). Este sitio, te 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, consulta la sección Importar un tema personalizado o Importar un tema de componente bajo demanda' que se encuentran dentro de esta sección).
### Update SCSS variables in your project ### Actualizando variables SCSS en tu proyecto
`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`: `theme-chalk` esta escrito en SCSS. Si tu proyecto también utiliza SCSS, puedes cambiar las variables de estilos de Element. Para ello, solo necesitas crear un nuevo archivo de estilos, por ejemplo, `element-variables.scss`:
```html ```html
/* theme color */ /* Color del tema */
$--color-primary: teal; $--color-primary: teal;
/* icon font path, required */ /* Ubicación de la fuente, obligatoria */
$--font-path: '../node_modules/element-ui/lib/theme-chalk/fonts'; $--font-path: '../node_modules/element-ui/lib/theme-chalk/fonts';
@import "../node_modules/element-ui/packages/theme-chalk/src/index"; @import "../node_modules/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: Entonces, en el archivo principal del proyecto, importa este archivo de estilos en lugar de los estilos de Element:
```JS ```JS
import Vue from 'vue' import Vue from 'vue'
import Element from 'element-ui' import Element from 'element-ui'
@ -29,29 +29,29 @@ Vue.use(Element)
``` ```
:::tip :::tip
Note that it is required to override icon font path to the relative path of Element's font files. Nota es necesario sobreescribir la ruta de la fuente por una ruta relativa de las fuentes de Element.
::: :::
### CLI theme tool ### CLI para generar temas
If you project doesn't use SCSS, you can customize themes with our CLI theme tool: Si tu proyecto no utiliza SCSS, puedes personalizar el tema a través de esta herramienta:
#### <strong>Install</strong> #### <strong>Instalación</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. Primero, debes 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 tu proyecto, npm automáticamente los instalará para ellos.
```shell ```shell
npm i element-theme -g npm i element-theme -g
``` ```
Then install the chalk theme from npm or GitHub. Ahora, instala el tema `chalk` desde npm o Github.
```shell ```shell
# from npm # desde npm
npm i element-theme-chalk -D npm i element-theme-chalk -D
# from GitHub # desde GitHub
npm i https://github.com/ElementUI/theme-chalk -D npm i https://github.com/ElementUI/theme-chalk -D
``` ```
#### <strong>Initialize variable file</strong> #### <strong>Inicializar archivo de variables</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. Después de haber instalado correctamente los paquetes, el comando `et` estará disponible en tu CLI (si instalaste el paquete de manera local, utilizá `node_modules/.bin/et` en su lugar). Ejecuta `-i` para inicializar un archivo de variables, puedes especificar un nombre distinto, pero por defecto, el archivo se llama `element-variables.scss`. También puedes especificar un directorio distinto.
```shell ```shell
et -i [custom output file] et -i [custom output file]
@ -59,7 +59,7 @@ et -i [custom output file]
> ✔ Generator variables 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: En el archivo `element-variables.scss` podrás encontrar todas las variables que utiliza Element para definir los estilos y estos están definidos en SCSS. Aquí un ejemplo:
```css ```css
$--color-primary: #409EFF !default; $--color-primary: #409EFF !default;
$--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */ $--color-primary-light-1: mix($--color-white, $--color-primary, 10%) !default; /* 53a8ff */
@ -80,14 +80,14 @@ $--color-info: #878d99 !default;
... ...
``` ```
#### <strong>Modify variables</strong> #### <strong>Modificando variables</strong>
Just edit `element-variables.scss`, e.g. changing the theme color to red: Solo debes modificar el archivo `element-variables.scss`, por ejemplo, para cambiar el color del tema a rojo:
```CSS ```CSS
$--color-primary: red; $--color-primary: red;
``` ```
#### <strong>Build theme</strong> #### <strong>Construyendo el tema</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: 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 deseas personalizar el nombre del archivo, debes agregar el parámetro `-c` seguido del nombre.
```shell ```shell
et et
@ -95,8 +95,8 @@ et
> ✔ build element theme > ✔ build element theme
``` ```
#### <strong>Import custom theme</strong> #### <strong>Importar un tema personalizado</strong>
By default the build theme file is placed inside `./theme`. You can specify its output directory with parameter `-o`. Importing your own theme is just like importing the default theme, only this time you import the file you just built: Por defecto, el archivo de tema construido es colocado dentro de `./theme`. Tu puedes especificar un directorio distinto utilizando el parámetro `-o`. Importar tu propio tema es igual a como si importarás el tema por defecto, únicamente tienes que importar el archivo que se construyó:
```javascript ```javascript
import '../theme/index.css' import '../theme/index.css'
@ -106,8 +106,8 @@ import Vue from 'vue'
Vue.use(ElementUI) Vue.use(ElementUI)
``` ```
#### <strong>Import component theme on demand</strong> #### <strong>Importar un tema de componente bajo demanda</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: Si estas utilizando `babel-plugin-component` para importar bajo demanda, solo debes modificar el archivo `.babelrc` y especificar en la propiedad `styleLibraryName` la ruta en donde se encuentra localizado tu tema personalizado relativo a `.babelrc`. Nota el carácter `~` es obligatorio:
```json ```json
{ {
"plugins": [["component", [ "plugins": [["component", [
@ -119,4 +119,4 @@ If you are using `babel-plugin-component` for on-demand import, just modify `.ba
} }
``` ```
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`. Si no estas familiarizado con `babel-plugin-component`, por favor dirígete a la documentación sobre <a href="./#/en-US/component/quickstart">Como Iniciar</a>. Para más detalles, consulta el [repositorio del proyecto](https://github.com/ElementUI/element-theme) de `element-theme`.

View File

@ -1,14 +1,14 @@
## Installation ## Instalación
### npm ### npm
Installing with npm is recommended and it works seamlessly with [webpack](https://webpack.js.org/). Instalar mediante npm es la forma recomendada ya que se integra facilmente con [webpack](https://webpack.js.org/).
```shell ```shell
npm i element-ui -S npm i element-ui -S
``` ```
### CDN ### CDN
Get the latest version from [unpkg.com/element-ui](https://unpkg.com/element-ui/) , and import JavaScript and CSS file in your page. Obten la última versión desde [unpkg.com/element-ui](https://unpkg.com/element-ui/) , e importa el JavaScript y los archivos CSS en tu página.
```html ```html
<!-- import CSS --> <!-- import CSS -->
@ -17,12 +17,12 @@ Get the latest version from [unpkg.com/element-ui](https://unpkg.com/element-ui/
<script src="https://unpkg.com/element-ui/lib/index.js"></script> <script src="https://unpkg.com/element-ui/lib/index.js"></script>
``` ```
:::tip ##Tip
We recommend our users to lock Element's version when using CDN. Please refer to [unpkg.com](https://unpkg.com) for more information. Recomendamos a nuestros usuarios congelar la versión de Elemet cuando usas un CDN. Por favor, refiérase a [unpkg.com](https://unpkg.com) para más información.
:::
### Hello world ### Hello world
If you are using CDN, a hello-world page is easy with Element. [Online Demo](https://jsfiddle.net/hzfpyvg6/14/) Si estás usando un CDN, una página con Hello-World es fácil con Element. [Online Demo](https://jsfiddle.net/hzfpyvg6/14/)
```html ```html
<!DOCTYPE html> <!DOCTYPE html>
@ -54,4 +54,5 @@ If you are using CDN, a hello-world page is easy with Element. [Online Demo](htt
</script> </script>
</html> </html>
``` ```
If you are using npm and wish to apply webpack, please continue to the next page: Quick Start. Si estás usando npm y deseas combinarlo con webpack, por favor continúa a la siguiente página: Quick Start

View File

@ -31,13 +31,13 @@
## Layout ## Layout
Quickly and easily create layouts with the basic 24-column. Rápido y facilmente crea un layout básico con 24 columnas.
### Basic layout ### Layout básico
Create basic grid layout using columns. Crea un layout básico usando columnas.
::: demo With `row` and `col`, we can easily manipulate the layout using the `span` attribute. :::**Demo** Con `row` y `col`, podemos facilmente manipular el layout usando el atributo `span`.
```html ```html
<el-row> <el-row>
<el-col :span="24"><div class="grid-content bg-purple-dark"></div></el-col> <el-col :span="24"><div class="grid-content bg-purple-dark"></div></el-col>
@ -97,11 +97,11 @@ Create basic grid layout using columns.
``` ```
::: :::
### Column spacing ### Espaciado de columnas
Column spacing is supported. El espaciado de columnas está soportado.
::: demo Row provides `gutter` attribute to specify spacings between columns, and its default value is 0. :::**Demo** Row provee el atributo `gutter` para especificar el espacio entre columnas y su valor por defecto es 0.
```html ```html
<el-row :gutter="20"> <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>
@ -141,11 +141,11 @@ Column spacing is supported.
``` ```
::: :::
### Hybrid layout ### Layout híbrido
Form a more complex hybrid layout by combining the basic 1/24 columns. Crea un complejo layout híbrido combinando el básico de 1/24 columnas.
::: demo :::**Demo**
```html ```html
<el-row :gutter="20"> <el-row :gutter="20">
<el-col :span="16"><div class="grid-content bg-purple"></div></el-col> <el-col :span="16"><div class="grid-content bg-purple"></div></el-col>
@ -194,11 +194,11 @@ Form a more complex hybrid layout by combining the basic 1/24 columns.
``` ```
::: :::
### Column offset ### Offset de columnas
You can specify column offsets. Puedes especificar offsets para las columnas.
::: demo You can specify the number of column offset by setting the value of `offset` attribute of Col. :::**Demo** Puedes especificar el offset para una columna mediante el atributo `offset` de Col.
```html ```html
<el-row :gutter="20"> <el-row :gutter="20">
@ -244,11 +244,11 @@ You can specify column offsets.
``` ```
::: :::
### Alignment ### Alineación
Use the flex layout to make flexible alignment of columns. Usa flex layout para un alineamiento flexible de columnas.
::: 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. :::**Demo** Puedes 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 ```html
<el-row type="flex" class="row-bg"> <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"></div></el-col>
@ -309,9 +309,9 @@ Use the flex layout to make flexible alignment of columns.
### Responsive Layout ### Responsive Layout
Taking example by Bootstrap's responsive design, five breakpoints are preset: xs, sm, md, lg and xl. Tomando el ejemplo de Bootstrap responsive design, existen 5 breakpoints: xs, sm, md, lg y xl.
::: demo :::**Demo**
```html ```html
<el-row :gutter="10"> <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="8" :sm="6" :md="4" :lg="3" :xl="1"><div class="grid-content bg-purple"></div></el-col>
@ -341,48 +341,50 @@ Taking example by Bootstrap's responsive design, five breakpoints are preset: xs
``` ```
::: :::
### Utility classes for hiding elements ### Clases útiles para ocultar elementos
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: 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. Necesitas importar el siguiente archivo CSS para usar estas clases:
```js ```js
import 'element-ui/lib/theme-chalk/display.css'; import 'element-ui/lib/theme-chalk/display.css';
``` ```
The classes are: Las clases son:
- `hidden-xs-only` - hide when on extra small viewports only - `hidden-xs-only` - oculto en viewports extra pequenhos solamente
- `hidden-sm-only` - hide when on small viewports and down - `hidden-sm-only` - oculto en viewports pequenhos solamente
- `hidden-sm-and-down` - hide when on small viewports and down - `hidden-sm-and-down` - oculto en viewports pequenhos y menores
- `hidden-sm-and-up` - hide when on small viewports and up - `hidden-sm-and-up` - oculto en viewports pequenhos y superiores
- `hidden-md-only` - hide when on medium viewports only - `hidden-md-only` - oculto en viewports medios solamente
- `hidden-md-and-down` - hide when on medium viewports and down - `hidden-md-and-down` - oculto en viewports medios y menores
- `hidden-md-and-up` - hide when on medium viewports and up - `hidden-md-and-up` - oculto en viewports medios y mayores
- `hidden-lg-only` - hide when on large viewports only - `hidden-lg-only` - ocultos en viewports grandes solamente
- `hidden-lg-and-down` - hide when on large viewports and down - `hidden-lg-and-down` - ocultos en viewports grandes y menores
- `hidden-lg-and-up` - hide when on large viewports and up - `hidden-lg-and-up` - ocultos en viewports grandes y superiores
- `hidden-xl-only` - hide when on extra large viewports only - `hidden-xl-only` - oculto en viewports extra grandes solamente
### Row Attributes ### Atributos Row
| Attribute | Description | Type | Accepted Values | Default |
| Atributos | Descripción | Tipo | Valores aceptados | Valor por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| gutter | grid spacing | number | — | 0 | | gutter | espaciado de la grilla | number | — | 0 |
| type | layout mode, you can use flex, works in modern browsers | string | — | — | | type | modo del layout , puedes usar flex, funciona en navegadores modernos| string | — | — |
| justify | horizontal alignment of flex layout | string | start/end/center/space-around/space-between | start | | justify | alineación horizontal del layout flex | string | start/end/center/space-around/space-between | start |
| align | vertical alignment of flex layout | string | top/middle/bottom | top | | align | alineación vertical del layout flex | string | top/middle/bottom | top |
| tag | custom element tag | string | * | div | | tag | tag de elemento propio | string | * | div |
### Col Attributes ### Atributos Col
| Attribute | Description | Type | Accepted Values | Default |
| Atributos | Descripción | Tipo | Valores aceptados | Valor por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| span | number of column the grid spans | number | — | 24 | | span | número de columnas que abarca la cuadrícula | number | — | 24 |
| offset | number of spacing on the left side of the grid | number | — | 0 | | offset | especific espacio en el lado izquierdo de la grill | number | — | 0 |
| push | number of columns that grid moves to the right | number | — | 0 | | push | número de columnas que la grilla se mueve hacia la derecha | number | — | 0 |
| pull | number of columns that grid moves to the left | number | — | 0 | | pull | número de columnas que la grilla se mueve hacia la izquierda | number | — | 0 |
| xs | `<768px` Responsive columns or column props object | number/object (e.g. {span: 4, offset: 4}) | — | — | | xs | `<768px` Columnas responsive u objeto con propiedades de la columna | number/object (e.g. {span: 4, offset: 4}) | — | — |
| sm | `≥768px` Responsive columns or column props object | 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` Responsive columns or column props object | 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` Responsive columns or column props object | 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` Responsive columns or column props object | 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 | custom element tag | string | * | div | | tag | tag de elemento propio | string | * | div |

View File

@ -49,15 +49,15 @@
} }
</script> </script>
## Loading ## Cargando
Show animation while loading data. Se muestra la animación mientras se cargan los datos.
### Loading inside a container ### Cargando dentro de un contenedor
Displays animation in a container (such as a table) while loading data. Muestra una animación en un contenedor (como en una tabla) mientras se cargan los datos.
:::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. :::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 ```html
<template> <template>
@ -67,17 +67,17 @@ Displays animation in a container (such as a table) while loading data.
style="width: 100%"> style="width: 100%">
<el-table-column <el-table-column
prop="date" prop="date"
label="Date" label="Fecha"
width="180"> width="180">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
prop="name" prop="name"
label="Name" label="Nombre"
width="180"> width="180">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
prop="address" prop="address"
label="Address"> label="Dirección">
</el-table-column> </el-table-column>
</el-table> </el-table>
</template> </template>
@ -113,11 +113,11 @@ Displays animation in a container (such as a table) while loading data.
``` ```
::: :::
### Customization ### Personalización
You can customize loading text, loading spinner and background color. Puedes personalizar el texto de carga, spinner de carga y color de fondo.
:::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. :::demo Agrega 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 ```html
<template> <template>
<el-table <el-table
@ -129,17 +129,17 @@ You can customize loading text, loading spinner and background color.
style="width: 100%"> style="width: 100%">
<el-table-column <el-table-column
prop="date" prop="date"
label="Date" label="Fecha"
width="180"> width="180">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
prop="name" prop="name"
label="Name" label="Nombre"
width="180"> width="180">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
prop="address" prop="address"
label="Address"> label="Dirección">
</el-table-column> </el-table-column>
</el-table> </el-table>
</template> </template>
@ -169,11 +169,11 @@ You can customize loading text, loading spinner and background color.
``` ```
::: :::
### Full screen loading ### Cargando a pantalla completa
Show a full screen animation while loading data. Muestra una animación de pantalla completa mientras se cargan los datos
:::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. :::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 deseas deshabilitas el desplazamiento en `body`, puedes agregar otro modificador `lock`. Cuando se utiliza como un servicio, el componente puede ser mostrado a pantalla completa por defecto.
```html ```html
<template> <template>
@ -181,12 +181,12 @@ Show a full screen animation while loading data.
type="primary" type="primary"
@click="openFullScreen" @click="openFullScreen"
v-loading.fullscreen.lock="fullscreenLoading"> v-loading.fullscreen.lock="fullscreenLoading">
As a directive Como directiva
</el-button> </el-button>
<el-button <el-button
type="primary" type="primary"
@click="openFullScreen2"> @click="openFullScreen2">
As a service Como servicio
</el-button> </el-button>
</template> </template>
@ -221,38 +221,40 @@ Show a full screen animation while loading data.
``` ```
::: :::
### Service ### Servicio
You can also invoke Loading with a service. Import Loading service:
Puedes invocar el componente con un servicio. Importa el servicio:
```javascript ```javascript
import { Loading } from 'element-ui'; import { Loading } from 'element-ui';
``` ```
Invoke it: Invocar:
```javascript ```javascript
Loading.service(options); 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: 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 tú puedes cerrarlo invocando el método `close`:
```javascript ```javascript
let loadingInstance = Loading.service(options); let loadingInstance = Loading.service(options);
loadingInstance.close(); 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: 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 ```javascript
let loadingInstance1 = Loading.service({ fullscreen: true }); let loadingInstance1 = Loading.service({ fullscreen: true });
let loadingInstance2 = Loading.service({ fullscreen: true }); let loadingInstance2 = Loading.service({ fullscreen: true });
console.log(loadingInstance1 === loadingInstance2); // true console.log(loadingInstance1 === loadingInstance2); // true
``` ```
Calling the `close` method on any one of them can close this full screen Loading. Llamar al método `close` en cualquiera de estas puede cerrarlo.
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. Si Element es importado completamente, un método global `$loading` puede ser registrado a Vue.prototype. Puedes invocarlo como esto: `this.$loading(options)`, y también devuelve una instancia del componente.
### Options ### Options
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Por defecto |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| 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 | | 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 | same as the `body` modifier of `v-loading` | boolean | — | false | | body | igual que el modificador `body` de `v-loading` | boolean | — | false |
| fullscreen | same as the `fullscreen` modifier of `v-loading` | boolean | — | true | | fullscreen | igual que el modificador `fullscreen` de `v-loading` | boolean | — | true |
| lock | same as the `lock` modifier of `v-loading` | boolean | — | false | | lock | igual que el modificador `lock` de `v-loading` | boolean | — | false |
| text | loading text that displays under the spinner | string | — | — | | text | texto de cargando que se muestra debajo del spinner | string | — | — |
| spinner | class name of the custom spinner | string | — | — | | spinner | nombre de clase del spinner personalizado | string | — | — |
| background | background color of the mask | string | — | — | | background | color de fondo de la máscara | string | — | — |
| customClass | custom class name for Loading | string | — | — | | customClass | nombre de clase personalizada para el componente | string | — | — |

View File

@ -53,13 +53,14 @@
## NavMenu ## NavMenu
Menu that provides navigation for your website. Menú que provee la navegación para tu sitio.
### Top bar ### Top bar
Top bar NavMenu can be used in a variety of scenarios. Top bar NavMenu puede ser usado en distinto escenarios.
:::**Demo** Por defecto el menú es vertical, pero puedes hacerlo horizontal asignando a la propiedad `mode` el valor 'horizontal'. Además, puedes 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.
::: 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 ```html
<el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect"> <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
<el-menu-item index="1">Processing Center</el-menu-item> <el-menu-item index="1">Processing Center</el-menu-item>
@ -110,9 +111,10 @@ Top bar NavMenu can be used in a variety of scenarios.
### Side bar ### Side bar
Vertical NavMenu with sub-menus. NavMenu vertical con sub-menús.
:::**Demo** Puedes 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`.
::: 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 ```html
<el-row class="tac"> <el-row class="tac">
<el-col :span="12"> <el-col :span="12">
@ -205,9 +207,9 @@ Vertical NavMenu with sub-menus.
### Collapse ### Collapse
Vertical NavMenu could be collapsed. NavMenu vertical puede ser colapsado.
::: demo :::**Demo**
```html ```html
<el-radio-group v-model="isCollapse" style="margin-bottom: 20px;"> <el-radio-group v-model="isCollapse" style="margin-bottom: 20px;">
<el-radio-button :label="false">expand</el-radio-button> <el-radio-button :label="false">expand</el-radio-button>
@ -269,50 +271,50 @@ Vertical NavMenu could be collapsed.
``` ```
::: :::
### Menu Attribute ### Atributos Menu
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Valores por defecto |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| mode | menu display mode | string | horizontal / vertical | vertical | | mode | modo de presentación del menú | string | horizontal / vertical | vertical |
| collapse | whether the menu is collapsed (available only in vertical mode) | boolean | — | false | | collapse | si el menú está colapsado (solo en modo vertical) | boolean | — | false |
| background-color | background color of Menu (hex format) | string | — | #ffffff | | background-color | color de fondo del menú (formato hexadecimal) | string | — | #ffffff |
| text-color | text color of Menu (hex format) | string | — | #2d2f33 | | text-color | color de texto del menú (formato hexadecimal) | string | — | #2d2f33 |
| active-text-color | text color of currently active menu item (hex format) | string | — | #409EFF | | active-text-color | color de text del menu-item activo (formato hexadecimal) | string | — | #409EFF |
| default-active | index of currently active menu | string | — | — | | default-active | índice del menu-item activo | string | — | — |
| default-openeds | array that contains keys of currently active sub-menus | Array | — | — | | default-openeds | arreglo que contiene las llaves del sub-menus activo | Array | — | — |
| unique-opened | whether only one sub-menu can be active | boolean | — | false | | 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 | | menu-trigger | como dispara eventos sub-menus, solo funciona cuando `mode` es 'horizontal' | string | — | hover |
| router | whether `vue-router` mode is activated. If true, index will be used as 'path' to activate the route action | boolean | — | false | | router | si el modo `vue-router` está activado. Si es verdader, índice será usado como 'path' para activar la ruta | boolean | — | false |
### Menu Methods ### Métodos Menu
| Event Name | Description | Parameters | | Nombre de evento | Descripción | Parámetros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| open | open a specific sub-menu | index: index of the sub-menu to open | | open | abre un sub-menu específico | index: índice del sub-menu para abrir |
| close | close a specific sub-menu | index: index of the sub-menu to close | | close | cierra un sub-menu específico | index: índice del sub-menu para cerrar |
### Menu Events ### Eventos Menu
| Event Name | Description | Parameters | | Nombre de evento | Descripción | Parámetros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| select | callback function when menu is activated | index: index of activated menu, indexPath: index path of activated menu | | select | callback ejecutado cuando el menú es activado | index: índice del menú activado, indexPath: index path del menú activado |
| open | callback function when sub-menu expands | index: index of expanded sub-menu, indexPath: index path of expanded sub-menu | | open | callback ejecutado cuando sub-menu se expande | index: índice del sub-menu expandido, indexPath: index path del sub-menu expandido |
| close | callback function when sub-menu collapses | index: index of collapsed sub-menu, indexPath: index path of collapsed sub-menu | | close | callback ejecutado cuando sub-menu colapsa | index: índice del sub-menu colapsado, indexPath: index path del menú colapsado |
### Menu-Item Events ### Eventos Menu-Item
| Event Name | Description | Parameters | | Nombre de evento | Descripción | Parámetros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| click | callback function when menu-item is clicked | el: menu-item instance | | click | callback ejecutado cuando se hace click sobre menu-item | el: instancia de menu-item |
### SubMenu Attribute ### Atributos SubMenu
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Valores por defecto |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| index | unique identification | string | — | — | | index | identificador único | string | — | — |
### Menu-Item Attribute ### Atributos Menu-Item
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Valores por defecto |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| index | unique identification | string | — | — | | index | identificador único | string | — | — |
| route | Vue Router object | object | — | — | | route | Object Vue Router | object | — | — |
### Menu-Group Attribute ### Atributos Menu-Group
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Valores por defecto |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| title | group title | string | — | — | | title | título del grupo | string | — | — |

View File

@ -123,16 +123,16 @@
## MessageBox ## MessageBox
A set of modal boxes simulating system message box, mainly for alerting information, confirm operations and prompting messages. Un conjunto de cajas modales simulando un sistema de message box, principalmente para alertar informacion, confirmar operaciones y mostrar mensajes de aviso.
:::tip :::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. 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 utilize el componente Dialog.
::: :::
### Alert ### Alert
Alert interrupts user operation until the user confirms. Alert interrumpe las operaciones realizadas hasta que el usuario confirme la alerta.
:::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. :::demo Desplegar una alerta utilizando el metodo `$alert`. Simula el sistema `alert`, y no puede ser cerrado al presionar la tecla ESC o al dar click fuera de la caja. En este ejemplo, dos parametros son recibidos `message` y `title`. Vale la pena mencionar que cuando la caja es cerrada, regresa un objeto `Promise` para su procesaimiento posteriormente. Si no estas seguro si el navegador soporta `Promise`, deberias importar una libreria de terceros de polyfill o utilizar callbacks.
```html ```html
<template> <template>
@ -161,9 +161,10 @@ Alert interrupts user operation until the user confirms.
### Confirm ### Confirm
Confirm is used to ask users' confirmation. Confirm es utilizado para preguntar al usuario y recibir una confirmacion.
:::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.
:::demo llamando al metodo `$confirm` para abrir el componente confirm, y simula el sistema `confirm`.Tambien podemos perzonalizar 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`. Aqui utilizamos `Promise` para manejar posteriormente el proceso.
```html ```html
<template> <template>
@ -199,9 +200,9 @@ Confirm is used to ask users' confirmation.
### Prompt ### Prompt
Prompt is used when user input is required. Prompt es utilizado cuando se requiere entrada de informacion del usuario.
:::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. :::demo LLamando al metodo `$prompt` desplegamos el componente prompt, y simula el sistema `prompt`.Puedes utilizar el parametro `inputPattern` para especificar tu propio patron RegExp. Utiliza el parametro `inputValidator` para especificar el metodo de validacion, y debería regresar un valor de tipo `Boolean` o `String`. Al regresar `false` o `String` significa que la validacion a fallado, y la cadena regresada se usara como `inputErrorMessage`.Ademas, puedes perzonalizar el atributo placeholder del input box con el parametro `inputPlaceholder`.
```html ```html
<template> <template>
@ -235,11 +236,11 @@ Prompt is used when user input is required.
``` ```
::: :::
### Customization ### Personalización
Can be customized to show various content. Puede ser personalizado para mostrar diversos contenidos.
:::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). :::demo Los tres metodos mencionados anteriormente son un rempaquetado del metodo `$msgbox`. En este ejemplo se realiza una llamada al metodo `$msgbox` directamente utilizando el atributo `showCancelButton`, el cual es utilizado para indicar si el boton cancelar es mostrado en pantalla. Ademas podemos utilizar el atributo `cancelButtonClass` para agregar un estilo personalizado y el atributo `cancelButtonText` para personalizar el texto del boton (el boton de confirmacion tambien cuenta con estos campos, y podras encontrar una lista completa de estos atributos al final de esta documentacion). Este ejemplo tambien utiliza el atributo `beforeClose`.Es un metodo que es disparado cuando una instancia del componente MessageBox es cerrada, y su ejecucion detendra el cierre de la instancia. Tiene tres parametros: `action`, `instance` y `done`. Al utilizarla te permite maniluplar la instancia antes de que sea cerrada, e.g. activando `loading` para el boton de confirmacion; puedes invocar el metodo `done` para cerrar la instancia del componente MessageBox (si el metodo `done` no es llamado dentro del atributo `beforeClose`, la instancia no podra cerrarse).
```html ```html
<template> <template>
@ -287,10 +288,10 @@ Can be customized to show various content.
``` ```
::: :::
### Use HTML String ### Utiliza cadenas HTML
`message` supports HTML string. `message` soporta cadenas HTML.
:::demo Set `dangerouslyUseHTMLString` to true and `message` will be treated as an HTML string. :::demo Establece el valor de `dangerouslyUseHTMLString` a true y `message` sera tratado como una cadena HTML.
```html ```html
<template> <template>
@ -311,14 +312,14 @@ Can be customized to show various content.
``` ```
::: :::
:::warning :::advertencia
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. Aunque la propiedad `message` soporta cadenas HTML, realizar arbitrariamente render dinamico de HTML en nuestro sitio web puede ser muy peligroso ya que puede conducir facilmente a [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). Entonces cuando `dangerouslyUseHTMLString` esta activada, asegurece que el contendio de `message` sea de confianza, y **nunca** asignar `message` a contenido generado por el usuario.
::: :::
### Centered content ### Centered content
Content of MessageBox can be centered. El contenido del componente MessageBox puede ser centrado.
:::demo Setting `center` to `true` will center the content :::demo Establecer `center` a `true` centrara el contenido
```html ```html
<template> <template>
@ -352,51 +353,51 @@ Content of MessageBox can be centered.
``` ```
::: :::
### Global method ### Metodos Globales
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: Si Element fue importado completamente, agregara los siguientes metodos globales para Vue.prototype: `$msgbox`, `$alert`, `$confirm` y `$prompt`. Asi que en una instancia de Vue puedes llamar el metodo `MessageBox` como lo que hicimos en esta pagina. Los parametros son:
- `$msgbox(options)` - `$msgbox(options)`
- `$alert(message, title, options)` or `$alert(message, options)` - `$alert(message, title, options)` or `$alert(message, options)`
- `$confirm(message, title, options)` or `$confirm(message, options)` - `$confirm(message, title, options)` or `$confirm(message, options)`
- `$prompt(message, title, options)` or `$prompt(message, options)` - `$prompt(message, title, options)` or `$prompt(message, options)`
### Local import ### Importación local
If you prefer importing `MessageBox` on demand: Si prefieres importar `MessageBox` cuando lo necesites (on demand):
```javascript ```javascript
import { MessageBox } from 'element-ui'; import { MessageBox } from 'element-ui';
``` ```
The corresponding methods are: `MessageBox`, `MessageBox.alert`, `MessageBox.confirm` and `MessageBox.prompt`. The parameters are the same as above. Los metodos correspondientes: `MessageBox`, `MessageBox.alert`, `MessageBox.confirm` y `MessageBox.prompt`. Los parametros son los mismos que los anteriores.
### Options ### Opciones
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Permitidos | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| title | title of the MessageBox | string | — | — | | title | titulo del componente MessageBox | string | — | — |
| message | content of the MessageBox | string | — | — | | message | contenido del componente MessageBox | string | — | — |
| dangerouslyUseHTMLString | whether `message` is treated as HTML string | boolean | — | false | | dangerouslyUseHTMLString | utilizado para que `message` sea tratado como una cadena HTML | boolean | — | false |
| type | message type, used for icon display | string | success / info / warning / error | — | | type | tipo de mensaje , utilizado para mostrar el icono | string | success / info / warning / error | — |
| customClass | custom class name for MessageBox | string | — | — | | customClass | nombre de la clase personzalida para el componente MessageBox | string | — | — |
| callback | MessageBox closing callback if you don't prefer Promise | function(action), where action can be 'confirm' or 'cancel', and `instance` is the MessageBox instance. You can access to that instance's attributes and methods | — | — | | callback | MessageBox callback al cerrar si no deseas utilizar Promise | function(action), donde la accion puede ser 'confirm' o 'cancel', e `instance` es la instancia del componente MessageBox. Puedes acceder a los metodos y atributos de esa instancia | — | — |
| beforeClose | callback before MessageBox closes, and it will prevent MessageBox from closing | function(action, instance, done), where `action` can be 'confirm' or 'cancel'; `instance` is the MessageBox instance, and you can access to that instance's attributes and methods; `done` is for closing the instance | — | — | | 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' o 'cancel'; `instance` es la instancia del componente MessageBox, Puedes acceder a los metodos y atributos de esa instancia; `done` es para cerrar la instancia | — | — |
| lockScroll | whether to lock body scroll when MessageBox prompts | boolean | — | true | | lockScroll | utilizado para bloquear el desplazamiento del contenido del MessageBox prompts | boolean | — | true |
| showCancelButton | whether to show a cancel button | boolean | — | false (true when called with confirm and prompt) | | showCancelButton | utlizado para mostrar un boton cancelar | boolean | — | false (true cuando es llamado con confirm y prompt) |
| showConfirmButton | whether to show a confirm button | boolean | — | true | | showConfirmButton |utlizado para mostrar un boton confirmar | boolean | — | true |
| cancelButtonText | text content of cancel button | string | — | Cancel | | cancelButtonText | contenido de texto del boton cancelar | string | — | Cancel |
| confirmButtonText | text content of confirm button | string | — | OK | | confirmButtonText | contenido de texto del boton confirmar | string | — | OK |
| cancelButtonClass | custom class name of cancel button | string | — | — | | cancelButtonClass | nombre de la clase personalizada del boton cancelar | string | — | — |
| confirmButtonClass | custom class name of confirm button | string | — | — | | confirmButtonClass | nombre de la clase personalizada del boton confirmar | string | — | — |
| closeOnClickModal | whether MessageBox can be closed by clicking the mask | boolean | — | true (false when called with alert) | | closeOnClickModal | utilizado para que que el componenteMessageBox pueda ser cerrado al dar click en la mascara | boolean | — | true (false cuando es llamado con alert) |
| closeOnPressEscape | whether MessageBox can be closed by pressing the ESC | boolean | — | true (false when called with alert) | | closeOnPressEscape | utilizado para que que el componenteMessageBox pueda ser cerrado al presionar la tecla ESC | boolean | — | true (false cuando es llamado con alert) |
| closeOnHashChange | whether to close MessageBox when hash changes | boolean | — | true | | closeOnHashChange | utilizado para cerra el componente MessageBox cuando hash cambie | boolean | — | true |
| showInput | whether to show an input | boolean | — | false (true when called with prompt) | | showInput | utilizado para mostrar el componente input| boolean | — | false (true cuando es llamado con prompt) |
| inputPlaceholder | placeholder of input | string | — | — | | inputPlaceholder | placeholder para el componente input | string | — | — |
| inputType | type of input | string | — | text | | inputType | tipo del componente input | string | — | text |
| inputValue | initial value of input | string | — | — | | inputValue | valor inicial del componente input | string | — | — |
| inputPattern | regexp for the input | regexp | — | — | | inputPattern | regexp del componente 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 | — | — | | inputValidator | funcion de validacion del componente input. Debe regresar un valor de tipo boolean o string. Si regresa un valor tipo string, sera asignado a inputErrorMessage | function | — | — |
| inputErrorMessage | error message when validation fails | string | — | Illegal input | | inputErrorMessage | mensaje de error cuando la validacion falla | string | — | Illegal input |
| center | whether to align the content in center | boolean | — | false | | center | utilizado para alinear el contenido al centro | boolean | — | false |
| roundButton | whether to use round button | boolean | — | false | | roundButton | utilizado para redondear el boton | boolean | — | false |

View File

@ -83,13 +83,13 @@
## Message ## 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. Utilizado para mostrar retroalimentacion despues de una actividad. La diferencia con el componente Notification es que este ultimo es utilizado para mostrar una notificacion pasiva a nivel de sistema.
### Basic usage ### Uso basico
Displays at the top, and disappears after 3 seconds. Se muestra en la parte superior de la pagina y desaparece despues de 3 segundos.
:::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. :::demo La configuracion del componente Message es muy similar al del componente notification, asi que parte de las opciones no seran explicadas a detalle aqui. Puedes consultar la tabla de opciones en la parte inferior conbinada con la documentacion del componente notification para comprenderla. Element a registrado un metodo `$message` para poder invocarlo. Message puede tomar una cadena o un Vnode como parametro, y lo mostrara como el cuerpo principal.
```html ```html
<template> <template>
@ -119,11 +119,11 @@ Displays at the top, and disappears after 3 seconds.
``` ```
::: :::
### Types ### Tipos
Used to show the feedback of Success, Warning, Message and Error activities. Utilizados para mostrar retroalimentacion de Success, Warning, Message y 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`. :::demo Cuando necesitas mas personalizacion, el componente Message tambien puede tomar un objeto como parametro. Por ejemplo, Estableciendo el valor de `type` puedes definir diferentes tipos, el predeterminado es `info`. En tales casos el cuerpo principal se pasa como el valor de `message`. Tambien, tenemos registrados metodos para los diferentes tipos, asi que, puedes llamarlos sin necesidad de pasar un tipo como `open4`.
```html ```html
<template> <template>
<el-button :plain="true" @click="open2">success</el-button> <el-button :plain="true" @click="open2">success</el-button>
@ -163,9 +163,9 @@ Used to show the feedback of Success, Warning, Message and Error activities.
### Closable ### Closable
A close button can be added. Un boton para cerrar que puede ser agregado.
:::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`. :::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 atriubuto `duration` que puede ser controlado. Por defecto la duracion es de 3000 ms, y no desaparecera al llegar a `0`.
```html ```html
<template> <template>
<el-button :plain="true" @click="open5">message</el-button> <el-button :plain="true" @click="open5">message</el-button>
@ -214,7 +214,7 @@ A close button can be added.
::: :::
### Centered text ### Centered text
Use the `center` attribute to center the text. Utiliza el atributo `center` para centrar el texto.
:::demo :::demo
@ -238,10 +238,10 @@ Use the `center` attribute to center the text.
``` ```
::: :::
### Use HTML string ### Utiliza cadenas HTML
`message` supports HTML string. `message` soporta cadenas HTML.
:::demo Set `dangerouslyUseHTMLString` to true and `message` will be treated as an HTML string. :::demo Establece la propiedad `dangerouslyUseHTMLString` en true y `message` sera tratado como una cadena HTML.
```html ```html
<template> <template>
@ -263,15 +263,15 @@ Use the `center` attribute to center the text.
``` ```
::: :::
:::warning :::advertencia
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. Aunque la propiedad `message` soporta cadenas HTML, realizar arbitrariamente render dinamico de HTML en nuestro sitio web puede ser muy peligroso ya que puede conducir facilmente a [XSS attacks](https://en.wikipedia.org/wiki/Cross-site_scripting). Entonces cuando `dangerouslyUseHTMLString` esta activada, asegurece que el contendio de `message` sea de confianza, y **nunca** asignar `message` a contenido generado por el usuario.
::: :::
### Global method ### Metodos Globales
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. Element ha agregado un método global llamado `$message` para Vue.prototype. Entonces en una instancia de vue puedes llamar a `Message` como lo hicimos en esta pagina.
### Local import ### Importación local
Import `Message`: Import `Message`:
@ -279,24 +279,24 @@ Import `Message`:
import { Message } from 'element-ui'; 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)`. En este caso deberias llamar al metodo `Message(options)`. Tambien hemos registrado metodos para los diferentes tipos, e.g. `Message.success(options)`.
You can call `Message.closeAll()` to manually close all the instances. Puedes llamar al metodo `Message.closeAll()` para cerrar manualmente todas las instancias.
### Options ### Options
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripcion | Tipo | Valores permitidos | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| message | message text | string / VNode | — | — | | message | texto del mensaje | string / VNode | — | — |
| type | message type | string | success/warning/info/error | info | | type | tipo del mensaje | string | success/warning/info/error | info |
| iconClass | custom icon's class, overrides `type` | string | — | — | | iconClass | clase personalizada para el icono, sobreescribe `type` | string | — | — |
| dangerouslyUseHTMLString | whether `message` is treated as HTML string | boolean | — | false | | dangerouslyUseHTMLString | utilizado para que `message` sea tratado como cadena HTML | boolean | — | false |
| customClass | custom class name for Message | string | — | — | | customClass | nombre de clase personalizado para el componente Message | string | — | — |
| duration | display duration, millisecond. If set to 0, it will not turn off automatically | number | — | 3000 | | duration | muestra la duracion,en milisegundos. si se establece en 0, este no se apagara automaticamente | number | — | 3000 |
| showClose | whether to show a close button | boolean | — | false | | showClose | utilizado para mostrar un boton para cerrar | boolean | — | false |
| center | whether to center the text | boolean | — | false | | center | utilizado para centrar el texto | boolean | — | false |
| onClose | callback function when closed with the message instance as the parameter | function | — | — | | onClose | funcion callback ejecutada cuando se cierra con una instancia de mensaje como parametro | function | — | — |
### Methods ### Metodos
`Message` and `this.$message` returns the current Message instance. To manually close the instance, you can call `close` on it. `Message` y `this.$message` regresan una instancia del componente Message. Para cerrar manualmente la instancia, puedes llamas al metodo `close`.
| Method | Description | | Metodo | Descripcion |
| ---- | ---- | | ---- | ---- |
| close | close the Message | | close | cierra el componente Message |

View File

@ -48,13 +48,12 @@
} }
</style> </style>
## Pagination ## Paginación
Si tiene que mostrar muchos datos en una página, utiliza la paginación.
If you have too much data to display in one page, use pagination. ### Uso básico
### Basic usage :::**Demo** Asigna en el atributo `layout` los diferentes elementos que quieres utilizar separados por coma. Los elementos de paginación son: `prev` (un botón para navegar a la página anterior), `next` (un botón para navegar a la siguiente página), `pager` (lista de página), `jumper` (un `input` para saltar a una página determinada), `total` (total de elementos), `size` (un `select` para seleccionar el tamanho de la página ) y `->`(todo elemento situado luego de este símbolo será halado a la derecha).
:::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 ```html
<div class="block"> <div class="block">
<span class="demonstration">When you have few pages</span> <span class="demonstration">When you have few pages</span>
@ -73,11 +72,11 @@ If you have too much data to display in one page, use pagination.
``` ```
::: :::
### Small Pagination ### Paginación pequenha
Use small pagination in the case of limited space. Usa una paginación pequenha en caso de espacio limitado.
:::demo Just set the `small` attribute to `true` and the Pagination becomes smaller. :::**Demo** Solo pon el atributo `small` como `true` y la Paginación se volverá pequenha.
```html ```html
<el-pagination <el-pagination
small small
@ -87,11 +86,11 @@ Use small pagination in the case of limited space.
``` ```
::: :::
### More elements ### Más elementos
Add more modules based on your scenario. Agrega más modulos basados en tu escenario.
:::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. :::**Demo** Este ejemplo es un completo caso de uso. Este utiliza los eventos `size-change` y `current-change` para manejar el tamanho de página y el cambio de página. El atributo `page-sizes` acepta un arrelgo de enteros, cada uno representa un diferente valor del atributo `sizes` que es un `select`, ejemplo `[100, 200, 300, 400]` indicará que el `select` tendrá las opciones: 100, 200, 300 o 400 elementos por página.
```html ```html
<template> <template>
@ -195,27 +194,27 @@ Add more modules based on your scenario.
} }
</script> </script>
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Valores por defecto |
|--------------------|----------------------------------------------------------|-------------------|-------------|--------| |--------------------|----------------------------------------------------------|-------------------|-------------|--------|
| small | whether to use small pagination | boolean | — | false | | small | usar paginación pequenha | boolean | — | false |
| page-size | item count of each page | number | — | 10 | | page-size | cantidad de elementos por página | number | — | 10 |
| total | total item count | number | — | — | | total | total de elementos | 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 | — | — | | page-count | total de páginas. Asigna `total` o `page-count` y las páginas serán mostradas; si necesitas `page-sizes`, `total` es **requerido** | number | — | — |
| current-page | current page number, supports the .sync modifier | number | — | 1 | | current-page | número actual de la página, soporta el modificador .sync | number | — | 1 |
| layout | layout of Pagination, elements separated with a comma | string | `sizes`, `prev`, `pager`, `next`, `jumper`, `->`, `total`, `slot` | 'prev, pager, next, jumper, ->, total' | | layout | layout de la paginación, elementos separados por coma | 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] | | page-sizes | opciones para la cantidad de elementos por página | number[] | — | [10, 20, 30, 40, 50, 100] |
| popper-class | custom class name for the page size Select's dropdown | string | — | — | | popper-class | clase propia para el `dropdown` del `select` del número de páginas | string | — | — |
| prev-text | text for the prev button | string | — | — | | prev-text | texto para el botón `prev` | string | — | — |
| next-text | text for the next button | string | — | — | | next-text | texto para el botón `next` | string | — | — |
### Events ### Eventos
| Event Name | Description | Parameters | | Nombre del evento | Descripción | Parámetros |
|---------|--------|---------| |---------|--------|---------|
| size-change | triggers when `page-size` changes | the new `page-size` | | size-change | se dispara cuando `page-size` cambia | nuevo valor de `page-size` |
| current-change | triggers when `current-page` changes | the new `current-page` | | current-change | se dispara cuando `current-page` cambia | nuevo valor de `current-page` |
### Slot ### Slot
| Name | Description | | Nombre | Descripción |
| --- | --- | | --- | --- |
| — | custom content. To use this, you need to declare `slot` in `layout` | | — | Elemento propio. Para utilizar esto necesitas declarar `slot` en el `layout` |

View File

@ -99,11 +99,11 @@
## Popover ## Popover
### Basic usage ### Uso básico
Similar to Tooltip, Popover is also built with `Vue-popper`. So for some duplicated attributes, please refer to the documentation of Tooltip. Similar a un Tooltip, Popover está construido con `Vue-popper`. Así que para atributos duplicados, por favor refiérase a la documentación de Tooltip.
:::demo Add `ref` in your popover, then in your button, use `v-popover` directive to link the button and the popover. The attribute `trigger` is used to define how popover is triggered: `hover`, `click` or `focus`. Alternatively, you can specify reference using a named `slot`. :::**Demo** Agrega `ref` al popover, luego en el botón usa la directiva `v-popover` para asociar el botón y el popover. El atributo `trigger` es usado para definir como el popover se dispara: `hover`, `click` o `focus`. De manera alternatica puedes especificar la referencia utilizando un `[named slot](https://vuejs.org/v2/guide/components.html#Named-Slots).
```html ```html
<el-popover <el-popover
@ -137,11 +137,10 @@ Similar to Tooltip, Popover is also built with `Vue-popper`. So for some duplica
``` ```
::: :::
### Nested information ### Información anidada
Otros componentes pueden anidarse dentro de popover. A continuación un ejemplo de una tabla anidada.
Other components can be nested in popover. Following is an example of nested table. :::**Demo** Reemplaza el atributo `content` con un `slot`.
:::demo replace the `content` attribute with a default `slot`.
```html ```html
<el-popover <el-popover
@ -186,11 +185,11 @@ Other components can be nested in popover. Following is an example of nested tab
``` ```
::: :::
### Nested operation ### Operación anidada
Of course, you can nest other operations. It's more light-weight than using a dialog. Por supuesto, puedes anidar otras operaciones. Es más ligero que utilizar un `dialog`.
:::demo :::**Demo**
```html ```html
<el-popover <el-popover
ref="popover5" ref="popover5"
@ -216,33 +215,33 @@ Of course, you can nest other operations. It's more light-weight than using a di
} }
</script> </script>
``` ```
:::
### Attributes
| Attribute | Description | Type | Accepted Values | Default | ### Atributos
| Atributo | Descripción | Tipo | Valores aceptados | Valores por defecto |
|--------------------|----------------------------------------------------------|-------------------|-------------|--------| |--------------------|----------------------------------------------------------|-------------------|-------------|--------|
| trigger | how the popover is triggered | string | click/focus/hover/manual | click | | trigger | cómo se dispara el popover | string | click/focus/hover/manual | click |
| title | popover title | string | — | — | | title | título del popover | string | — | — |
| content | popover content, can be replaced with a default `slot` | string | — | — | | content | contenido del popover, puede ser sustituido por un `slot` | string | — | — |
| width | popover width | string, number | — | Min width 150px | | width | ancho del popover | 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 | | placement | posición del popover en la pantalla | 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 | | disabled | si el popover está deshabilitado | boolean | — | false |
| value(v-model) | whether popover is visible | Boolean | — | false | | value(v-model) | si el popover está visible | Boolean | — | false |
| offset | popover offset | number | — | 0 | | offset | popover offset | number | — | 0 |
| transition | popover transition animation | string | — | el-fade-in-linear | | 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 | | visible-arrow | si una flecha del tooltip is mostrada o no. Para más información, por favor refiérase a [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-options | parámetros para [popper.js](https://popper.js.org/documentation.html) | object | por favor, refiérase a [popper.js](https://popper.js.org/documentation.html) | `{ boundariesElement: 'body', gpuAcceleration: false }` |
| popper-class | custom class name for popover | string | — | — | | popper-class | clase propia para popover | string | — | — |
| open-delay | delay of appearance when `trigger` is hover, in milliseconds | number | — | — | | open-delay | retraso de la aparición cuando `trigger` es hover, en milisegundos | number | — | — |
### Slot ### Slot
| Name | Description | | Nombre | Descripción |
| --- | --- | | --- | --- |
| — | text content of popover | | — | texto contenido en popover |
| reference | HTML element that triggers popover | | reference | elemento HTML que dispara el popover |
### Events ### Eventos
| Event Name | Description | 回调参数 | | Nombre del evento | Descripción | Parámetros |
|---------|--------|---------| |---------|--------|---------|
| show | triggers when popover shows | — | | show | se dispara cuando se muestra el popover | — |
| hide | triggers when popover hides | — | | hide | se dispara cuando se oculta el popover | — |

View File

@ -9,13 +9,12 @@
} }
} }
</style> </style>
## Progress ## Progreso
Progreso es usado para mostrar el estado de la operación actual e informar al usuario acerca de ésta.
Progress is used to show the progress of current operation, and inform the user the current status. ### Barra de progreso lineal (porcentage externo)
### Linear progress bar (external percentage) :::**Demo** Usa el atributo `percentage` para asignar el porcentage. Este es **requerido** y tiene que ser un valor entre `0-100`.
:::demo Use `percentage` attribute to set the percentage. It's **required** and must be between `0-100`.
```html ```html
<el-progress :percentage="0"></el-progress> <el-progress :percentage="0"></el-progress>
<el-progress :percentage="70"></el-progress> <el-progress :percentage="70"></el-progress>
@ -24,11 +23,10 @@ Progress is used to show the progress of current operation, and inform the user
``` ```
::: :::
### Linear progress bar (internal percentage) ### Barra de progreso lineal (porcentage interno)
En este caso el porcentage no toma espacio adicional.
In this case the percentage takes no additional space. :::**Demo** El atributo `stroke-width` decide el ancho de la barra de progreso, y usa el atributo `text-inside` para poner la descripción dentro de la misma.
:::demo `stroke-width` attribute decides the `width` of progress bar, and use `text-inside` attribute to put description inside the progress bar.
```html ```html
<el-progress :text-inside="true" :stroke-width="18" :percentage="0"></el-progress> <el-progress :text-inside="true" :stroke-width="18" :percentage="0"></el-progress>
<el-progress :text-inside="true" :stroke-width="18" :percentage="70"></el-progress> <el-progress :text-inside="true" :stroke-width="18" :percentage="70"></el-progress>
@ -37,9 +35,9 @@ In this case the percentage takes no additional space.
``` ```
::: :::
### Circular progress bar ### Barra de progreso circular
:::demo You can specify `type` attribute to `circle` to use circular progress bar, and use `width` attribute to change the size of circle. :::**Demo** Puedes asignar el atributo `type` como `circle` para usar la barra circular de progreso, y usar el atributo `width` para cambiar el tamanho del círculo.
```html ```html
<el-progress type="circle" :percentage="0"></el-progress> <el-progress type="circle" :percentage="0"></el-progress>
<el-progress type="circle" :percentage="25"></el-progress> <el-progress type="circle" :percentage="25"></el-progress>
@ -49,13 +47,13 @@ In this case the percentage takes no additional space.
::: :::
### Attributes ### Attributes
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptado | Valores por defecto |
| --- | ---- | ---- | ---- | ---- | | --- | ---- | ---- | ---- | ---- |
| **percentage** | percentage, **required** | number | 0-100 | 0 | | **percentage** | porcenteage, **requerido** | number | 0-100 | 0 |
| type | the type of progress bar | string | line/circle | line | | type | tipo de barra de progreso | string | line/circle | line |
| stroke-width | the width of progress bar | number | — | 6 | | stroke-width | ancho de la barra de progreso | number | — | 6 |
| text-inside | whether to place the percentage inside progress bar, only works when `type` is 'line' | boolean | — | false | | text-inside | mostrar el porcentage dentro de la barra de progreso, solo funciona cuando `type` es 'line' | boolean | — | false |
| status | the current status of progress bar | string | success/exception | — | | status | estado actual de la barra de progreso | string | success/exception | — |
| width | the canvas width of circle progress bar | number | — | 126 | | width | ancho del canvas que contiene la barra de progreso circula | number | — | 126 |
| show-text | whether to show percentage | boolean | — | true | | show-text | mostrar porcentage | boolean | — | true |

View File

@ -1,16 +1,16 @@
## Quick start ## Inicio rápido
This part walks you through the process of using Element in a webpack project. Esta sección te guía en el proceso de usar Element con webpack en un proyecto.
### Use Starter Kit ### Usa la plantilla de Kit de inicio
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. Proveemos una plantilla general [project template](https://github.com/ElementUI/element-starter) para ti. Para los usuarios de Laravel, también tenemos [template](https://github.com/ElementUI/element-in-laravel-starter). Puedes descargarlas y agregarlas directamente también.
If you prefer not to use them, please read the following. Si prefieres no utilizarlas, lee las siguientes secciones de este documento.
### Use vue-cli ### Usando vue-cli
We can also start a project using [vue-cli](https://github.com/vuejs/vue-cli): Podemos empezar un proyecto utilizando [vue-cli](https://github.com/vuejs/vue-cli):
```shell ```shell
> npm i -g vue-cli > npm i -g vue-cli
@ -19,11 +19,11 @@ We can also start a project using [vue-cli](https://github.com/vuejs/vue-cli):
> npm i && npm i element-ui > npm i && npm i element-ui
``` ```
### Import Element ### Importando Element
You can import Element entirely, or just import what you need. Let's start with fully import. Puedes importar Element completamente o solamente importar lo que necesites. Comencemos importando todo.
#### Fully import #### Importando todo
In main.js: In main.js:
```javascript ```javascript
@ -39,19 +39,19 @@ new Vue({
render: h => h(App) render: h => h(App)
}) })
``` ```
The above imports Element entirely. Note that CSS file needs to be imported separately. El código anterior importa Element completamente. Nótese que el archivo CSS necesita ser incluido por separado.
#### On demand #### En demanda
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. Con la ayuda de [babel-plugin-component](https://github.com/QingWei-Li/babel-plugin-component), podemos importar los componentes que necesitamos, haciendo nuestro proyecto más pequenho que de la otra manera.
First, install babel-plugin-component: Primero, instala babel-plugin-component:
```bash ```bash
npm install babel-plugin-component -D npm install babel-plugin-component -D
``` ```
Then edit .babelrc: Luego edita .babelrc:
```json ```json
{ {
"presets": [ "presets": [
@ -66,7 +66,7 @@ Then edit .babelrc:
} }
``` ```
Next, if you need Button and Select, edit main.js: Luego, si necesitas Button y Select, edita main.js:
```javascript ```javascript
import Vue from 'vue' import Vue from 'vue'
@ -86,7 +86,7 @@ new Vue({
}) })
``` ```
Full example (Component list reference [components.json](https://github.com/ElemeFE/element/blob/master/components.json)) Ejemplo completo (Referencia completa de componentes [components.json](https://github.com/ElemeFE/element/blob/master/components.json))
```javascript ```javascript
import Vue from 'vue' import Vue from 'vue'
@ -233,17 +233,17 @@ Vue.prototype.$notify = Notification
Vue.prototype.$message = Message Vue.prototype.$message = Message
``` ```
### Global config ### Configuración global
When importing Element, you can define a global config object. For now this object has only one property: `size`, which sets the default size for all components: Cuando importas Element, puedes definir un objeto global de configuración. Por ahora este elemento solo contiene una propiedad: `size`, que define el tamanho por defecto de todos los componentes:
Fully import Element Importando Element completamente
```JS ```JS
import Vue from 'vue' import Vue from 'vue'
import Element from 'element-ui' import Element from 'element-ui'
Vue.use(Element, { size: 'small' }) Vue.use(Element, { size: 'small' })
``` ```
Partial import Element Importando Element parcialmente
```JS ```JS
import Vue from 'vue' import Vue from 'vue'
import { Button } from 'element-ui' import { Button } from 'element-ui'
@ -251,11 +251,10 @@ import { Button } from 'element-ui'
Vue.prototype.$ELEMENT = { size: 'small' } Vue.prototype.$ELEMENT = { size: 'small' }
Vue.use(Button) Vue.use(Button)
``` ```
With the above config, the default size of all components that have size attribute will be 'small'. Con la anterior configuración, el tamanho por defecto de todos los componentes que tienen el atributo `size` será `small`.
### Start coding ### Empieza ya!
Ahora haz incorporado Vue y Element a tu proyecto es tiempo para comenzar a programar. Inicia el modo de desarrollo:
Now you have implemented Vue and Element to your project, and it's time to write your code. Start development mode:
```bash ```bash
# visit localhost:8086 # visit localhost:8086
@ -267,4 +266,4 @@ Build:
```bash ```bash
npm run build npm run build
``` ```
Please refer to each component's documentation to learn how to use them. Por favor, refiérase a la documentación de cada componente para aprender cómo usarlos.

View File

@ -19,14 +19,12 @@
</script> </script>
## Radio ## Radio
Selección única entre múltiples opciones.
Single selection among multiple options. ### Uso básico
El elemento Radio no debe tener muchas opciones. De otra manera, utilice el componente Select.
### Basic usage :::**Demo** Crear un elemento Radio es fácil, solo necesitas enlazar(`bind`) una variable a la directiva `v-model` del Radio. Va a ser igual al valor `label` del Radio seleccionado. El tipo de dato de `label` es `String`, `Number` o `Boolean`.
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 ```html
<template> <template>
<el-radio v-model="radio" label="1">Option A</el-radio> <el-radio v-model="radio" label="1">Option A</el-radio>
@ -45,11 +43,11 @@ Radio should not have too many options. Otherwise, use the Select component inst
``` ```
::: :::
### Disabled ### Deshabilitado
`disabled` attribute is used to disable the radio. El atributo `disabled` es utilizado para deshabilitar un Radio.
:::demo You just need to add the `disabled` attribute. :::**Demo** Solo necesitas agregar el atributo `disabled`.
```html ```html
<template> <template>
<el-radio disabled v-model="radio1" label="disabled">Option A</el-radio> <el-radio disabled v-model="radio1" label="disabled">Option A</el-radio>
@ -68,11 +66,11 @@ Radio should not have too many options. Otherwise, use the Select component inst
``` ```
::: :::
### Radio button group ### Grupo de elementos Radio
Suitable for choosing from some mutually exclusive options. Recomendado para seleccionar opciones que se excluyen mutuamente.
:::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. :::**Demo** Combina `el-radio-group` con `el-radio` para mostrar un grupo de Radios. Enlaza la variable con `v-model` del elemento `el-radio-group` y asigna el valor del `label` en `el-radio`. También provee el evento `change` con el valor actual como parámetro.
```html ```html
<el-radio-group v-model="radio2"> <el-radio-group v-model="radio2">
@ -93,11 +91,11 @@ Suitable for choosing from some mutually exclusive options.
``` ```
::: :::
### Button style ### Estilo Button
Radio with button styles. Radio con estilo de botón.
:::demo You just need to change `el-radio` element into `el-radio-button` element. We also provide `size` attribute. :::**Demo** Solo necesitas cambiar el elemento `el-radio` a `el-radio-button`. También proveemos el atributo `size`.
```html ```html
<template> <template>
<div> <div>
@ -149,9 +147,9 @@ Radio with button styles.
``` ```
::: :::
### With borders ### Con bordes
:::demo The `border` attribute adds a border to Radios. :::**Demo** El atributo `border` agrega un borde al elemento Radios.
```html ```html
<template> <template>
<div> <div>
@ -191,41 +189,43 @@ Radio with button styles.
``` ```
::: :::
### Radio Attributes ### Atributos de Radio
Attribute | Description | Type | Accepted Values | Default Atributo | Descripción| Tipo |Valores Aceptado| Valores por defecto
---- | ---- | ---- | ---- | ---- ---- | ---- | ---- | ---- | ----
label | the value of Radio | string / number / boolean | — | — label | el valor del Radio | string / number / boolean | — | —
disabled | whether Radio is disabled | boolean | — | false disabled | si el Radio está deshabilitado| boolean | — | false
border | whether to add a border around Radio | boolean | — | false border | agregar borde alrededor del elemento Radio | boolean | — | false
size | size of the Radio, only works when `border` is true | string | medium / small / mini | — size | tamanho del elemento Radio, solo funciona si `border` es verdadero | string | medium / small / mini | —
name | native 'name' attribute | string | — | — name | atributo nativo 'name'| string | — | —
### Radio Events ### Atributos de Radio-button
| Event Name | Description | Parameters | Atributo | Descripción| Tipo |Valores Aceptado| Valores por defecto
---- | ---- | ---- | ---- | ----
label | el valor del Radio | string / number | — | —
disabled | si el Radio está deshabilitado | boolean | — | false
name | atributo nativo 'name' | string | — | —
### Atributos de Radio-group
Atributo | Descripción| Tipo |Valores Aceptado| Valores por defecto
---- | ---- | ---- | ---- | ----
size | tamanho de los `radio buttons` o `bordered radios` | string | medium / small / mini | —
disabled | si la anidación de radios está desahabilitada| boolean | — | false
text-color | color de las letras cuando el botón está activo | string | — | #ffffff |
fill | color del borde y fondo cuando el botón está activo | string | — | #409EFF |
### Eventos de Radio
| Nombre de evento| Descripción| Parámetros |
| --- | --- | --- | | --- | --- | --- |
| change | triggers when the bound value changes | the label value of the chosen radio | | change | se dispara cuando el valor cambia | el valor del `label` del Radio seleccionado |
### Radio-group Attributes
Attribute | Description | Type | Accepted Values | Default ### Eventos de Radio-group
---- | ---- | ---- | ---- | ----
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 | Nombre de evento| Descripción| Parámetros |
| Event Name | Description | Parameters |
| --- | --- | --- | | --- | --- | --- |
| change | triggers when the bound value changes | the label value of the chosen radio | | change | se dispara cuando el valor cambia | el valor del `label` del Radio seleccionado |
### 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 | — | —

View File

@ -39,13 +39,14 @@
} }
</script> </script>
## Rate ## Calificación
Used for rating Usado para la calificación
### Basic usage ### Uso básico
:::**Demo** Clasificación divide las puntuaciones en tres niveles y estos niveles pueden distinguirse usando diferentes colores de fondo. Por defecto los colores de fondo son iguales, pero puedes asignarlos para reflejar los tres niveles usando el atributo `colors` y sus dos umbrales pueden ser definidos con `low-treshold` y `high-treshold`.
:::demo Rate divides rating scores into three levels and these levels can be distinguished by using different background colors. By default background colors are the same, but you can assign them to reflect three levels using the `colors` attribute, and their two thresholds can be defined by `low-threshold` and `high-threshold`.
``` html ``` html
<div class="block"> <div class="block">
@ -73,11 +74,11 @@ Used for rating
``` ```
::: :::
### With text ### Con texto
Using text to indicate rating score Usa texto para indicar la puntuación
:::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`. :::**Demo** Agrega el atributo `show-text` para mostrar texto a la derecha del componente. Puedes asignar textos para las distintas puntuaciones usando `texts`. `texts` es un arreglo cuya longitud debe ser igual a la máxima puntuación `max`.
``` html ``` html
<el-rate <el-rate
@ -98,11 +99,11 @@ Using text to indicate rating score
``` ```
::: :::
### More icons ### Más iconos
You can use different icons to distinguish different rate components. Puedes utilizar iconos para diferenciar cada componente.
:::demo You can customize icons for three different levels using `icon-classes`. In this example, we also use `void-icon-class` to set the icon if it is unselected. :::**Demo** Puedes customizar iconos para tres niveles diferentes usando `icon-classes`. En este ejemplo también usamos `void-icon-class` para asignar un icono si no está seleccionado.
``` html ``` html
<el-rate <el-rate
@ -124,11 +125,11 @@ You can use different icons to distinguish different rate components.
``` ```
::: :::
### Read-only ### Solo lectura
Read-only Rate is for displaying rating score. Half star is supported. La calificación de solo lectura is para mostrar la puntuación. Soporta media estrella.
:::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. :::**Demo** Usa el atributo `disabled` para hacer el componente de solo lectura. Agrega `show-score` para mostrar la puntuación en el lado derecho. Además, puedes usar el atributo `score-template` para proveer una plantilla. Tiene que contener `{value}`, y `{value}` será sustituido por la puntuación.
``` html ``` html
<el-rate <el-rate
@ -151,27 +152,27 @@ Read-only Rate is for displaying rating score. Half star is supported.
``` ```
::: :::
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción| Tipo| Valores aceptado| Valores por defecto|
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| max | max rating score | number | — | 5 | | max | puntuación máxima | number | — | 5 |
| disabled | whether Rate is read-only | boolean | — | false | | disabled | si la calificación es de solo lectura | boolean | — | false |
| allow-half | whether picking half start is allowed | boolean | — | false | | allow-half | si escoger media estrella está permitido | boolean | — | false |
| low-threshold | threshold value between low and medium level. The value itself will be included in low level | number | — | 2 | | low-threshold | valor del umbral entre nivel bajo y medio. El valor será incluido en el nivel bajo | number | — | 2 |
| high-threshold | threshold value between medium and high level. The value itself will be included in high level | number | — | 4 | | high-threshold | valor del umbral entre nivel bajo y medio. El valor será incluido en el nivel alto | number | — | 4 |
| colors | color array for icons. It should have 3 elements, each of which corresponds with a score level | array | — | ['#F7BA2A', '#F7BA2A', '#F7BA2A'] | | colors | arreglo de colores para iconos. Debe tener 3 elementos, cada uno corresponde a un nivel de puntuación | array | — | ['#F7BA2A', '#F7BA2A', '#F7BA2A'] |
| void-color | color of unselected icons | string | — | #C6D1DE | | void-color | color para iconos no seleccionados | string | — | #C6D1DE |
| disabled-void-color | color of unselected read-only icons | string | — | #EFF2F7 | | disabled-void-color | color para las iconos no seleccionados de solo lectura | string | — | #EFF2F7 |
| icon-classes | array of class names of icons. It should have 3 elements, each of which corresponds with a score level | array | — | ['el-icon-star-on', 'el-icon-star-on','el-icon-star-on'] | | icon-classes | arreglo de nombres para clases de iconos. Debe tener 3 elementos, cada uno corresponde a un nivel de puntuación | array | — | ['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 | | void-icon-class | nombre de clase para iconos no seleccionados | string | — | el-icon-star-off |
| disabled-void-icon-class | class name of unselected read-only icons | string | — | el-icon-star-on | | disabled-void-icon-class | nombre de clase para elementos no seleccionados de solo lectura | string | — | el-icon-star-on |
| show-text | whether to display texts | boolean | — | false | | show-text | muestra el texto | boolean | — | false |
| show-score | whether to display current score. show-score and show-text cannot be true at the same time | boolean | — | false | | show-score | muestra puntuación actual. `show-score` y `show-text` no pueden ser verdaderos al mismo tiempo | boolean | — | false |
| text-color | color of texts | string | — | #1F2D3D | | text-color | color del texto | string | — | #1F2D3D |
| texts | text array | array | — | ['极差', '失望', '一般', '满意', '惊喜'] | | texts | arreglo de textos | array | — | ['极差', '失望', '一般', '满意', '惊喜'] |
| score-template | score template | string | — | {value} | | score-template | plantilla de puntuación | string | — | {value} |
### Events ### Events
| Event Name | Description | Parameters | | Nombre del evento | Descripción | Parámetros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| change | Triggers when rate value is changed | value after changing | | change | Se dispara cuando la puntuación es cambiada | valor luego del cambio |

View File

@ -101,6 +101,7 @@
value8: '', value8: '',
value9: [], value9: [],
value10: [], value10: [],
value11: [],
loading: false, 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"] 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"]
}; };
@ -322,7 +323,7 @@ Puede limpiar un Select con un icono.
Selección multiple utiliza tags para mostrar las opciones seleccionadas. Selección multiple utiliza tags para mostrar las opciones seleccionadas.
:::demo Configure el atributo `multiple` para `el-select` para habilitar el modo múltiple. En este caso, el valor del `v-model` será un array de opciones seleccionadas. :::demo Configure el atributo `multiple` para `el-select` para habilitar el modo múltiple. En este caso, el valor del `v-model` será un array de opciones seleccionadas. By default the selected options will be displayed as Tags. You can collapse them to a text by using `collapse-tags` attribute.
```html ```html
<template> <template>
@ -334,6 +335,20 @@ Selección multiple utiliza tags para mostrar las opciones seleccionadas.
:value="item.value"> :value="item.value">
</el-option> </el-option>
</el-select> </el-select>
<el-select
v-model="value11"
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> </template>
<script> <script>
@ -655,6 +670,7 @@ Si el valor de encuadernación de Select es un objeto, asegúrese de asignar `va
| -------------------- | ---------------------------------------- | -------- | ----------------- | ---------------- | | -------------------- | ---------------------------------------- | -------- | ----------------- | ---------------- |
| multiple | si multiple-select esta activo | boolean | — | false | | multiple | si multiple-select esta activo | boolean | — | false |
| disabled | si Select esta deshabilitado | boolean | — | false | | disabled | si Select esta deshabilitado | boolean | — | false |
| collapse-tags | whether to collapse tags to a text when multiple selecting | boolean | — | false |
| value-key | nombre de clave de identidad única para el valor, necesario cuando el valor es un objeto. | string | — | value | | value-key | nombre de clave de identidad única para el valor, necesario cuando el valor es un objeto. | string | — | value |
| size | tamaño del Input | string | large/small/mini | — | | size | tamaño del Input | string | large/small/mini | — |
| clearable | si el single select puede ser limpiable | boolean | — | false | | clearable | si el single select puede ser limpiable | boolean | — | false |

View File

@ -24,10 +24,11 @@
## Switch ## Switch
Switch is used for switching between two opposing states. Switch es utilizdo para realizar cambios entre dos estados opuestos.
### Basic usage ### Uso básico
:::demo Bind `v-model` to a `Boolean` typed variable. The `active-color` and `inactive-color` attribute decides the background color in two states.
:::demo Enlaza `v-model` a una variable de tipo `Boolean`. Los atributos `active-color` y `inactive-color` deciden el color de fondo en cada estado.
```html ```html
<el-switch v-model="value1"> <el-switch v-model="value1">
@ -51,8 +52,8 @@ Switch is used for switching between two opposing states.
``` ```
::: :::
### Text description ### Texto de descripción
:::demo You can add `active-text` and `inactive-text` attribute to show texts. :::demo Puedes agregar los atributos `active-text` y `inactive-text` para mostrar los textos.
```html ```html
<el-switch <el-switch
@ -82,9 +83,9 @@ Switch is used for switching between two opposing states.
``` ```
::: :::
### Extended value types ### Tipos de valores extendidos
:::demo You can set `active-value` and `inactive-value` attributes. They both receive a `Boolean`, `String` or `Number` typed value. :::demo Puedes establecer los atributos `active-value` y `inactive-value`. Ambos reciben valores de tipo `Boolean`, `String` o `Number`.
```html ```html
<el-tooltip :content="'Switch value: ' + value5" placement="top"> <el-tooltip :content="'Switch value: ' + value5" placement="top">
@ -112,7 +113,7 @@ Switch is used for switching between two opposing states.
### Disabled ### Disabled
:::demo Adding the `disabled` attribute disables Switch. :::demo Agregar el atributo `disabled` desactiva el componente Switch.
```html ```html
<el-switch <el-switch
@ -137,29 +138,30 @@ Switch is used for switching between two opposing states.
``` ```
::: :::
### Attributes ### Atributos
Attribute | Description | Type | Accepted Values | Default Atributo | Descripción | Tipo | Valores aceptados | Por defecto
----| ----| ----| ----|---- ----| ----| ----| ----|----
disabled | whether Switch is disabled | boolean | — | false disabled | whether Switch is disabled | boolean | — | false
width | width of Switch | number | — | 40 width | ancho del componente Switch | number | — | 40
active-icon-class | class name of the icon displayed when in `on` state, overrides `active-text` | string | — | — active-icon-class | nombre de la clase del icono mostrado en el estado `on`, sobreescribe `active-text` | string | — | —
inactive-icon-class |class name of the icon displayed when in `off` state, overrides `inactive-text`| string | — | — inactive-icon-class |nombre de la clase del icono mostrado en el estado `off`, sobreescribe `inactive-text`| string | — | —
active-text | text displayed when in `on` state | string | — | — active-text | texto mostrado en el estado `on` | string | — | —
inactive-text | text displayed when in `off` state | string | — | — inactive-text | texto mostrado en el estado `off` | string | — | —
active-value | switch value when in `on` state | boolean / string / number | — | true active-value | cambia su valor cuando se encuentra en el estado `on` | boolean / string / number | — | true
inactive-value | switch value when in `off` state | boolean / string / number | — | false inactive-value | cambia su valor cuando se encuentra en el estado `off` | boolean / string / number | — | false
active-color | background color when in `on` state | string | — | #409EFF active-color | color de fondo cuando se encuentra en el estado `on` | string | — | #409EFF
inactive-color | background color when in `off` state | string | — | #C0CCDA inactive-color | color de fondo cuando se encuentra en el estado `off` | string | — | #C0CCDA
name| input name of Switch | string | — | — name| nombre de entrada del componente Switch | string | — | —
### Events ### Eventos
Event Name | Description | Parameters Nombre del evento | Descripción | Parametro
---- | ----| ---- ---- | ----| ----
change | triggers when value changes | value after changing change | se dispara cuando el valor cambia | valor
después de cambiar
### Methods ### Metodos
Method | Description | Parameters Metodo | Descripción | Parametro
------|--------|------- ------|--------|-------
focus | focus the Switch component | — focus | foco al componente Switch | —

File diff suppressed because it is too large Load Diff

View File

@ -90,15 +90,15 @@
} }
</script> </script>
## Tabs ## Tabulación
Divide data collections which are related yet belong to different types. Divide collecciones de datos que están relacionados pero pertenecen a diferentes tipos.
### Basic usage ### Uso básico
Basic and concise tabs. Tabulación básica y concisa
:::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. :::demo de Tabulación provee funcionalidad de tarjeta selectiva. Por defecto, la primer pestaña es seleccionada como activa, y es posible activar cualquier pestaña estableciendo el atributo de `value`.
```html ```html
<template> <template>
@ -126,11 +126,11 @@ Basic and concise tabs.
``` ```
::: :::
### Card Style ### Estilo de Tarjeta
Tabs styled as cards. Pestañas diseñadas como tarjetas.
:::demo Set `type` to `card` can get a card-styled tab. :::demo Establecer `type` a `card` para obtener una pestaña diseñada como tarjeta.
```html ```html
<template> <template>
@ -158,11 +158,11 @@ Tabs styled as cards.
``` ```
::: :::
### Border card ### Tarjeta con Bordes
Border card tabs. Pestañas de tarjeta con bordes.
:::demo Set `type` to `border-card`. :::demo Establecer `type` a `border-card`.
```html ```html
<el-tabs type="border-card"> <el-tabs type="border-card">
@ -175,11 +175,11 @@ Border card tabs.
::: :::
### Tab position ### Posición de tabulación
You can use `tab-position` attribute to set the tab's position. Es posible usar el atributo `tab-position` para establecer la posición de la tabulación.
:::demo You can choose from four directions: `tabPosition="left|right|top|bottom"` :::demo Es posible escoger entre cuatro direcciones: `tabPosition="left|right|top|bottom"`
```html ```html
<template> <template>
@ -209,9 +209,9 @@ You can use `tab-position` attribute to set the tab's position.
``` ```
::: :::
### Custom Tab ### Pestaña Personalizada
You can use named slot to customize the tab label content. Es posible usar slots nombrados para personalizar el contenido de la etiqueta de la pestaña.
:::demo :::demo
```html ```html
@ -227,9 +227,9 @@ You can use named slot to customize the tab label content.
``` ```
::: :::
### Add & close tab ### Agregar y cerrar pestaña
Only card type Tabs support addable & closeable. Solo las pestañas de tipo tarjeta soportan adición y cierre.
:::demo :::demo
```html ```html
@ -295,7 +295,7 @@ Only card type Tabs support addable & closeable.
``` ```
::: :::
### Customized trigger button of new tab ### Botón disparador personalizado de la nueva pestaña
:::demo :::demo
```html ```html
@ -367,28 +367,28 @@ Only card type Tabs support addable & closeable.
``` ```
::: :::
### Tabs Attributes ### Atributos de Pestañas
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Aceptados | Default |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| type | type of Tab | string | card/border-card | — | | type | tipo de Pestaña | string | card/border-card | — |
| closable | whether Tab is closable | boolean | — | false | | closable | si la Pestaña es cerrable | boolean | — | false |
| addable | whether Tab is addable | boolean | — | false | | addable | si la Pestaña es añadible | boolean | — | false |
| editable | whether Tab is addable and closable | boolean | — | false | | editable | si la Pestaña es añadible y cerrable | boolean | — | false |
| value | name of the selected tab | string | — | name of first tab | | value | nombre de la pestaña seleccionada | string | — | nombre de la primer pestaña |
| tab-position | position of tabs | string | top/right/bottom/left | top | | tab-position | posición de tabulación | string | top/right/bottom/left | top |
### Tabs Events ### Eventos de Pestañas
| Event Name | Description | Parameters | | Nombre de Evento | Descripción | Parámetros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| tab-click | triggers when a tab is clicked | clicked tab | | tab-click | se lanza cuando se hace click a una pestaña | pestaña clickeada |
| tab-remove | triggers when tab-remove button is clicked | name of the removed tab | | tab-remove | se lanza cuando se hace click al botón tab-remove | nombre de la pestaña removida |
| tab-add | triggers when tab-add button is clicked | — | | tab-add | se lanza cuando se hace click al botón tab-add | — |
| edit | triggers when tab-add button or tab-remove is clicked | (targetName, action) | | edit | se lanza cuando los botones de tab-add y/o tab-remove son clickeados | (targetName, action) |
### Tab-pane Attributes ### Attributos del Tab-pane
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Aceptados | Default |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| label | title of the tab | string | — | — | | label | título de la pestaña | string | — | — |
| disabled | whether Tab is disabled | boolean | — | false | | disabled | si la Tabulación está deshabilitada | boolean | — | false |
| name | identifier corresponding to the activeName 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' | | name | identificador correspondiente al activeName de la Tabulación, representando el alias del tab-pane | string | — | número ordinal del tab-pane en la secuencia, p.ej el primer tab-pane de pestañas es '1' |
| closable | whether Tab is closable | boolean | — | false | | closable | whether Tab is closable | boolean | — | false |

View File

@ -6,15 +6,15 @@
} }
</style> </style>
## TimePicker ## Selector de Tiempo
Use Time Picker for time input. Usar el Selector de Tiempo para entradas de tiempo.
### Fixed time picker ### Selector de tiempo fijo
Provide a list of fixed time for users to choose. Provee una lista de tiempo fijo para que los usuarios escogan.
:::demo Use `el-time-select` label, then assign start time, end time and time step with `start`, `end` and `step`. :::demo Usar el tag `el-time-select`, se pueden asignar tiempo de inicio, tiempo de finalización y salto de tiempo con `start`, `end` y `step`.
```html ```html
<el-time-select <el-time-select
v-model="value1" v-model="value1"
@ -38,11 +38,11 @@ Provide a list of fixed time for users to choose.
``` ```
::: :::
### Arbitrary time picker ### Selector de tiempo arbitrario
Can pick an arbitrary time. Un tiempo arbitrario puede ser escogido.
:::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. :::demo Al usar el tag `el-time-picker`, es posible limitar el rango de tiempo al especificar `selectableRange`. Por defecto, es posible hacer scroll con la rueda del mouse para escoger el tiempo, alternativamente se pueden utilizar las flechas de control cuando el atributo `arrow-control` esté establecido.
```html ```html
<template> <template>
@ -76,9 +76,9 @@ Can pick an arbitrary time.
``` ```
::: :::
### Fixed time range ### Rango de tiempo fijo
If start time is picked at first, then the end time will change accordingly. Si se escoge el tiempo de inicio al principio, el tiempo de finalización cambiará respectivamente.
:::demo :::demo
```html ```html
@ -117,11 +117,11 @@ If start time is picked at first, then the end time will change accordingly.
``` ```
::: :::
### Arbitrary time range ### Rango de tiempo arbitrario
Can pick an arbitrary time range. Es posible escoger un rango de tiempo arbitrario.
:::demo We can pick a time range by adding an `is-range` attribute. Also, `arrow-control` is supported in range mode. :::demo Es posible seleccionar un rango de tiempo al añadir el atributo `is-range`. También, `arrow-control` es soportado en modo de rango.
```html ```html
<template> <template>
<el-time-picker <el-time-picker
@ -170,47 +170,47 @@ Can pick an arbitrary time range.
} }
</script> </script>
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Aceptados | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| readonly | whether DatePicker is read only | boolean | — | false | | readonly | saber si el Selector de Fecha está en modo de sólo lectura | boolean | — | false |
| disabled | whether DatePicker is disabled | boolean | — | false | | disabled | saber si el Selector de Fecha se encuentra deshabilitado | boolean | — | false |
| editable | whether the input is editable | boolean | — | true | | editable | saber si el input puede ser editado | boolean | — | true |
| clearable | whether to show clear button | boolean | — | true | | clearable | saber si mostrar el botón de borrado | boolean | — | true |
| size | size of Input | string | medium / small / mini | — | | size | tamaño del input | string | medium / small / mini | — |
| placeholder | placeholder in non-range mode | string | — | — | | placeholder | placeholder en un modo fuera de rango | string | — | — |
| start-placeholder | placeholder for the start time in range mode | string | — | — | | start-placeholder | placeholder para el tiempo de inicio en modo de rango | string | — | — |
| end-placeholder | placeholder for the end time in range mode | string | — | — | | end-placeholder | placeholder para el tiempo de finalización en modo de rango | string | — | — |
| is-range | whether to pick a time range, only works with `<el-time-picker>` | boolean | — | false | | is-range | saber si es posible escoger un rango de tiempo, solo funciona con `<el-time-picker>` | boolean | — | false |
| arrow-control | whether to pick time using arrow buttons, only works with `<el-time-picker>` | boolean | — | false | | arrow-control | saber si es posible escoger el tiempo usando los botones de flecha, solo funciona con `<el-time-picker>` | boolean | — | false |
| value | value of the picker | Date for Time Picker, and string for Time Select | hour `HH`, minute `mm`, second `ss` | HH:mm:ss | | value | valor del selector | Fecha para Selector de Tiempo, string para el Seleccionador de Tiempo | hour `HH`, minute `mm`, second `ss` | HH:mm:ss |
| align | alignment | left / center / right | left | | align | alineación | left / center / right | left |
| popper-class | custom class name for TimePicker's dropdown | string | — | — | | popper-class | nombre de clase personalizada para el dropdown del Selector de Tiempo | string | — | — |
| picker-options | additional options, check the table below | object | — | {} | | picker-options | opciones adicionales, revisar la tabla posterior | object | — | {} |
| range-separator | range separator | string | - | '-' | | range-separator | separador de rango | 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 | — | | default-value | opcional, fecha por defecto del calendario | Fecha para Selector de Tiempo, string para el Seleccionador de Tiempo | cualquier cosa aceptada por `new Date()` para el Selector de Tiempo, Selector de Tiempo, valor seleccionable para el Seleccionador de Tiempo | — |
| value-format | optional, only for TimePicker, format of bounded value | string | hour `HH`, minute `mm`, second `ss` | — | | value-format | opcional, solo para Selector de Tiempo, formato de valor limitado | string | hour `HH`, minute `mm`, second `ss` | — |
| name | same as `name` in native input | string | — | — | | name | así como `name` en input nativo | string | — | — |
### Time Select Options ### Opciones para Seleccionador de Tiempo
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Aceptados | Default |
|---------- |-------------- |---------- |-------------------------------- |-------- | |---------- |-------------- |---------- |-------------------------------- |-------- |
| start | start time | string | — | 09:00 | | start | tiempo de inicio | string | — | 09:00 |
| end | end time | string | — | 18:00 | | end | tiempo de finalización | string | — | 18:00 |
| step | time step | string | — | 00:30 | | step | salto de tiempo | string | — | 00:30 |
| minTime | minimum time, any time before this time will be disabled | string | — | 00:00 | | minTime | tiempo mínimo, cualquier tiempo antes de éste será deshabilitado | string | — | 00:00 |
| maxTime | maximum time, any time after this time will be disabled | string | — | — | | maxTime | tiempo máximo, cualquier tiempo después de éste será deshabilitado | string | — | — |
### Time Picker Options ### Opciones para Selector de Tiempo
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Aceptados | 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 | — | — | | selectableRange | rango de tiempo disponible p.ej. `'18:30:00 - 20:30:00'`ó`['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` | HH:mm:ss | | format | formato para el selector | string | hour `HH`, minute `mm`, second `ss` | HH:mm:ss |
### Events ### Eventos
| Event Name | Description | Parameters | | Nombre de Evento | Descripción | Parámetros |
|---------|--------|---------| |---------|--------|---------|
| change | triggers when user confirms the value | component's bounded value | | change | se lanza cuando el usuario confirma el valor | valor limitado del componente |
| blur | triggers when Input blurs | (event: Event) | | blur | se lanza cuando el input se difumina | (event: Event) |
| focus | triggers when Input focuses | (event: Event) | | focus | se lanza cuando el input se enfoca | (event: Event) |

View File

@ -57,13 +57,13 @@
## Tooltip ## Tooltip
Display prompt information for mouse hover. Mostrar aviso de información para el hover del mouse.
### Basic usage ### Uso básico
Tooltip has 9 placements. Tooltip tiene 9 colocaciones.
:::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. :::demo Usar el atributo `content` para establecer el contenido que se mostrará al hacer hover. El atributo `placement` determina la posición del tooltip. Su valor es `[orientation]-[alignment]` con cuatro orientaciones `top`, `left`, `right`, `bottom` y tres alineaciones `start`, `end`, `null`, la alineación default es null. Tome `placement="left-end"` como ejemplo, Tooltip será mostrado en la izquierda del elemento en que se esté haciendo hover y el fondo del tooltip se alineará con el fondo del elemento.
```html ```html
<div class="box"> <div class="box">
<div class="top"> <div class="top">
@ -154,11 +154,11 @@ Tooltip has 9 placements.
::: :::
### Theme ### Tema
Tooltip has two themes: `dark` and `light` Tooltip tiene dos temas: `dark` and `light`.
:::demo Set `effect` to modify theme, and the default value is `dark`. :::demo Establecer `effect` para modificar el tema, el valor por defecto es `dark`.
```html ```html
<el-tooltip content="Top center" placement="top"> <el-tooltip content="Top center" placement="top">
<el-button>Dark</el-button> <el-button>Dark</el-button>
@ -169,11 +169,11 @@ Tooltip has two themes: `dark` and `light`。
``` ```
::: :::
### More Content ### Más Contenido
Display multiple lines of text and set their format. Despliegue múltiples líneas de texto y establezca su formato.
:::demo Override attribute `content` of `el-tooltip` by adding a slot named `content`. :::demo Sobre-escribir el atributo `content` del `el-tooltip` al añadir un slot llamado `content`.
```html ```html
<el-tooltip placement="top"> <el-tooltip placement="top">
<div slot="content">multiple lines<br/>second line</div> <div slot="content">multiple lines<br/>second line</div>
@ -182,15 +182,15 @@ Display multiple lines of text and set their format.
``` ```
::: :::
### Advanced usage ### Uso Avanzado
In addition to basic usages, there are some attributes that allow you to customize your own: Adicional a los usos básicos, existen algunos atributos que permiten la personalización:
`transition` attribute allows you to customize the animation in which the tooltip shows or hides, and the default value is el-fade-in-linear. el atributo `transition` permite personalizar la animación con la que el Tooltip se muestra o se esconda, el valor por defecto es `is el-fade-in-linear`.
`disabled` attribute allows you to disable `tooltip`. You just need set it to `true`. el atributo `disabled` permite deshabilitar `tooltip`. Solo es necesario definirlo como `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. De hecho, Tooltip es una extension basada en [Vue-popper](https://github.com/element-component/vue-popper), es posible utilizar cualquier atributo permitido en Vue-popper.
:::demo :::demo
```html ```html
@ -217,26 +217,27 @@ In fact, Tooltip is an extension based on [Vue-popper](https://github.com/elemen
:::tip :::tip
The `router-link` component is not supported in tooltip, please use `vm.$router.push`. El componente `router-link` no es soportado por Tooltip, favor de usar `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. Elementos de forma deshabilitados no son soportados por Tooltip, más información puede ser encontrada en [MDN](https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter).
Es necesario envolver los elementos de forma deshabilitados en un elemento contenedor para que Tooltipo funcione.
::: :::
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores Aceptados | Default |
|----------------|---------|-----------|-------------|--------| |----------------|---------|-----------|-------------|--------|
| effect | Tooltip theme | string | dark/light | dark | | effect | tema del Tooltip | string | dark/light | dark |
| content | display content, can be overridden by `slot#content` | String | — | — | | content | contenido a mostrar, puede ser sobre-escrito por `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 | | placement | posición del 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 | | value(v-model) | visibilidad del Tooltip | boolean | — | false |
| disabled | whether Tooltip is disabled | boolean | — | false | | disabled | saber si el Tooltip se encuentra deshabilitado | boolean | — | false |
| offset | offset of the Tooltip | number | — | 0 | | offset | offset del Tooltip | number | — | 0 |
| transition | animation name | string | — | el-fade-in-linear | | transition | nombre de animación | 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 | | visible-arrow | saber si una flecha es mostrada. Para mayor información, revisar la página de [Vue-popper](https://github.com/element-component/vue-popper) | 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 }` | | popper-options | parámetros de [popper.js](https://popper.js.org/documentation.html) | Object | referirse a la documentación de [popper.js](https://popper.js.org/documentation.html) | `{ boundariesElement: 'body', gpuAcceleration: false }` |
| open-delay | delay of appearance, in millisecond | number | — | 0 | | open-delay | retraso de la apariencia, en milisegundos | number | — | 0 |
| manual | whether to control Tooltip manually. `mouseenter` and `mouseleave` won't have effects if set to `true` | boolean | — | false | | manual | saber si el Tooltipo será controlado de forma manual. `mouseenter` y `mouseleave` no tendrán efecto si fue establecido como `true` | boolean | — | false |
| popper-class | custom class name for Tooltip's popper | string | — | — | | popper-class | nombre de clase personalizada para el popper del Tooltip | string | — | — |
| enterable | whether the mouse can enter the tooltip | Boolean | — | true | | enterable | saber si el mouse puede entrar al Tooltip | Boolean | — | true |
| hide-after | timeout in milliseconds to hide tooltip | number | — | 0 | | hide-after | tiempo a esperar en milisegundos para esconder el Tooltip | number | — | 0 |

View File

@ -72,8 +72,8 @@
## Transfer ## Transfer
### Basic usage ### Uso básico
:::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. :::demo Los datos se pasan a Transfer a través del atributo `data`. Los datos tienen que ser un array de objetos, y cada objeto debe tener estos atributos: `key` que será el identificador del item, `label` que será el texto a mostrar, y `disabled` que indicará si el elemento esta desactivado. Los items dentro de la lista destino están sincronizados con la variable asociada a `v-model`, y el valor de esa variable es un array de claves de los elementos de la lista destino. Así que si no quieres que la lista destino esté vacía inicialmente puedes inicializar el `v-model` con un array.
```html ```html
<template> <template>
<el-transfer <el-transfer
@ -106,11 +106,11 @@
``` ```
::: :::
### Filterable ### Filtrar
You can search and filter data items. Puedes buscar y filtrar los 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. ::demo Pon el atributo `filterable` a true para permitir el filtrado.Por defecto si el `label` del item contiene el término buscado será incluido en el resultado. También puedes implementar tu propio método de filtrado con el atributo `filter-method`, que recibe un método y le pasa la búsqueda y cada item. Los items para los que devuelva true serán incluidos en el resultado de la búsqueda.
```html ```html
<template> <template>
<el-transfer <el-transfer
@ -153,9 +153,9 @@ You can search and filter data items.
### Customizable ### Customizable
You can customize list titles, button texts, render function for data items, checking status texts in list footer and list footer contents. Puedes customizar los títulos, botones, la función de renderizado de los items, el texto de status de la cabecera y el contenido del pie.
:::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. 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. :::demo Usa `titles`, `button-texts`, `render-content` y `format` respectivamente para customizar los títulos de las listas, el texto de los botones, la función de renderizado para los items y el texto de la cabecera que muestra el estado de los items. Para el pie de la lista hay dos slots: `left-footer` y `right-footer`. Además, si quieres algunos items marcados inicialmente pudes usar `left-default-checked` y `right-default-checked`. Finalmente este ejemplo muestra el evento `change`. Ten en cuenta que este ejemplo no se puede ejecutar en jsfiddle porque no soporta sintaxis JSX. En un proyecto real `render-content` funcionará si las dependencias son configuradas correctamente.
```html ```html
<template> <template>
<el-transfer <el-transfer
@ -219,8 +219,9 @@ You can customize list titles, button texts, render function for data items, che
### Prop aliases ### 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. Por defecto Transfer busca los atributos `key`, `label`, y `disabled` en cada elemento. Si tus datos tienen un nombre diferente para la clave puedes usar el atributo `props` para añadir alias.
:::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`.
:::demo En este ejemplo los elementos no tienen `key`y `label`, en vez de eso tienen `value` y `desc`. Así que tienes que añadir alias para `key` y `label`.
```html ```html
<template> <template>
<el-transfer <el-transfer
@ -257,28 +258,29 @@ By default, Transfer looks for `key`, `label` and `disabled` in a data item. If
``` ```
::: :::
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atriburo | Descripcion | Tipo | Valores aceptados | Por defecto |
|---------- |-------- |---------- |------------- |-------- | |---------- |-------- |---------- |------------- |-------- |
| data | data source | array[{ key, label, disabled }] | — | [ ] | | data | Origen de datos | array[{ key, label, disabled }] | — | [ ] |
| filterable | whether Transfer is filterable | boolean | — | false | | filterable | Si se puede filtrar | boolean | — | false |
| filter-placeholder | placeholder for the filter input | string | — | Enter keyword | | filter-placeholder | Placeholder para el input del filtro| string | — | Enter keyword |
| filter-method | custom filter method | function | — | — | | filter-method | Método de filtrado | function | — | — |
| titles | custom list titles | array | — | ['List 1', 'List 2'] | | titles | Títulos de las listas | array | — | ['List 1', 'List 2'] |
| button-texts | custom button texts | array | — | [ ] | | button-texts | Texto de los botones | array | — | [ ] |
| render-content | custom render function for data items | function(h, option) | — | — | | render-content | Función de renderizado | function(h, option) | — | — |
| format | texts for checking status in list header | object{noChecked, hasChecked} | — | { noChecked: '${checked}/${total}', hasChecked: '${checked}/${total}' } | | format | Texto para el status en el header| object{noChecked, hasChecked} | — | { noChecked: '${checked}/${total}', hasChecked: '${checked}/${total}' } |
| props | prop aliases for data source | object{key, label, disabled} | — | — | | props | prop alias para el origen de datos | object{key, label, disabled} | — | — |
| left-default-checked | key array of initially checked data items of the left list | array | — | [ ] | | left-default-checked | Array de claves de los elementos marcados inicialmente en la lista de la izquierda | array | — | [ ] |
| right-default-checked | key array of initially checked data items of the right list | array | — | [ ] | | right-default-checked | Array de claves de los elementos marcados inicialmente en la lista de la derecha | array | — | [ ] |
### Slot ### Slot
| Name | Description | | Nombre | Descripcion |
|------|--------| |------|--------|
| left-footer | content of left list footer | | left-footer | Contenido del footer de la lista de la izquierda |
| right-footer | content of right list footer | | right-footer | Contenido del footer de la lista de la derecha |
### Events ### Eventos
| Event Name | Description | Parameters | | Nombre | Descripcion | Parametros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| 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 | | change | se lanzá cuando los elementos cambian en la lista de la derecha | array con las claves de los elementos de la lista de la derecha |

View File

@ -1,10 +1,10 @@
## Built-in transition ## Transiciones incorporadas
You can use Element's built-in transitions directly. Before that, please read the [transition docs](https://vuejs.org/v2/api/#transition). Puedes usar directamente las transiciones incorporadas en Element. Antes de hacerlo, por favor lea la [documentación](https://vuejs.org/v2/api/#transition).
### fade ### Fade
:::demo We have two fading effects: `el-fade-in-linear` and `el-fade-in`. :::demo Tenemos dos efectos de fading: `el-fade-in-linear` y `el-fade-in`.
```html ```html
<template> <template>
<div> <div>
@ -46,9 +46,9 @@ You can use Element's built-in transitions directly. Before that, please read th
``` ```
::: :::
### zoom ### Zoom
:::demo `el-zoom-in-center`, `el-zoom-in-top` and `el-zoom-in-bottom` are provided. :::demo También tenemos zoom: `el-zoom-in-center`, `el-zoom-in-top` y `el-zoom-in-bottom`.
```html ```html
<template> <template>
<div> <div>
@ -96,10 +96,8 @@ You can use Element's built-in transitions directly. Before that, please read th
::: :::
### collapse ### Colapsado
Para efectos de colapsado usar el componente `el-collapse-transition`.
For collapse effect, use the `el-collapse-transition` component.
:::demo :::demo
```html ```html
<template> <template>
@ -147,7 +145,7 @@ For collapse effect, use the `el-collapse-transition` component.
```js ```js
// fade/zoom // fade/zoom
import 'element-ui/lib/theme-chalk/base.css'; import 'element-ui/lib/theme-chalk/base.css';
// collapse // colapsar
import CollapseTransition from 'element-ui/lib/transitions/collapse-transition'; import CollapseTransition from 'element-ui/lib/transitions/collapse-transition';
import Vue from 'vue' import Vue from 'vue'

View File

@ -286,11 +286,11 @@
## Tree ## Tree
Display a set of data with hierarchies. Muestra un conjunto de datos jerárquicos.
### Basic usage ### Uso básico
Basic tree structure. Estructura básica de árbol.
::: demo ::: demo
```html ```html
@ -351,11 +351,11 @@ Basic tree structure.
``` ```
::: :::
### Selectable ### Seleccionable
Used for node selection. Usado para la selección de nodos.
::: demo This example also shows how to load node data asynchronously. ::: demo Este ejemplo también muestra como cargar los datos de forma asíncrona.
```html ```html
<el-tree <el-tree
:props="props" :props="props"
@ -419,9 +419,9 @@ Used for node selection.
``` ```
::: :::
### Custom leaf node in lazy mode ### Nodos hoja en modo perezoso
::: 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. :::demo Los datos de un nodo no son cargados hasta que no es pinchado, así que el árbol no puede predecir si es una hoja. Por eso a cada nodo se le añade el botón de desplegar, y si el nodo es una hoja el botón desaparecerá al pinchar en él. También puedes decirle al árbol que el nodo es una hoja de antemano, y así evitas que muestre el botón de desplegar.
```html ```html
<el-tree <el-tree
:props="props1" :props="props1"
@ -465,11 +465,11 @@ Used for node selection.
``` ```
::: :::
### Disabled checkbox ### Checkbox desactivados
The checkbox of a node can be set as disabled. El checkbox de un nodo se puede poner como desactivado.
::: 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. ::: demo En el ejemplo, la propiedad 'disabled' se declara en defaultProps, y algunos nodos se ponen como 'disabled:true'. Los checkboxes correspondientes son desactivados y no se pueden pinchar.
```html ```html
<el-tree <el-tree
:data="data3" :data="data3"
@ -522,10 +522,10 @@ The checkbox of a node can be set as disabled.
``` ```
::: :::
### Default expanded and default checked ### Desplegado o seleccionado por defecto
Tree nodes can be initially expanded or checked Los nodos pueden estar desplegados o seleccionados por defecto.
::: 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. :::demo Utiliza `default-expanded-keys` y `default-checked-keys` para establecer los nodos desplegados y seleccionados respectivamente. Ten en cuenta que para que funcione es necesario que tengan `node-key`. Su valor es el nombre de una clave en el objeto data, y el valor de la clave debe ser único en todo el árbol.
```html ```html
<el-tree <el-tree
:data="data2" :data="data2"
@ -586,9 +586,9 @@ Tree nodes can be initially expanded or checked
``` ```
::: :::
### Checking tree nodes ### Seleccionando nodos
::: 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. ::: demo Este ejemplo muestra como establecer y leer nodos seleccionados. Esto se puede hacer por nodos o por claves. Si lo haces por claves el atributo `node-key` es necesario.
```html ```html
<el-tree <el-tree
:data="data2" :data="data2"
@ -682,10 +682,10 @@ Tree nodes can be initially expanded or checked
``` ```
::: :::
### Custom node content ### Contenido personalzado en los nodos
The content of tree nodes can be customized, so you can add icons or buttons as you will El contenido de los nodos puede ser personalizado, así que puedes añadir iconos y botones a tu gusto.
::: demo 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. 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. ::: demo Utiliza `render-content` para asignar una función de renderizado que devuelve el contenido del árbol de nodos. Mira la documentación de node para una introducción detallada a las funciondes de renderizado. Ten en cuenta que este ejemplo no puede ejecutarse en jsfiddle ya que no soporta la sintaxis JSX. En un proyecto real `render-content` funcionará si las dependencias relevantes están configuradas correctamente.
```html ```html
<el-tree <el-tree
:data="data4" :data="data4"
@ -779,10 +779,10 @@ The content of tree nodes can be customized, so you can add icons or buttons as
``` ```
::: :::
### Tree node filtering ### Filtrado de nodos
Tree nodes can be filtered Los nodos del árbol se pueden filtrar.
::: 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. :::demo Invoca el método `filter` de la instancia de Tree para filtrar los nodos. Su parametro es la palabra de filtrado. Ten en cuenta que para que funcione es necesario `filter-node-method`, y su valor el método de filtrado.
```html ```html
<el-input <el-input
placeholder="Filter keyword" placeholder="Filter keyword"
@ -862,9 +862,9 @@ Tree nodes can be filtered
``` ```
::: :::
### Accordion ### Acordeón
Only one node among the same level can be expanded at one time. Solo puede ser expandido un nodo del mismo nivel a la vez.
::: demo ::: demo
```html ```html
@ -930,56 +930,55 @@ Only one node among the same level can be expanded at one time.
``` ```
::: :::
### Attributes ### Atributos
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Default |
| --------------------- | ---------------------------------------- | --------------------------- | --------------- | ------- | | - | - | - | - | -|
| data | tree data | array | — | — | | data | Datos del árbol | array | — | — |
| empty-text | text displayed when data is void | string | — | — | | empty-text | Texto a mostrar cuando data es void | string | — | — |
| node-key | unique identity key name for nodes, its value should be unique across the whole tree | string | — | — | | node-key | Identificador único en todo el árbol para los nodos | string | — | — |
| props | configuration options, see the following table | object | — | — | | props | Opciones de configuración | object | — | — |
| load | method for loading subtree data | function(node, resolve) | — | — | | load | Método para cargar los datos de subárboles | function(node, resolve) | — | — |
| render-content | render function for tree node | Function(h, { node, data, store } | — | — | | render-content | Función de renderizado para los nodos | Function(h, { node, data, store }| — | — |
| highlight-current | whether current node is highlighted | boolean | — | false | | highlight-current | Si el nodo actual está resaltado | boolean | — | false |
| default-expand-all | whether to expand all nodes by default | boolean | — | false | | default-expand-all | Expandir todos los nodos por defecto | 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. | — | true | | | expand-on-click-node | Si expandir o contraer un nodo al pincharlo, si es false solo se hará al pinchar en la flecha | — | true | - |
| auto-expand-parent | whether to expand father node when a child node is expanded | boolean | — | true | | auto-expand-parent | Expandir un nodo padre si el hijo está seleccionado | boolean | — | true |
| default-expanded-keys | array of keys of initially expanded nodes | array | — | — | | default-expanded-keys | Array de claves de los nodos expandidos inicialmente | array | — | — |
| show-checkbox | whether node is selectable | boolean | — | false | | show-checkbox | Si un nodo es seleccionable | boolean | — | false |
| check-strictly | whether checked state of a node not affects its father and child nodes when `show-checkbox` is `true` | boolean | — | false | | check-strictly | El estado de seleccion de un nodo no afecta a sus padres o hijos, cuando `show-checkbox` es `true` | boolean | — | false |
| default-checked-keys | array of keys of initially checked nodes | array | — | — | | default-checked-keys | Array con claves de los nodos seleccionados inicialmente | array | — | — |
| 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) | — | — | | filter-node-method | Esta función se ejecutará en cada nodo cuando se use el método filtrtar, si devuelve `false` el nodo se oculta | Function(value, data, node) | — | — |
| accordion | whether only one node among the same level can be expanded at one time | boolean | — | false | | accordion | Dice si solo un nodo de cada nivel puede expandirse a la vez | boolean | — | false |
| indent | horizontal indentation of nodes in adjacent levels in pixels | number | — | 16 | | indent | Indentación horizontal de los nodos en niveles adyacentes, en pixeles | number | — | 16 |
### props ### props
| Attribute | Description | Type | Accepted Values | Default | | Atributo | Descripción | Tipo | Valores aceptados | Default |
| --------- | ---------------------------------------- | ------ | --------------- | ------- | | - | -| - | - | - |
| label | specify which key of node object is used as the node's label | string, function(data, node) | — | — | | label | Especifica que clave del objecto nodo se utilizará como label | string, function(data, node) | — | — |
| children | specify which node object is used as the node's subtree | string, function(data, node) | — | — | | children | Especifica que objeto del nodo se utiliza como subárbol | string, function(data, node) | — | — |
| disabled | specify which key of node object represents if node's checkbox is disabled | boolean, function(data, node) | — | — | | isLeaf | Especifica si el nodo es una hoja | boolean, function(data, node) | — | — |
| isLeaf | specify whether the node is a leaf node | boolean, function(data, node) | — | — |
### Method ### Métodos
`Tree` has the following method, which returns the currently selected array of nodes. `Tree` tiene los siguientes métodos, que devuelven el array de nodos seleccionados.
| Method | Description | Parameters | | Método | Descripción | Parámetros |
| --------------- | ---------------------------------------- | ---------------------------------------- | | - | - | - |
| filter | filter all tree nodes, filtered nodes will be hidden | Accept a parameter which will be used as first parameter for filter-node-method | | filter | Filtra los nodos del árbol, los nodos filtrados estarán ocultos | Acepta un parámetro que será usado como primer parámetro para 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 | | updateKeyChildren | Asocia un nuevo dato al nodo, solo funciona si `node-key` está asignado | (key, data)Acepta dos parámetros: 1. clave del nodo 2. nuevo dato |
| getCheckedNodes | If the node can be selected (`show-checkbox` is `true`), it returns the currently selected array of nodes | 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. | | getCheckedNodes | Si los nodos puede ser seleccionado (`show-checkbox` es `true`), devuelve el array de nodos seleccionados | Acepta un booleano cuyo valor por defecto es `false`|
| setCheckedNodes | set certain nodes to be checked, only works when `node-key` is assigned | an array of nodes to be checked | | setCheckedNodes | Establece algunos nodos como seleccionados, solo funciona cuando `node-key` está asignado | Un array de nodos a seleccionar |
| 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. | | getCheckedKeys | Si los nodos pueden ser seleccionados (`show-checkbox` es `true`), devuelve un array con las claves de los nodos seleccionados | (leafOnly) Acepta un booleano que por defecto es `false`. |
| 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. | | setCheckedKeys | Establece algunos nodos como seleccionados, solo si `node-key` está asignado| (keys, leafOnly) Acepta dos parametros: 1. un array de claves 2. un booleano cuyo valor por defecto es `false`. Si el parámetro es `true`, solo devuelve los nodos seleccionados |
| 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. | | setChecked | Establece si un nodo está seleccionado, solo funciona si `node-key` esta asignado | (key/data, checked, deep) Acepta tres parámetros: 1. la clave o dato del nodo a ser seleccionado 2. un booleano que indica si un nodo el nodo estará seleccionado 3. un booleanoque indica si se hará en profundidad |
| getCurrentKey | return the highlight node's key (null if no node is highlighted) | — | | getCurrentKey | devuelve la clave del nodo resaltado actualmente (null si no hay ninguno) | — |
| getCurrentNode | return the highlight node (null if no node is highlighted) | — | | getCurrentNode | devuelve el nodo resaltado (null si no hay ninguno) | — |
| setCurrentKey | set highlighted node by key, only works when `node-key` is assigned | (key) the node's key to be highlighted | | setCurrentKey | establece el nodo resaltado por la clave, solo funciona si `node-key` está asignado | (key) la clave del nodo a ser resaltado|
| setCurrentNode | set highlighted node, only works when `node-key` is assigned | (node) the node to be highlighted | | setCurrentNode | establece el nodo resaltado, solo funciona si `node-key` está asignado | (node) nodo a ser resaltado |
### Events ### Eventos
| Event Name | Description | Parameters | | Nombre del evento | Descripción | Parámetros |
| -------------- | ---------------------------------------- | ---------------------------------------- | | - | - | - |
| node-click | triggers when a node is clicked | three parameters: node object corresponding to the node clicked, `node` property of TreeNode, TreeNode itself | | node-click | se lanza cuando un nodo es pinchado | tres parámetros: el objeto del nodo seleccionado, propiedad `node` de TreeNode y el TreeNode en si |
| 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-change | se lanza cuando el estado de selección del nodo cambia | tres parámetros: objeto nodo que se corresponde con el que ha cambiado, booleano que dice si esta seleccionado, booleano que dice si el nodo tiene hijos seleccionados |
| current-change | triggers when current node changes | two parameters: node object corresponding to the current node, `node` property of TreeNode | | current-change | cambia cuando el nodo actual cambia | dos parámetros: objeto nodo que se corresponde al nodo actual y propiedad `node` del TreeNode |
| node-expand | triggers when current node open | three parameters: node object corresponding to the node opened, `node` property of TreeNode, TreeNode itself | | node-expand | se lanza cuando el nodo actual se abre | tres parámetros: el objeto del nodo abierto, propiedad `node` de TreeNode y el TreeNode en si |
| node-collapse | triggers when current node close | three parameters: node object corresponding to the node closed, `node` property of TreeNode, TreeNode itself | | node-collapse | se lanza cuando el nodo actual se cierra | tres parámetros: el objeto del nodo cerrado, propiedad `node` de TreeNode y el TreeNode en si |

View File

@ -120,13 +120,13 @@
} }
} }
</script> </script>
## Upload ## Carga de archivos
Upload files by clicking or drag-and-drop Carga archivos haciendo clic o arrastrándolos.
### Click to upload files ### Clic para cargar archivos
:::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. :::demo Personaliza el tipo y texto del botón utilizando la propiedad `slot`. Define las propiedades `limit` y `on-exceed` para limitar el número máximo de archivos a subir y especifica un método para cuando el límite ha sido excedido.
```html ```html
<el-upload <el-upload
class="upload-demo" class="upload-demo"
@ -137,8 +137,8 @@ Upload files by clicking or drag-and-drop
:limit="3" :limit="3"
:on-exceed="handleExceed" :on-exceed="handleExceed"
:file-list="fileList"> :file-list="fileList">
<el-button size="small" type="primary">Click to upload</el-button> <el-button size="small" type="primary">Clic para subir archivo</el-button>
<div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div> <div slot="tip" class="el-upload__tip">Solo archivos jpg/png con un tamaño menor de 500kb</div>
</el-upload> </el-upload>
<script> <script>
export default { export default {
@ -155,7 +155,7 @@ Upload files by clicking or drag-and-drop
console.log(file); console.log(file);
}, },
handleExceed(files, fileList) { 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`); this.$message.warning(`El límite es 3, haz seleccionado ${files.length} archivos esta vez, añade hasta ${files.length + fileList.length}`);
} }
} }
} }
@ -163,9 +163,9 @@ Upload files by clicking or drag-and-drop
``` ```
::: :::
### User avatar upload ### Cargar avatar de usuario
Use `before-upload` hook to limit the upload file format and size. Utiliza el _hook_ `before-upload` para limitar el formato de archivo y su tamaño.
::: demo ::: demo
```html ```html
@ -221,10 +221,10 @@ Use `before-upload` hook to limit the upload file format and size.
const isLt2M = file.size / 1024 / 1024 < 2; const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) { if (!isJPG) {
this.$message.error('Avatar picture must be JPG format!'); this.$message.error('La imagen debe estar en formato JPG!');
} }
if (!isLt2M) { if (!isLt2M) {
this.$message.error('Avatar picture size can not exceed 2MB!'); this.$message.error('La imagen excede los 2MB!');
} }
return isJPG && isLt2M; return isJPG && isLt2M;
} }
@ -234,9 +234,9 @@ Use `before-upload` hook to limit the upload file format and size.
``` ```
::: :::
### Photo Wall ### Pared de fotografías
Use `list-type` to change the fileList style. Utiliza la propiedad `list-type` para cambiar el estilo a un listado de archivos.
::: demo ::: demo
```html ```html
@ -272,7 +272,7 @@ Use `list-type` to change the fileList style.
``` ```
::: :::
### FileList with thumbnail ### Lista de archivos con miniatura
::: demo ::: demo
```html ```html
@ -283,8 +283,8 @@ Use `list-type` to change the fileList style.
:on-remove="handleRemove" :on-remove="handleRemove"
:file-list="fileList2" :file-list="fileList2"
list-type="picture"> list-type="picture">
<el-button size="small" type="primary">Click to upload</el-button> <el-button size="small" type="primary">Clic para subir archivo</el-button>
<div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div> <div slot="tip" class="el-upload__tip">Solo archivos jpg/png con un tamaño menor de 500kb</div>
</el-upload> </el-upload>
<script> <script>
export default { export default {
@ -306,9 +306,9 @@ Use `list-type` to change the fileList style.
``` ```
::: :::
### File list control ### Control de lista de archivos
Use `on-change` hook function to control upload file list Utiliza el _hook_ `on-change` para controlar la funcionalidad de la lista de archivos subidos.
::: demo ::: demo
```html ```html
@ -317,8 +317,8 @@ Use `on-change` hook function to control upload file list
action="https://jsonplaceholder.typicode.com/posts/" action="https://jsonplaceholder.typicode.com/posts/"
:on-change="handleChange" :on-change="handleChange"
:file-list="fileList3"> :file-list="fileList3">
<el-button size="small" type="primary">Click to upload</el-button> <el-button size="small" type="primary">Clic para subir archivo</el-button>
<div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div> <div slot="tip" class="el-upload__tip">Solo archivos jpg/png con un tamaño menor de 500kb</div>
</el-upload> </el-upload>
<script> <script>
export default { export default {
@ -345,9 +345,9 @@ Use `on-change` hook function to control upload file list
``` ```
::: :::
### Drag to upload ### Arrastrar para cargar archivo
You can drag your file to a certain area to upload it. Puedes arrastrar el archivo dentro de un área en especifico para cargar el archivo.
::: demo ::: demo
```html ```html
@ -360,13 +360,13 @@ You can drag your file to a certain area to upload it.
:file-list="fileList" :file-list="fileList"
multiple> multiple>
<i class="el-icon-upload"></i> <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__text">Suelta tu archivo aquí o <em>haz clic para cargar</em></div>
<div class="el-upload__tip" slot="tip">jpg/png files with a size less than 500kb</div> <div slot="tip" class="el-upload__tip">Solo archivos jpg/png con un tamaño menor de 500kb</div>
</el-upload> </el-upload>
``` ```
::: :::
### Manual upload ### Carga normal
::: demo ::: demo
```html ```html
@ -375,9 +375,9 @@ You can drag your file to a certain area to upload it.
ref="upload" ref="upload"
action="https://jsonplaceholder.typicode.com/posts/" action="https://jsonplaceholder.typicode.com/posts/"
:auto-upload="false"> :auto-upload="false">
<el-button slot="trigger" size="small" type="primary">select file</el-button> <el-button slot="trigger" size="small" type="primary">Selecciona un archivo</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">upload to server</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">Cargar al servidor</el-button>
<div class="el-upload__tip" slot="tip">jpg/png files with a size less than 500kb</div> <div slot="tip" class="el-upload__tip">Solo archivos jpg/png con un tamaño menor de 500kb</div>
</el-upload> </el-upload>
<script> <script>
export default { export default {
@ -391,36 +391,36 @@ You can drag your file to a certain area to upload it.
``` ```
::: :::
### Attributes ### Atributos
Attribute | Description | Type | Accepted Values | Default Atributo | Descripción | Tipo | Valores aceptados | Por defecto
----| ----| ----| ----| ---- ----| ----| ----| ----| ----
action | required, request URL | string | — | — action | obligatorio, URL de la petición | string | — | —
headers | request headers | object | — | — headers | cabeceras de la petición | object | — | —
multiple | whether uploading multiple files is permitted | boolean | — | — multiple | especifica si se permite subir múltiples archivos | boolean | — | —
data | additions options of request | object | — | — data | opciones adicionales de la petición | object | — | —
name | key name for uploaded file | string | — | file name | nombre clave del archivo | string | — | file
with-credentials | whether cookies are sent | boolean | — |false with-credentials | especifica si enviará cookies | boolean | — |false
show-file-list | whether to show the uploaded file list | boolean | — | true show-file-list | especifica si se debe mostrar la lista de archivos cargados | boolean | — | true
drag | whether to activate drag and drop mode | boolean | — | false drag | se especifica si se activará el modo arrastrar y soltar | 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 | — | — accept | acepta [tipos de archvios](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-accept), puede no funcionar cuando `thumbnail-mode` esta en `true` | string | — | —
on-preview | hook function when clicking the uploaded files | function(file) | — | — on-preview | _hook_ lanzado al hacer clic en los archivos subidos | function(file) | — | —
on-remove | hook function when files are removed | function(file, fileList) | — | — on-remove | _hook_ lanzado cuando los archivos son eliminados | function(file, fileList) | — | —
on-success | hook function when uploaded successfully | function(response, file, fileList) | — | — on-success | _hook_ lanzado cuando los archivos fueron cargados correctamente | function(response, file, fileList) | — | —
on-error | hook function when some errors occurs | function(err, file, fileList) | — | — on-error | _hook_ lanzado cuando han ocurrido algunos errores | function(err, file, fileList) | — | —
on-progress | hook function when some progress occurs | function(event, file, fileList) | — | — | on-progress | _hook_ lanzado cuando se produce algún progreso | function(event, file, fileList) | — | — |
on-change | hook function when select file or upload file success or upload file fail | function(file, fileList) | — | — | on-change | _hook_ lanzado cuando el archivo seleccionado se carga correctamente o falla | 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-upload | _hook_ lanzado antes de que el archivo sea cargado. Si este devuelve `true` o `Promise` entonces será rechazado, la carga puede ser cancelada | function(file) | — | —
thumbnail-mode | whether thumbnail is displayed | boolean | — | false thumbnail-mode | especifica si se mostrará la miniatura | boolean | — | false
file-list | default uploaded files, e.g. [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] | array | — | [] file-list | archivos cargados por defecto, por ejemplo, [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] | array | — | []
list-type | type of fileList | string | text/picture/picture-card | text | list-type | tipo de lista de archivos | string | text/picture/picture-card | text |
auto-upload | whether to auto upload file | boolean | — | true | auto-upload | se especifica si se autocargan archivos | boolean | — | true |
http-request | override default xhr behavior, allowing you to implement your own upload-file's request | function | — | — | http-request | sobreescribe el comportamiento por defecto de xhr, permitiendo implementar tu propia petición de carga de archivos | function | — | — |
disabled | whether to disable upload | boolean | — | false | disabled | especifica si se deshabilita la carga de archivos | boolean | — | false |
limit | maximum number of uploads allowed | number | — | — | limit | número máximo de cargas permitidas | number | — | — |
on-exceed | hook function when limit is exceeded | function(files, fileList) | — | - | on-exceed | _hook_ lanzado cuando el límite ha sido excedido | function(files, fileList) | — | - |
### Methods ### Métodos
| Methods Name | Description | Parameters | | Nombre del método | Descripción | Parametros |
|---------- |-------- |---------- | |---------- |-------- |---------- |
| clearFiles | clear the uploaded file list (this method is not supported in the `before-upload` hook) | — | | clearFiles | limpia la lista de archivos cargados (este método no esta soportado en el _hook_ `before-upload`) | — |
| abort | cancel upload request | file: fileList's item | | abort | cancela la petición de carga | file: fileList's item |

View File

@ -101,6 +101,7 @@
value8: '', value8: '',
value9: '', value9: '',
value10: [], value10: [],
value11: [],
loading: false, 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"] 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"]
}; };
@ -319,7 +320,7 @@
适用性较广的基础多选,用 Tag 展示已选项 适用性较广的基础多选,用 Tag 展示已选项
:::demo 为`el-select`设置`multiple`属性即可启用多选,此时`v-model`的值为当前选中值所组成的数组 :::demo 为`el-select`设置`multiple`属性即可启用多选,此时`v-model`的值为当前选中值所组成的数组。默认情况下选中值会以 Tag 的形式展现,你也可以设置`collapse-tags`属性将它们合并为一段文字。
```html ```html
<template> <template>
<el-select v-model="value5" multiple placeholder="请选择"> <el-select v-model="value5" multiple placeholder="请选择">
@ -330,6 +331,20 @@
:value="item.value"> :value="item.value">
</el-option> </el-option>
</el-select> </el-select>
<el-select
v-model="value11"
multiple
collapse-tags
style="margin-left: 20px;"
placeholder="请选择">
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value">
</el-option>
</el-select>
</template> </template>
<script> <script>
@ -645,6 +660,7 @@
| value-key | 作为 value 唯一标识的键名,绑定值为对象类型时必填 | string | — | value | | value-key | 作为 value 唯一标识的键名,绑定值为对象类型时必填 | string | — | value |
| size | 输入框尺寸 | string | large/small/mini | — | | size | 输入框尺寸 | string | large/small/mini | — |
| clearable | 单选时是否可以清空选项 | boolean | — | false | | clearable | 单选时是否可以清空选项 | boolean | — | false |
| collapse-tags | 多选时是否将选中值按文字的形式展示 | boolean | — | false |
| multiple-limit | 多选时用户最多可以选择的项目数,为 0 则不限制 | number | — | 0 | | multiple-limit | 多选时用户最多可以选择的项目数,为 0 则不限制 | number | — | 0 |
| name | select input 的 name 属性 | string | — | — | | name | select input 的 name 属性 | string | — | — |
| placeholder | 占位符 | string | — | 请选择 | | placeholder | 占位符 | string | — | 请选择 |

View File

@ -64,32 +64,32 @@
{ {
"lang": "es", "lang": "es",
"demo-block": { "demo-block": {
"hide-text": "Hide", "hide-text": "Ocultar",
"show-text": "Expand", "show-text": "Mostrar",
"button-text": "Try it!", "button-text": "Probar",
"tooltip-text": "Run this demo on jsfiddle.net" "tooltip-text": "Prueba este ejemplo en jsfiddle.net"
}, },
"footer": { "footer": {
"links": "Links", "links": "Enlaces",
"repo": "GitHub", "repo": "GitHub",
"community": "Community", "community": "Comunidad",
"changelog": "Changelog", "changelog": "Lista de cambios",
"theme": "Theme CLI tool", "theme": "Generador de temas por CLI",
"preview": "Online theme generator", "preview": "Generador de temas en línea",
"faq": "FAQ", "faq": "FAQ",
"gitter": "Gitter", "gitter": "Gitter",
"starter": "Starter kit", "starter": "Kit de inicio",
"feedback": "Feedback", "feedback": "Comentarios",
"contribution": "Contribution", "contribution": "Contribución",
"eleme": "Eleme" "eleme": "Eleme"
}, },
"header": { "header": {
"guide": "Guide", "guide": "Guía",
"components": "Component", "components": "Componentes",
"resource": "Resource" "resource": "Recursos"
}, },
"nav": { "nav": {
"dropdown": "Version: " "dropdown": "Versión: "
} }
} }
] ]

View File

@ -190,16 +190,16 @@
"lang": "es", "lang": "es",
"pages": { "pages": {
"index": { "index": {
"1": "A Desktop UI Library", "1": "Un kit de interfaz de usuario para la web",
"2": "Element, a Vue 2.0 based component library for developers, designers and product managers", "2": "Element, una librería de componentes basada en Vue 2.0 para desarrolladores, diseñadores y jefes de producto",
"3": "Guide", "3": "Guía",
"4": "Understand the design guidelines, helping designers build product that's logically sound, reasonably structured and easy to use.", "4": "Entender los líneamientos de diseño, ayudando a diseñadores a crear productos que sean lógicos, razonablemente estructurados y fáciles de usar.",
"5": "View Detail", "5": "Ver detalle",
"6": "Component", "6": "Componentes",
"7": "Experience interaction details by strolling through component demos. Use encapsulated code to improve developing efficiency.", "7": "Experimenta la interacción al pasear con los ejemplos de los componentes. Utiliza el código encapsulado para mejorar la eficiencia en el desarrollo.",
"8": "Resource", "8": "Recursos",
"9": "Download relevant design resources for shaping page prototype or visual draft, increasing design efficiency.", "9": "Descarga los recursos de diseño relevantes para dar forma a un prototipo o borrador, aumentando la eficiencia del diseño.",
"lang": "en-US", "lang": "es",
"titleSize": "34", "titleSize": "34",
"paraSize": "18", "paraSize": "18",
"theatreParam": "{ maxSpeed: 100 }", "theatreParam": "{ maxSpeed: 100 }",
@ -208,76 +208,76 @@
}, },
"component": {}, "component": {},
"changelog": { "changelog": {
"1": "Changelog", "1": "Lista de cambios",
"2": "en-US" "2": "en-US"
}, },
"design": { "design": {
"1": "Design Disciplines", "1": "Disciplinas de diseño",
"2": "Consistency", "2": "Consistencia",
"3": "", "3": "",
"4": "Feedback", "4": "Comentarios",
"5": "", "5": "",
"6": "Efficiency", "6": "Eficiencia",
"7": "", "7": "",
"8": "Controllability", "8": "Control",
"9": "", "9": "",
"10": "Consistency", "10": "Consistencia",
"11": "Consistent with real life: ", "11": "Consistente con la vida real: ",
"12": "in line with the process and logic of real life, and comply with languages and habits that the users are used to.", "12": "en línea con el proceso y la vida real, y cumple con los idiomas y hábitos a los que los usuarios están acostumbrados.",
"13": "Consistent within interface: ", "13": "Consistente dentro de la interfaz: ",
"14": "all elements should be consistent, such as: design style, icons and texts, position of elements, etc.", "14": "todos los elementos deben ser consistentes, como: estilo de diseño, iconos y texto, posición de los elementos, etc.",
"15": "Feedback", "15": "Comentarios",
"16": "Operation feedback: ", "16": "Comentarios sobre la operación: ",
"17": "enable the users to clearly perceive their operations by style updates and interactive effects.", "17": "Permite a los usuarios percibir claramente las operaciones mediante actualizaciones de estilo y efectos interactivos.",
"18": "Visual feedback: ", "18": "Comentarios visuales: ",
"19": "reflect current state by updating or rearranging elements of the page.", "19": "Refleja el estado actual al actualizar o reorganizar los elementos de la página.",
"20": "Efficiency", "20": "Eficiencia",
"21": "Simplify the process: ", "21": "Simplifica el proceso: ",
"22": "keep operating process simple and intuitive.", "22": "Mantiene el proceso operativo simple e intuitivo.",
"23": "Definite and clear: ", "23": "Bien definido y claro: ",
"24": "enunciate your intentions clearly so that the users can quickly understand and make decisions.", "24": "Expresa las intenciones claramente para que los usuarios puedan comprender y tomar decisiones rápidamente.",
"25": "Easy to identify: ", "25": "Fácil de identificar: ",
"26": "the interface should be straightforward, which helps the users to identify and frees them from memorizing and recalling.", "26": "La interfaz debe ser sencilla, lo que permitirá a los usuarios a identificar y liberarlos de la memorización y recuerdos.",
"27": "Controllability", "27": "Control",
"28": "Decision making: ", "28": "Toma de decisiones: ",
"29": "giving advices about operations is acceptable, but do not make decisions for the users.", "29": "Brindar consejos sobres las operaciones es aceptable, pero no tomar desiciones para los usuarios.",
"30": "Controlled consequences: ", "30": "Consecuencias controladas: ",
"31": "users should be granted the freedom to operate, including canceling, aborting or terminating current operation." "31": "Los usuarios deben tener la libertad de operar, incluida la cancelación, el aborto o la terminación de las operaciones actuales."
}, },
"guide": { "guide": {
"1": "Design Disciplines", "1": "Disciplinas de diseño",
"2": "Navigation" "2": "Navegación"
}, },
"nav": { "nav": {
"1": "Navigation", "1": "Navegación",
"2": "Navigation focuses on solving the users' problems of where to go and how to get there. Generally it can be categorized into 'sidebar navigation' and 'top navigation'.", "2": "La navegación se centra en resolver los problemas de los usuarios sobre donde ir y como llegar ahí. En general, se puede categorizar en 'navegación de barra lateral' y 'navegación superior'.",
"3": "Choose the right navigation", "3": "Elige la navegación correcta",
"4": "An appropriate navigation gives users a smooth experience, while an inappropriate one leads to confusion. Here are the differences between sidebar navigation and top navigation", "4": "Una navegación apropiada provee a los usuarios una mejor experiencia, mientras que una inapropiada genera confusión. Esta es la diferencia entre la navegación de la barra lateral y la navegación superior.",
"5": "Side Navigation", "5": "Navegación lateral",
"6": "Fix the navigation at the left edge, thus improves its visibility, making it easier to switch between pages. In this case, the top area of the page holds commonly used tools, e.g. search bar, help button, notice button, etc. Suitable for background management or utility websites.", "6": "Fija la navegación del lado izquierdo, esto permitirá una mejor visibilidad, lo que facilitará el cambio de pagina. En este caso, el área superior de la pagina contiene herramientas comúnmente utilizadas, por ejemplo, barra de búsqueda, botón de ayuda, botón de aviso, etc. Adecuado para sitios web de gestión.",
"7": "Level 1 categories", "7": "Categorías de Nivel 1",
"8": "Suitable for simply structured sites with only one level of pages. No breadcrumb is needed.", "8": "Adecuado para sitios con una estructura simple con un solo nivel de páginas. No se necesita un 'breadcrumb'.",
"9": "Level 2 categories", "9": "Categorías de Nivel 2",
"10": "Sidebar displays up to two levels of navigation. Breadcrumbs are recommended in combination of second level navigation, making it easier for the users to locate and navigate.", "10": "La barra lateral muestra hasta dos niveles de navegación. Se recomienda utilizar un 'breadcrumb' en combinación con la navegación de segundo nivel, lo que facilita la localización y navegación de los usuarios.",
"11": "Level 3 categories", "11": "Categorías de Nivel 3",
"12": "Suitable for complicated utility websites. The left sidebar holds first level navigation, and the middle column displays second level navigation or other utility options.", "12": "Adecuado para sitios web bastante complejos. La barra lateral izquierda contiene navegación de primer nivel, y la columna central muestra navegación de segundo nivel u otras opciones de utilidad.",
"13": "Top Navigation", "13": "Navegación superior",
"14": "Conforms to the normal browsing order from top to bottom, which makes things more natural. The navigation amount and text length are limited to the width of the top.", "14": "Se ajusta de acuerdo a la exploración normal de arriba a abajo, lo que hace que las cosas sean más naturales. La cantidad de navegación y la longitud del texto están limitadas al ancho de la parte superior.",
"15": "Suitable for sites with few navigations and large chunks." "15": "Adecuado para sitios con pocas navegaciones y grandes trozos."
}, },
"resource": { "resource": {
"1": "Resource", "1": "Recursos",
"2": "Under construction.", "2": "En construcción",
"3": "Axure Components", "3": "Componetes de Axure",
"4": "By importing Element UI in Axure, you can easily apply all the components we provide during interaction design.", "4": "Mediante la importación de elementos de interfaz de usuario en Axure, se puede aplicar fácilmente a todos los componentes que proporcionamos durante el diseño de interacción.",
"5": "Download", "5": "Descarga",
"6": "Sketch Template", "6": "Plantilla de Sketch",
"7": "Apply components from Element template, so you can improve design efficiency while keeping a unified visual style.", "7": "Aplica componentes de la plantilla Element para que pueda mejorarla eficiencia del diseño manteniendo un estilo visual unificado.",
"8": "Interaction Design Documentation", "8": "Documentación de diseño de interacción",
"9": "Take a closer look at the interaction design documentation. Learn more details of each component from a microcosmic perspective.", "9": "Eche un vistazo más de cerca a la documentación de diseño de interacción. Conoce más detalles de cada componente desde una perspectiva microcósmica.",
"paraHeight": "1.6", "paraHeight": "1.6",
"placeholder1": "Under construction", "placeholder1": "En construcción",
"placeholder2": "Please wait while we prepare the design resources" "placeholder2": "Por favor espere mientras preparamos los recursos de diseño"
} }
} }
} }

View File

@ -12,9 +12,9 @@
"resource": "Resource | Element" "resource": "Resource | Element"
}, },
"es": { "es": {
"home": "Element - A Desktop UI Toolkit for Web", "home": "Element - Un kit de interfaz de usuario para la web",
"guide": "Guide | Element", "guide": "Guía | Element",
"component": "Component | Element", "component": "Componentes | Element",
"resource": "Resource | Element" "resource": "Recursos | Element"
} }
} }

View File

@ -10,7 +10,7 @@
}, },
{ {
"name": "Element Angular", "name": "Element Angular",
"href": "https://eleme.github.io/element-angular/" "href": "https://element-angular.faas.ele.me/"
}, },
{ {
"name": "开发指南", "name": "开发指南",
@ -260,7 +260,7 @@
}, },
{ {
"name": "Element Angular", "name": "Element Angular",
"href": "https://eleme.github.io/element-angular/" "href": "https://element-angular.faas.ele.me/"
}, },
{ {
"name": "Development", "name": "Development",

View File

@ -1 +1 @@
{"1.0.9":"1.0","1.1.6":"1.1","1.2.9":"1.2","1.3.7":"1.3","1.4.9":"1.4","2.0.3":"2.0"} {"1.0.9":"1.0","1.1.6":"1.1","1.2.9":"1.2","1.3.7":"1.3","1.4.9":"1.4","2.0.4":"2.0"}

View File

@ -1,6 +1,6 @@
{ {
"name": "element-ui", "name": "element-ui",
"version": "2.0.3", "version": "2.0.4",
"description": "A Component Library for Vue.js.", "description": "A Component Library for Vue.js.",
"main": "lib/element-ui.common.js", "main": "lib/element-ui.common.js",
"files": [ "files": [
@ -82,6 +82,7 @@
"css-loader": "^0.28.7", "css-loader": "^0.28.7",
"es6-promise": "^4.0.5", "es6-promise": "^4.0.5",
"eslint": "^3.10.2", "eslint": "^3.10.2",
"eslint-plugin-json": "^1.2.0",
"extract-text-webpack-plugin": "^3.0.1", "extract-text-webpack-plugin": "^3.0.1",
"file-loader": "^1.1.5", "file-loader": "^1.1.5",
"file-save": "^0.2.0", "file-save": "^0.2.0",

View File

@ -10,9 +10,12 @@
]" ]"
@click="handleClick" @click="handleClick"
@mouseenter="inputHover = true" @mouseenter="inputHover = true"
@focus="inputHover = true"
@mouseleave="inputHover = false" @mouseleave="inputHover = false"
@blur="inputHover = false"
ref="reference" ref="reference"
v-clickoutside="handleClickoutside" v-clickoutside="handleClickoutside"
@keydown="handleKeydown"
> >
<el-input <el-input
ref="input" ref="input"
@ -63,6 +66,7 @@ import emitter from 'element-ui/src/mixins/emitter';
import Locale from 'element-ui/src/mixins/locale'; import Locale from 'element-ui/src/mixins/locale';
import { t } from 'element-ui/src/locale'; import { t } from 'element-ui/src/locale';
import debounce from 'throttle-debounce/debounce'; import debounce from 'throttle-debounce/debounce';
import { generateId } from 'element-ui/src/utils/util';
const popperMixin = { const popperMixin = {
props: { props: {
@ -149,6 +153,10 @@ export default {
beforeFilter: { beforeFilter: {
type: Function, type: Function,
default: () => (() => {}) default: () => (() => {})
},
hoverThreshold: {
type: Number,
default: 500
} }
}, },
@ -191,11 +199,15 @@ export default {
}, },
cascaderSize() { cascaderSize() {
return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size; return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
},
id() {
return generateId();
} }
}, },
watch: { watch: {
menuVisible(value) { menuVisible(value) {
this.$refs.input.$refs.input.setAttribute('aria-expanded', value);
value ? this.showMenu() : this.hideMenu(); value ? this.showMenu() : this.hideMenu();
}, },
value(value) { value(value) {
@ -204,6 +216,10 @@ export default {
currentValue(value) { currentValue(value) {
this.dispatch('ElFormItem', 'el.form.change', [value]); this.dispatch('ElFormItem', 'el.form.change', [value]);
}, },
currentLabels(value) {
const inputLabel = this.showAllLevels ? value.join('/') : value[value.length - 1] ;
this.$refs.input.$refs.input.setAttribute('value', inputLabel);
},
options: { options: {
deep: true, deep: true,
handler(value) { handler(value) {
@ -224,10 +240,13 @@ export default {
this.menu.expandTrigger = this.expandTrigger; this.menu.expandTrigger = this.expandTrigger;
this.menu.changeOnSelect = this.changeOnSelect; this.menu.changeOnSelect = this.changeOnSelect;
this.menu.popperClass = this.popperClass; this.menu.popperClass = this.popperClass;
this.menu.hoverThreshold = this.hoverThreshold;
this.popperElm = this.menu.$el; this.popperElm = this.menu.$el;
this.menu.$refs.menus[0].setAttribute('id', `cascader-menu-${this.id}`);
this.menu.$on('pick', this.handlePick); this.menu.$on('pick', this.handlePick);
this.menu.$on('activeItemChange', this.handleActiveItemChange); this.menu.$on('activeItemChange', this.handleActiveItemChange);
this.menu.$on('menuLeave', this.doDestroy); this.menu.$on('menuLeave', this.doDestroy);
this.menu.$on('closeInside', this.handleClickoutside);
}, },
showMenu() { showMenu() {
if (!this.menu) { if (!this.menu) {
@ -245,6 +264,7 @@ export default {
hideMenu() { hideMenu() {
this.inputValue = ''; this.inputValue = '';
this.menu.visible = false; this.menu.visible = false;
this.$refs.input.focus();
}, },
handleActiveItemChange(value) { handleActiveItemChange(value) {
this.$nextTick(_ => { this.$nextTick(_ => {
@ -252,6 +272,23 @@ export default {
}); });
this.$emit('active-item-change', value); this.$emit('active-item-change', value);
}, },
handleKeydown(e) {
const keyCode = e.keyCode;
if (keyCode === 13) {
this.handleClick();
} else if (keyCode === 40) { // down
this.menuVisible = true; //
setTimeout(() => {
const firstMenu = this.popperElm.querySelectorAll('.el-cascader-menu')[0];
firstMenu.querySelectorAll("[tabindex='-1']")[0].focus();
});
e.stopPropagation();
e.preventDefault();
} else if (keyCode === 27 || keyCode === 9) { // esc tab
this.inputValue = '';
if (this.menu) this.menu.visible = false;
}
},
handlePick(value, close = true) { handlePick(value, close = true) {
this.currentValue = value; this.currentValue = value;
this.$emit('input', value); this.$emit('input', value);

View File

@ -1,6 +1,7 @@
<script> <script>
import { isDef } from 'element-ui/src/utils/shared'; import { isDef } from 'element-ui/src/utils/shared';
import scrollIntoView from 'element-ui/src/utils/scroll-into-view'; import scrollIntoView from 'element-ui/src/utils/scroll-into-view';
import { generateId } from 'element-ui/src/utils/util';
const copyArray = (arr, props) => { const copyArray = (arr, props) => {
if (!arr || !Array.isArray(arr) || !props) return arr; if (!arr || !Array.isArray(arr) || !props) return arr;
@ -39,7 +40,8 @@
value: [], value: [],
expandTrigger: 'click', expandTrigger: 'click',
changeOnSelect: false, changeOnSelect: false,
popperClass: '' popperClass: '',
hoverTimer: 0
}; };
}, },
@ -94,6 +96,9 @@
formatOptions(optionsCopy); formatOptions(optionsCopy);
return loadActiveOptions(optionsCopy); return loadActiveOptions(optionsCopy);
} }
},
id() {
return generateId();
} }
}, },
@ -135,11 +140,41 @@
activeOptions, activeOptions,
visible, visible,
expandTrigger, expandTrigger,
popperClass popperClass,
hoverThreshold
} = this; } = this;
let itemId = null;
let itemIndex = 0;
let hoverMenuRefs = {};
const hoverMenuHandler = e => {
const offsetX = e.offsetX;
const width = hoverMenuRefs.activeMenu.offsetWidth;
const height = hoverMenuRefs.activeMenu.offsetHeight;
if (e.target === hoverMenuRefs.activeItem) {
clearTimeout(this.hoverTimer);
const {activeItem} = hoverMenuRefs;
const offsetY_top = activeItem.offsetTop;
const offsetY_Bottom = offsetY_top + activeItem.offsetHeight;
hoverMenuRefs.hoverZone.innerHTML = `
<path style="pointer-events: auto;" fill="transparent" d="M${offsetX} ${offsetY_top} L${width} 0 V${offsetY_top} Z" />
<path style="pointer-events: auto;" fill="transparent" d="M${offsetX} ${offsetY_Bottom} L${width} ${height} V${offsetY_Bottom} Z" />
`;
} else {
if (!this.hoverTimer) {
this.hoverTimer = setTimeout(() => {
hoverMenuRefs.hoverZone.innerHTML = '';
}, hoverThreshold);
}
}
};
const menus = this._l(activeOptions, (menu, menuIndex) => { const menus = this._l(activeOptions, (menu, menuIndex) => {
let isFlat = false; let isFlat = false;
const menuId = `menu-${this.id}-${ menuIndex}`;
const ownsId = `menu-${this.id}-${ menuIndex + 1 }`;
const items = this._l(menu, item => { const items = this._l(menu, item => {
const events = { const events = {
on: {} on: {}
@ -148,12 +183,52 @@
if (item.__IS__FLAT__OPTIONS) isFlat = true; if (item.__IS__FLAT__OPTIONS) isFlat = true;
if (!item.disabled) { if (!item.disabled) {
// keydown up/down/left/right/enter
events.on.keydown = (ev) => {
const keyCode = ev.keyCode;
if (![37, 38, 39, 40, 13, 9, 27].indexOf(keyCode) > -1) {
return;
}
const currentEle = ev.target;
const parentEle = this.$refs.menus[menuIndex];
const menuItemList = parentEle.querySelectorAll("[tabindex='-1']");
const currentIndex = Array.prototype.indexOf.call(menuItemList, currentEle); //
let nextIndex, nextMenu;
if ([38, 40].indexOf(keyCode) > -1) {
if (keyCode === 38) { // up
nextIndex = currentIndex !== 0 ? (currentIndex - 1) : currentIndex;
} else if (keyCode === 40) { // down
nextIndex = currentIndex !== (menuItemList.length - 1) ? currentIndex + 1 : currentIndex;
}
menuItemList[nextIndex].focus();
} else if (keyCode === 37) { // left
if (menuIndex !== 0) {
const previousMenu = this.$refs.menus[menuIndex - 1];
previousMenu.querySelector('[aria-expanded=true]').focus();
}
} else if (keyCode === 39) { // right
if (item.children) {
// menu menumenuitem
nextMenu = this.$refs.menus[menuIndex + 1];
nextMenu.querySelectorAll("[tabindex='-1']")[0].focus();
}
} else if (keyCode === 13) {
if (!item.children) {
const id = currentEle.getAttribute('id');
parentEle.setAttribute('aria-activedescendant', id);
this.select(item, menuIndex);
this.$nextTick(() => this.scrollMenu(this.$refs.menus[menuIndex]));
}
} else if (keyCode === 9 || keyCode === 27) { // esc tab
this.$emit('closeInside');
}
};
if (item.children) { if (item.children) {
let triggerEvent = { let triggerEvent = {
click: 'click', click: 'click',
hover: 'mouseenter' hover: 'mouseenter'
}[expandTrigger]; }[expandTrigger];
events.on[triggerEvent] = () => { events.on[triggerEvent] = events.on['focus'] = () => { // focus
this.activeItem(item, menuIndex); this.activeItem(item, menuIndex);
this.$nextTick(() => { this.$nextTick(() => {
// adjust self and next level // adjust self and next level
@ -168,7 +243,10 @@
}; };
} }
} }
if (!item.disabled && !item.children) { // no children set id
itemId = `${menuId}-${itemIndex}`;
itemIndex++;
}
return ( return (
<li <li
class={{ class={{
@ -177,7 +255,14 @@
'is-active': item.value === activeValue[menuIndex], 'is-active': item.value === activeValue[menuIndex],
'is-disabled': item.disabled 'is-disabled': item.disabled
}} }}
ref={item.value === activeValue[menuIndex] ? 'activeItem' : null}
{...events} {...events}
tabindex= { item.disabled ? null : -1 }
role="menuitem"
aria-haspopup={ !!item.children }
aria-expanded={ item.value === activeValue[menuIndex] }
id = { itemId }
aria-owns = { !item.children ? null : ownsId }
> >
{item.label} {item.label}
</li> </li>
@ -188,19 +273,68 @@
menuStyle.minWidth = this.inputWidth + 'px'; menuStyle.minWidth = this.inputWidth + 'px';
} }
const isHoveredMenu = expandTrigger === 'hover' && activeValue.length - 1 === menuIndex;
const hoverMenuEvent = {
on: {
}
};
if (isHoveredMenu) {
hoverMenuEvent.on.mousemove = hoverMenuHandler;
menuStyle.position = 'relative';
}
return ( return (
<ul <ul
class={{ class={{
'el-cascader-menu': true, 'el-cascader-menu': true,
'el-cascader-menu--flexible': isFlat 'el-cascader-menu--flexible': isFlat
}} }}
{...hoverMenuEvent}
style={menuStyle} style={menuStyle}
refInFor refInFor
ref="menus"> ref="menus"
role="menu"
id = { menuId }
>
{items} {items}
{
isHoveredMenu
? (<svg
ref="hoverZone"
style={{
position: 'absolute',
top: 0,
height: '100%',
width: '100%',
left: 0,
pointerEvents: 'none'
}}
></svg>) : null
}
</ul> </ul>
); );
}); });
if (expandTrigger === 'hover') {
this.$nextTick(() => {
const activeItem = this.$refs.activeItem;
if (activeItem) {
const activeMenu = activeItem.parentElement;
const hoverZone = this.$refs.hoverZone;
hoverMenuRefs = {
activeMenu,
activeItem,
hoverZone
};
} else {
hoverMenuRefs = {};
}
});
}
return ( return (
<transition name="el-zoom-in-top" on-before-enter={this.handleMenuEnter} on-after-leave={this.handleMenuLeave}> <transition name="el-zoom-in-top" on-before-enter={this.handleMenuEnter} on-after-leave={this.handleMenuLeave}>
<div <div

View File

@ -6,6 +6,8 @@
'el-dropdown-menu__item--divided': divided 'el-dropdown-menu__item--divided': divided
}" }"
@click="handleClick" @click="handleClick"
:aria-disabled="disabled"
:tabindex="disabled ? null : -1"
> >
<slot></slot> <slot></slot>
</li> </li>

View File

@ -4,6 +4,7 @@
import Migrating from 'element-ui/src/mixins/migrating'; import Migrating from 'element-ui/src/mixins/migrating';
import ElButton from 'element-ui/packages/button'; import ElButton from 'element-ui/packages/button';
import ElButtonGroup from 'element-ui/packages/button-group'; import ElButtonGroup from 'element-ui/packages/button-group';
import { generateId } from 'element-ui/src/utils/util';
export default { export default {
name: 'ElDropdown', name: 'ElDropdown',
@ -61,25 +62,43 @@
return { return {
timeout: null, timeout: null,
visible: false, visible: false,
triggerElm: null triggerElm: null,
menuItems: null,
menuItemsArray: null,
dropdownElm: null,
focusing: false
}; };
}, },
computed: { computed: {
dropdownSize() { dropdownSize() {
return this.size || (this.$ELEMENT || {}).size; return this.size || (this.$ELEMENT || {}).size;
},
listId() {
return `dropdown-menu-${generateId()}`;
} }
}, },
mounted() { mounted() {
this.$on('menu-item-click', this.handleMenuItemClick); this.$on('menu-item-click', this.handleMenuItemClick);
this.initEvent(); this.initEvent();
this.initAria();
}, },
watch: { watch: {
visible(val) { visible(val) {
this.broadcast('ElDropdownMenu', 'visible', val); this.broadcast('ElDropdownMenu', 'visible', val);
this.$emit('visible-change', val); this.$emit('visible-change', val);
},
focusing(val) {
const selfDefine = this.$el.querySelector('.el-dropdown-selfdefine');
if (selfDefine) { //
if (val) {
selfDefine.className += ' focusing';
} else {
selfDefine.className = selfDefine.className.replace('focusing', '');
}
}
} }
}, },
@ -100,6 +119,8 @@
}, },
hide() { hide() {
if (this.triggerElm.disabled) return; if (this.triggerElm.disabled) return;
this.removeTabindex();
this.resetTabindex(this.triggerElm);
clearTimeout(this.timeout); clearTimeout(this.timeout);
this.timeout = setTimeout(() => { this.timeout = setTimeout(() => {
this.visible = false; this.visible = false;
@ -109,18 +130,98 @@
if (this.triggerElm.disabled) return; if (this.triggerElm.disabled) return;
this.visible = !this.visible; this.visible = !this.visible;
}, },
handleTriggerKeyDown(ev) {
const keyCode = ev.keyCode;
if ([38, 40].indexOf(keyCode) > -1) { // up/down
this.removeTabindex();
this.resetTabindex(this.menuItems[0]);
this.menuItems[0].focus();
ev.preventDefault();
ev.stopPropagation();
} else if (keyCode === 13) { // space enter
this.handleClick();
} else if ([9, 27].indexOf(keyCode) > -1) { // tab || esc
this.hide();
}
return;
},
handleItemKeyDown(ev) {
const keyCode = ev.keyCode;
const target = ev.target;
const currentIndex = this.menuItemsArray.indexOf(target);
const max = this.menuItemsArray.length - 1;
let nextIndex;
if ([38, 40].indexOf(keyCode) > -1) { // up/down
if (keyCode === 38) { // up
nextIndex = currentIndex !== 0 ? currentIndex - 1 : 0;
} else { // down
nextIndex = currentIndex < max ? currentIndex + 1 : max;
}
this.removeTabindex();
this.resetTabindex(this.menuItems[nextIndex]);
this.menuItems[nextIndex].focus();
ev.preventDefault();
ev.stopPropagation();
} else if (keyCode === 13) { // enter
this.triggerElm.focus();
target.click();
if (!this.hideOnClick) { // click
this.visible = false;
}
} else if ([9, 27].indexOf(keyCode) > -1) { // tab // esc
this.hide();
this.triggerElm.focus();
}
return;
},
resetTabindex(ele) { // tab
this.removeTabindex();
ele.setAttribute('tabindex', '0'); //
},
removeTabindex() {
this.triggerElm.setAttribute('tabindex', '-1');
this.menuItemsArray.forEach((item) => {
item.setAttribute('tabindex', '-1');
});
},
initAria() {
this.dropdownElm.setAttribute('id', this.listId);
this.triggerElm.setAttribute('aria-haspopup', 'list');
this.triggerElm.setAttribute('aria-controls', this.listId);
this.menuItems = this.dropdownElm.querySelectorAll("[tabindex='-1']");
this.menuItemsArray = Array.prototype.slice.call(this.menuItems);
if (!this.splitButton) { //
this.triggerElm.setAttribute('role', 'button');
this.triggerElm.setAttribute('tabindex', '0');
this.triggerElm.className += ' el-dropdown-selfdefine'; //
}
},
initEvent() { initEvent() {
let { trigger, show, hide, handleClick, splitButton } = this; let { trigger, show, hide, handleClick, splitButton, handleTriggerKeyDown, handleItemKeyDown } = this;
this.triggerElm = splitButton this.triggerElm = splitButton
? this.$refs.trigger.$el ? this.$refs.trigger.$el
: this.$slots.default[0].elm; : this.$slots.default[0].elm;
let dropdownElm = this.dropdownElm = this.$slots.dropdown[0].elm;
this.triggerElm.addEventListener('keydown', handleTriggerKeyDown); // triggerElm keydown
dropdownElm.addEventListener('keydown', handleItemKeyDown, true); // item keydown
//
if (!splitButton) {
this.triggerElm.addEventListener('focus', () => {
this.focusing = true;
});
this.triggerElm.addEventListener('blur', () => {
this.focusing = false;
});
this.triggerElm.addEventListener('click', () => {
this.focusing = false;
});
}
if (trigger === 'hover') { if (trigger === 'hover') {
this.triggerElm.addEventListener('mouseenter', show); this.triggerElm.addEventListener('mouseenter', show);
this.triggerElm.addEventListener('mouseleave', hide); this.triggerElm.addEventListener('mouseleave', hide);
let dropdownElm = this.$slots.dropdown[0].elm;
dropdownElm.addEventListener('mouseenter', show); dropdownElm.addEventListener('mouseenter', show);
dropdownElm.addEventListener('mouseleave', hide); dropdownElm.addEventListener('mouseleave', hide);
} else if (trigger === 'click') { } else if (trigger === 'click') {

View File

@ -157,14 +157,14 @@
}, },
getColorChannels(color) { getColorChannels(color) {
color = color.replace('#', ''); color = color.replace('#', '');
if (/^[1-9a-fA-F]{3}$/.test(color)) { if (/^[0-9a-fA-F]{3}$/.test(color)) {
color = color.split(''); color = color.split('');
for (let i = 2; i >= 0; i--) { for (let i = 2; i >= 0; i--) {
color.splice(i, 0, color[i]); color.splice(i, 0, color[i]);
} }
color = color.join(''); color = color.join('');
} }
if (/^[1-9a-fA-F]{6}$/.test(color)) { if (/^[0-9a-fA-F]{6}$/.test(color)) {
return { return {
red: parseInt(color.slice(0, 2), 16), red: parseInt(color.slice(0, 2), 16),
green: parseInt(color.slice(2, 4), 16), green: parseInt(color.slice(2, 4), 16),

View File

@ -173,11 +173,13 @@
}, },
handleTitleMouseenter() { handleTitleMouseenter() {
if (this.mode === 'horizontal' && !this.rootMenu.backgroundColor) return; if (this.mode === 'horizontal' && !this.rootMenu.backgroundColor) return;
this.$refs['submenu-title'].style.backgroundColor = this.rootMenu.hoverBackground; const title = this.$refs['submenu-title'];
title && (title.style.backgroundColor = this.rootMenu.hoverBackground);
}, },
handleTitleMouseleave() { handleTitleMouseleave() {
if (this.mode === 'horizontal' && !this.rootMenu.backgroundColor) return; if (this.mode === 'horizontal' && !this.rootMenu.backgroundColor) return;
this.$refs['submenu-title'].style.backgroundColor = this.rootMenu.backgroundColor || ''; const title = this.$refs['submenu-title'];
title && (title.style.backgroundColor = this.rootMenu.backgroundColor || '');
} }
}, },
created() { created() {

View File

@ -9,15 +9,15 @@
v-show="visible" v-show="visible"
@mouseenter="clearTimer" @mouseenter="clearTimer"
@mouseleave="startTimer" @mouseleave="startTimer"
role="alertdialog" role="alert"
> >
<i :class="iconClass" v-if="iconClass"></i> <i :class="iconClass" v-if="iconClass"></i>
<i :class="typeClass" v-else></i> <i :class="typeClass" v-else></i>
<slot> <slot>
<p v-if="!dangerouslyUseHTMLString" class="el-message__content" tabindex="0">{{ message }}</p> <p v-if="!dangerouslyUseHTMLString" class="el-message__content">{{ message }}</p>
<p v-else v-html="message" class="el-message__content" tabindex="0"></p> <p v-else v-html="message" class="el-message__content"></p>
</slot> </slot>
<i v-if="showClose" class="el-message__closeBtn el-icon-close" @click="close" tabindex="0" role="button" aria-label="close" @keydown.enter.stop="close"></i> <i v-if="showClose" class="el-message__closeBtn el-icon-close" @click="close"></i>
</div> </div>
</transition> </transition>
</template> </template>
@ -44,9 +44,7 @@
closed: false, closed: false,
timer: null, timer: null,
dangerouslyUseHTMLString: false, dangerouslyUseHTMLString: false,
center: false, center: false
initFocus: null,
originFocus: null
}; };
}, },
@ -87,18 +85,6 @@
if (typeof this.onClose === 'function') { if (typeof this.onClose === 'function') {
this.onClose(this); this.onClose(this);
} }
if (!this.originFocus || !this.originFocus.getBoundingClientRect) return;
// restore keyboard focus
const { top, left, bottom, right } = this.originFocus.getBoundingClientRect();
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
if (top >= 0 &&
left >= 0 &&
bottom <= viewportHeight &&
right <= viewportWidth) {
this.originFocus.focus();
}
}, },
clearTimer() { clearTimer() {
@ -115,24 +101,15 @@
} }
}, },
keydown(e) { keydown(e) {
if (e.keyCode === 46 || e.keyCode === 8) { if (e.keyCode === 27) { // esc
this.clearTimer(); // detele
} else if (e.keyCode === 27) { // esc
if (!this.closed) { if (!this.closed) {
this.close(); this.close();
} }
} else {
this.startTimer(); //
} }
} }
}, },
mounted() { mounted() {
this.startTimer(); this.startTimer();
this.originFocus = document.activeElement;
this.initFocus = this.showClose ? this.$el.querySelector('.el-icon-close') : this.$el.querySelector('.el-message__content');
setTimeout(() => {
this.initFocus && this.initFocus.focus();
});
document.addEventListener('keydown', this.keydown); document.addEventListener('keydown', this.keydown);
}, },
beforeDestroy() { beforeDestroy() {

View File

@ -6,7 +6,9 @@
:style="positionStyle" :style="positionStyle"
@mouseenter="clearTimer()" @mouseenter="clearTimer()"
@mouseleave="startTimer()" @mouseleave="startTimer()"
@click="click"> @click="click"
role="alert"
>
<i <i
class="el-notification__icon" class="el-notification__icon"
:class="[ typeClass, iconClass ]" :class="[ typeClass, iconClass ]"
@ -119,9 +121,19 @@
} }
}, this.duration); }, this.duration);
} }
},
keydown(e) {
if (e.keyCode === 46 || e.keyCode === 8) {
this.clearTimer(); // detele
} else if (e.keyCode === 27) { // esc
if (!this.closed) {
this.close();
}
} else {
this.startTimer(); //
}
} }
}, },
mounted() { mounted() {
if (this.duration > 0) { if (this.duration > 0) {
this.timer = setTimeout(() => { this.timer = setTimeout(() => {
@ -130,6 +142,11 @@
} }
}, this.duration); }, this.duration);
} }
document.addEventListener('keydown', this.keydown);
},
beforeDestroy() {
document.removeEventListener('keydown', this.keydown);
} }
}; };
</script> </script>

View File

@ -6,7 +6,11 @@
:class="[popperClass, content && 'el-popover--plain']" :class="[popperClass, content && 'el-popover--plain']"
ref="popper" ref="popper"
v-show="!disabled && showPopper" v-show="!disabled && showPopper"
:style="{ width: width + 'px' }"> :style="{ width: width + 'px' }"
role="tooltip"
:id="tooltipId"
:aria-hidden="(disabled || !showPopper) ? 'true' : 'false'"
>
<div class="el-popover__title" v-if="title" v-text="title"></div> <div class="el-popover__title" v-if="title" v-text="title"></div>
<slot>{{ content }}</slot> <slot>{{ content }}</slot>
</div> </div>
@ -14,10 +18,11 @@
<slot name="reference"></slot> <slot name="reference"></slot>
</span> </span>
</template> </template>
<script> <script>
import Popper from 'element-ui/src/utils/vue-popper'; import Popper from 'element-ui/src/utils/vue-popper';
import { on, off } from 'element-ui/src/utils/dom'; import { on, off } from 'element-ui/src/utils/dom';
import { addClass, removeClass } from 'element-ui/src/utils/dom';
import { generateId } from 'element-ui/src/utils/util';
export default { export default {
name: 'ElPopover', name: 'ElPopover',
@ -49,25 +54,35 @@ export default {
} }
}, },
computed: {
tooltipId() {
return `el-popover-${generateId()}`;
}
},
watch: { watch: {
showPopper(newVal, oldVal) { showPopper(val) {
newVal ? this.$emit('show') : this.$emit('hide'); val ? this.$emit('show') : this.$emit('hide');
},
'$refs.reference': {
deep: true,
handler(val) {
console.log(val);
}
} }
}, },
mounted() { mounted() {
let reference = this.reference || this.$refs.reference; let reference = this.referenceElm = this.reference || this.$refs.reference;
const popper = this.popper || this.$refs.popper; const popper = this.popper || this.$refs.popper;
if (!reference && this.$slots.reference && this.$slots.reference[0]) { if (!reference && this.$slots.reference && this.$slots.reference[0]) {
reference = this.referenceElm = this.$slots.reference[0].elm; reference = this.referenceElm = this.$slots.reference[0].elm;
} }
// 访
if (reference) {
addClass(reference, 'el-popover__reference');
reference.setAttribute('aria-describedby', this.tooltipId);
reference.setAttribute('tabindex', 0); // tab
this.trigger !== 'click' && on(reference, 'focus', this.handleFocus);
this.trigger !== 'click' && on(reference, 'blur', this.handleBlur);
on(reference, 'keydown', this.handleKeydown);
on(reference, 'click', this.handleClick);
}
if (this.trigger === 'click') { if (this.trigger === 'click') {
on(reference, 'click', this.doToggle); on(reference, 'click', this.doToggle);
on(document, 'click', this.handleDocumentClick); on(document, 'click', this.handleDocumentClick);
@ -114,6 +129,17 @@ export default {
doClose() { doClose() {
this.showPopper = false; this.showPopper = false;
}, },
handleFocus() {
addClass(this.referenceElm, 'focusing');
this.showPopper = true;
},
handleClick() {
removeClass(this.referenceElm, 'focusing');
},
handleBlur() {
removeClass(this.referenceElm, 'focusing');
this.showPopper = false;
},
handleMouseEnter() { handleMouseEnter() {
clearTimeout(this._timer); clearTimeout(this._timer);
if (this.openDelay) { if (this.openDelay) {
@ -124,6 +150,11 @@ export default {
this.showPopper = true; this.showPopper = true;
} }
}, },
handleKeydown(ev) {
if (ev.keyCode === 27) { // esc
this.doClose();
}
},
handleMouseLeave() { handleMouseLeave() {
clearTimeout(this._timer); clearTimeout(this._timer);
this._timer = setTimeout(() => { this._timer = setTimeout(() => {

View File

@ -53,9 +53,10 @@
}, },
mounted() { mounted() {
// radioGroupTab // radioGroupTab
let radios = this.$el.querySelectorAll('[type=radio]'); const radios = this.$el.querySelectorAll('[type=radio]');
if (![].some.call(radios, radio => radio.checked)) { const firstLabel = this.$el.querySelectorAll('[role=radio]')[0];
this.$el.querySelectorAll('[role=radio]')[0].tabIndex = 0; if (![].some.call(radios, radio => radio.checked) && firstLabel) {
firstLabel.tabIndex = 0;
} }
}, },
methods: { methods: {

View File

@ -1,6 +1,6 @@
<template> <template>
<ul class="el-select-group__wrap"> <ul class="el-select-group__wrap" v-show="visible">
<li class="el-select-group__title" v-show="visible">{{ label }}</li> <li class="el-select-group__title">{{ label }}</li>
<li> <li>
<ul class="el-select-group"> <ul class="el-select-group">
<slot></slot> <slot></slot>

View File

@ -9,7 +9,12 @@
@click.stop="toggleMenu" @click.stop="toggleMenu"
ref="tags" ref="tags"
:style="{ 'max-width': inputWidth - 32 + 'px' }"> :style="{ 'max-width': inputWidth - 32 + 'px' }">
<transition-group @after-leave="resetInputHeight"> <span
class="el-select__multiple-text"
v-if="collapseTags">
{{ multipleText }}
</span>
<transition-group @after-leave="resetInputHeight" v-if="!collapseTags">
<el-tag <el-tag
v-for="item in selected" v-for="item in selected"
:key="getValueKey(item)" :key="getValueKey(item)"
@ -29,6 +34,7 @@
:class="[selectSize ? `is-${ selectSize }` : '']" :class="[selectSize ? `is-${ selectSize }` : '']"
:disabled="disabled" :disabled="disabled"
@focus="handleFocus" @focus="handleFocus"
@click.stop
@keyup="managePlaceholder" @keyup="managePlaceholder"
@keydown="resetInputState" @keydown="resetInputState"
@keydown.down.prevent="navigateOptions('next')" @keydown.down.prevent="navigateOptions('next')"
@ -183,6 +189,14 @@
selectSize() { selectSize() {
return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size; return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
},
multipleText() {
const selected = this.selected;
if (!selected || !selected.length) return '';
const length = selected.length;
const countText = length > 1 ? `(+${ selected.length - 1 })` : '';
return `${ selected[0].currentLabel } ${ countText }`;
} }
}, },
@ -231,7 +245,8 @@
valueKey: { valueKey: {
type: String, type: String,
default: 'value' default: 'value'
} },
collapseTags: Boolean
}, },
data() { data() {
@ -534,6 +549,7 @@
}, },
resetInputHeight() { resetInputHeight() {
if (this.collapseTags) return;
this.$nextTick(() => { this.$nextTick(() => {
if (!this.$refs.reference) return; if (!this.$refs.reference) return;
let inputChildNodes = this.$refs.reference.$el.childNodes; let inputChildNodes = this.$refs.reference.$el.childNodes;

View File

@ -119,12 +119,10 @@ export default {
{ {
column.sortable column.sortable
? <span class="caret-wrapper" on-click={ ($event) => this.handleSortClick($event, column) }> ? <span class="caret-wrapper" on-click={ ($event) => this.handleSortClick($event, column) }>
<span class="sort-caret ascending" on-click={ ($event) => this.handleSortClick($event, column, 'ascending') }> <i class="sort-caret ascending el-icon-caret-top" on-click={ ($event) => this.handleSortClick($event, column, 'ascending') }>
<i class="el-icon-sort-up"></i> </i>
</span> <i class="sort-caret descending el-icon-caret-bottom" on-click={ ($event) => this.handleSortClick($event, column, 'descending') }>
<span class="sort-caret descending" on-click={ ($event) => this.handleSortClick($event, column, 'descending') }> </i>
<i class="el-icon-sort-down"></i>
</span>
</span> </span>
: '' : ''
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "element-theme-chalk", "name": "element-theme-chalk",
"version": "2.0.3", "version": "2.0.4",
"description": "Element component chalk theme.", "description": "Element component chalk theme.",
"main": "lib/index.css", "main": "lib/index.css",
"style": "lib/index.css", "style": "lib/index.css",
@ -28,7 +28,8 @@
"devDependencies": { "devDependencies": {
"gulp": "^3.9.1", "gulp": "^3.9.1",
"gulp-cssmin": "^0.1.7", "gulp-cssmin": "^0.1.7",
"gulp-sass": "^3.1.0" "gulp-sass": "^3.1.0",
"gulp-autoprefixer": "^4.0.0"
}, },
"dependencies": {} "dependencies": {}
} }

View File

@ -128,7 +128,7 @@
line-height: 1.5; line-height: 1.5;
box-sizing: border-box; box-sizing: border-box;
cursor: pointer; cursor: pointer;
outline: none;
@include m(extensible) { @include m(extensible) {
&:after { &:after {
font-family: 'element-icons'; font-family: 'element-icons';
@ -154,7 +154,7 @@
color: $--select-option-selected; color: $--select-option-selected;
} }
&:hover { &:hover, &:focus:not(:active) {
background-color: $--select-option-hover-background; background-color: $--select-option-hover-background;
} }

View File

@ -17,6 +17,9 @@
padding: $--checkbox-bordered-padding; padding: $--checkbox-bordered-padding;
border-radius: $--border-radius-base; border-radius: $--border-radius-base;
border: $--border-base; border: $--border-base;
box-sizing: border-box;
line-height: normal;
height: $--checkbox-bordered-height;
&.is-checked { &.is-checked {
border-color: $--color-primary; border-color: $--color-primary;
@ -34,6 +37,7 @@
&.el-checkbox--medium { &.el-checkbox--medium {
padding: $--checkbox-bordered-medium-padding; padding: $--checkbox-bordered-medium-padding;
border-radius: $--button-medium-border-radius; border-radius: $--button-medium-border-radius;
height: $--checkbox-bordered-medium-height;
.el-checkbox__label { .el-checkbox__label {
line-height: 17px; line-height: 17px;
@ -49,6 +53,7 @@
&.el-checkbox--small { &.el-checkbox--small {
padding: $--checkbox-bordered-small-padding; padding: $--checkbox-bordered-small-padding;
border-radius: $--button-small-border-radius; border-radius: $--button-small-border-radius;
height: $--checkbox-bordered-small-height;
.el-checkbox__label { .el-checkbox__label {
line-height: 15px; line-height: 15px;
@ -69,6 +74,7 @@
&.el-checkbox--mini { &.el-checkbox--mini {
padding: $--checkbox-bordered-mini-padding; padding: $--checkbox-bordered-mini-padding;
border-radius: $--button-mini-border-radius; border-radius: $--button-mini-border-radius;
height: $--checkbox-bordered-mini-height;
.el-checkbox__label { .el-checkbox__label {
line-height: 12px; line-height: 12px;

View File

@ -137,16 +137,20 @@ $--checkbox-checked-icon-color: $--fill-base !default;
$--checkbox-input-border-color-hover: $--color-primary !default; $--checkbox-input-border-color-hover: $--color-primary !default;
$--checkbox-bordered-height: 40px !default;
$--checkbox-bordered-padding: 9px 20px 9px 10px !default; $--checkbox-bordered-padding: 9px 20px 9px 10px !default;
$--checkbox-bordered-medium-padding: 7px 20px 7px 10px !default; $--checkbox-bordered-medium-padding: 7px 20px 7px 10px !default;
$--checkbox-bordered-small-padding: 3px 15px 7px 10px !default; $--checkbox-bordered-small-padding: 5px 15px 5px 10px !default;
$--checkbox-bordered-mini-padding: 1px 15px 5px 10px !default; $--checkbox-bordered-mini-padding: 3px 15px 3px 10px !default;
$--checkbox-bordered-medium-input-height: 14px !default; $--checkbox-bordered-medium-input-height: 14px !default;
$--checkbox-bordered-medium-input-width: 14px !default; $--checkbox-bordered-medium-input-width: 14px !default;
$--checkbox-bordered-medium-height: 36px !default;
$--checkbox-bordered-small-input-height: 12px !default; $--checkbox-bordered-small-input-height: 12px !default;
$--checkbox-bordered-small-input-width: 12px !default; $--checkbox-bordered-small-input-width: 12px !default;
$--checkbox-bordered-small-height: 32px !default;
$--checkbox-bordered-mini-input-height: 12px !default; $--checkbox-bordered-mini-input-height: 12px !default;
$--checkbox-bordered-mini-input-width: 12px !default; $--checkbox-bordered-mini-input-width: 12px !default;
$--checkbox-bordered-mini-height: 28px !default;
$--checkbox-button-font-size: $--font-size-base !default; $--checkbox-button-font-size: $--font-size-base !default;
$--checkbox-button-checked-fill: $--color-primary !default; $--checkbox-button-checked-fill: $--color-primary !default;
@ -183,16 +187,20 @@ $--radio-checked-icon-color: $--color-primary !default;
$--radio-input-border-color-hover: $--color-primary !default; $--radio-input-border-color-hover: $--color-primary !default;
$--radio-bordered-padding: 10px 20px 10px 10px !default; $--radio-bordered-height: 40px !default;
$--radio-bordered-medium-padding: 8px 20px 8px 10px !default; $--radio-bordered-padding: 12px 20px 0 10px !default;
$--radio-bordered-small-padding: 6px 15px 6px 10px !default; $--radio-bordered-medium-padding: 10px 20px 0 10px !default;
$--radio-bordered-mini-padding: 4px 15px 4px 10px !default; $--radio-bordered-small-padding: 8px 15px 0 10px !default;
$--radio-bordered-mini-padding: 6px 15px 0 10px !default;
$--radio-bordered-medium-input-height: 14px !default; $--radio-bordered-medium-input-height: 14px !default;
$--radio-bordered-medium-input-width: 14px !default; $--radio-bordered-medium-input-width: 14px !default;
$--radio-bordered-medium-height: 36px !default;
$--radio-bordered-small-input-height: 12px !default; $--radio-bordered-small-input-height: 12px !default;
$--radio-bordered-small-input-width: 12px !default; $--radio-bordered-small-input-width: 12px !default;
$--radio-bordered-small-height: 32px !default;
$--radio-bordered-mini-input-height: 12px !default; $--radio-bordered-mini-input-height: 12px !default;
$--radio-bordered-mini-input-width: 12px !default; $--radio-bordered-mini-input-width: 12px !default;
$--radio-bordered-mini-height: 28px !default;
$--radio-button-font-size: $--font-size-base !default; $--radio-button-font-size: $--font-size-base !default;
$--radio-button-checked-fill: $--color-primary !default; $--radio-button-checked-fill: $--color-primary !default;

View File

@ -50,6 +50,12 @@
font-size: 12px; font-size: 12px;
margin: 0 3px; margin: 0 3px;
} }
.el-dropdown-selfdefine { //
&:focus:active, &:focus:not(.focusing) {
outline-width: 0;
}
}
} }
@include b(dropdown-menu) { @include b(dropdown-menu) {
@ -72,8 +78,8 @@
font-size: $--font-size-base; font-size: $--font-size-base;
color: $--color-text-regular; color: $--color-text-regular;
cursor: pointer; cursor: pointer;
outline: none;
&:not(.is-disabled):hover { &:not(.is-disabled):hover, &:focus {
background-color: $--dropdown-menuItem-hover-fill; background-color: $--dropdown-menuItem-hover-fill;
color: $--dropdown-menuItem-hover-color; color: $--dropdown-menuItem-hover-color;
} }

View File

@ -27,4 +27,10 @@
line-height: 1; line-height: 1;
margin-bottom: 12px; margin-bottom: 12px;
} }
@include e(reference) {
&:focus:not(.focusing), &:focus:hover {
outline-width: 0;
}
}
} }

View File

@ -19,6 +19,8 @@
padding: $--radio-bordered-padding; padding: $--radio-bordered-padding;
border-radius: $--border-radius-base; border-radius: $--border-radius-base;
border: $--border-base; border: $--border-base;
box-sizing: border-box;
height: $--radio-bordered-height;
&.is-checked { &.is-checked {
border-color: $--color-primary; border-color: $--color-primary;
@ -38,6 +40,7 @@
&.is-bordered { &.is-bordered {
padding: $--radio-bordered-medium-padding; padding: $--radio-bordered-medium-padding;
border-radius: $--button-medium-border-radius; border-radius: $--button-medium-border-radius;
height: $--radio-bordered-medium-height;
.el-radio__label { .el-radio__label {
font-size: $--button-medium-font-size; font-size: $--button-medium-font-size;
} }
@ -51,6 +54,7 @@
&.is-bordered { &.is-bordered {
padding: $--radio-bordered-small-padding; padding: $--radio-bordered-small-padding;
border-radius: $--button-small-border-radius; border-radius: $--button-small-border-radius;
height: $--radio-bordered-small-height;
.el-radio__label { .el-radio__label {
font-size: $--button-small-font-size; font-size: $--button-small-font-size;
} }
@ -64,6 +68,7 @@
&.is-bordered { &.is-bordered {
padding: $--radio-bordered-mini-padding; padding: $--radio-bordered-mini-padding;
border-radius: $--button-mini-border-radius; border-radius: $--button-mini-border-radius;
height: $--radio-bordered-mini-height;
.el-radio__label { .el-radio__label {
font-size: $--button-mini-font-size; font-size: $--button-mini-font-size;
} }

View File

@ -1,4 +1,5 @@
@import "mixins/mixins"; @import "mixins/mixins";
@import "mixins/utils";
@import "common/var"; @import "common/var";
@import "select-dropdown"; @import "select-dropdown";
@import "input"; @import "input";
@ -88,6 +89,14 @@
} }
} }
@include e(multiple-text) {
margin-left: 15px;
color: $--input-color;
font-size: $--font-size-base;
display: block;
@include utils-ellipsis;
}
@include e(close) { @include e(close) {
cursor: pointer; cursor: pointer;
position: absolute; position: absolute;

View File

@ -426,20 +426,29 @@
} }
.caret-wrapper { .caret-wrapper {
position: relative; position: absolute;
display: inline-flex; display: inline-block;
align-items: center; height: 100%;
height: 13px; vertical-align: middle;
width: 24px;
cursor: pointer; cursor: pointer;
overflow: initial; overflow: initial;
} }
.sort-caret { .sort-caret {
color: $--icon-color-base; color: $--color-text-placeholder;
width: 14px; width: 14px;
overflow: hidden; overflow: hidden;
font-size: 13px; font-size: 15px;
position: absolute;
left: 4px;
&.ascending {
top: 1px;
}
&.descending {
bottom: 1px;
}
} }
.ascending .sort-caret.ascending { .ascending .sort-caret.ascending {

View File

@ -2,6 +2,9 @@
@import "common/var"; @import "common/var";
@include b(tooltip) { @include b(tooltip) {
&:focus:not(.focusing), &:focus:hover {
outline-width: 0;
}
@include e(popper) { @include e(popper) {
position: absolute; position: absolute;
border-radius: 4px; border-radius: 4px;

View File

@ -25,7 +25,12 @@
@include b(tree-node) { @include b(tree-node) {
white-space: nowrap; white-space: nowrap;
outline: none;
&:focus { /* focus */
> .el-tree-node__content {
background-color: $--tree-node-hover-color;
}
}
@include e(content) { @include e(content) {
display: flex; display: flex;
align-items: center; align-items: center;

View File

@ -1,6 +1,7 @@
import Popper from 'element-ui/src/utils/vue-popper'; import Popper from 'element-ui/src/utils/vue-popper';
import debounce from 'throttle-debounce/debounce'; import debounce from 'throttle-debounce/debounce';
import { getFirstComponentChild } from 'element-ui/src/utils/vdom'; import { getFirstComponentChild } from 'element-ui/src/utils/vdom';
import { generateId } from 'element-ui/src/utils/util';
import Vue from 'vue'; import Vue from 'vue';
export default { export default {
@ -48,10 +49,15 @@ export default {
data() { data() {
return { return {
timeoutPending: null timeoutPending: null,
focusing: false
}; };
}, },
computed: {
tooltipId() {
return `el-tooltip-${generateId()}`;
}
},
beforeCreate() { beforeCreate() {
if (this.$isServer) return; if (this.$isServer) return;
@ -75,6 +81,9 @@ export default {
onMouseleave={ () => { this.setExpectedState(false); this.debounceClose(); } } onMouseleave={ () => { this.setExpectedState(false); this.debounceClose(); } }
onMouseenter= { () => { this.setExpectedState(true); } } onMouseenter= { () => { this.setExpectedState(true); } }
ref="popper" ref="popper"
role="tooltip"
id={this.tooltipId}
aria-hidden={ (this.disabled || !this.showPopper) ? 'true' : 'false' }
v-show={!this.disabled && this.showPopper} v-show={!this.disabled && this.showPopper}
class={ class={
['el-tooltip__popper', 'is-' + this.effect, this.popperClass] ['el-tooltip__popper', 'is-' + this.effect, this.popperClass]
@ -87,24 +96,38 @@ export default {
if (!this.$slots.default || !this.$slots.default.length) return this.$slots.default; if (!this.$slots.default || !this.$slots.default.length) return this.$slots.default;
const vnode = getFirstComponentChild(this.$slots.default); const vnode = getFirstComponentChild(this.$slots.default);
if (!vnode) return vnode; if (!vnode) return vnode;
const data = vnode.data = vnode.data || {}; const data = vnode.data = vnode.data || {};
const on = vnode.data.on = vnode.data.on || {}; const on = vnode.data.on = vnode.data.on || {};
const nativeOn = vnode.data.nativeOn = vnode.data.nativeOn || {}; const nativeOn = vnode.data.nativeOn = vnode.data.nativeOn || {};
data.staticClass = this.concatClass(data.staticClass, 'el-tooltip'); data.staticClass = this.concatClass(data.staticClass, 'el-tooltip');
on.mouseenter = this.addEventHandle(on.mouseenter, this.show); nativeOn.mouseenter = on.mouseenter = this.addEventHandle(on.mouseenter, this.show);
on.mouseleave = this.addEventHandle(on.mouseleave, this.hide); nativeOn.mouseleave = on.mouseleave = this.addEventHandle(on.mouseleave, this.hide);
nativeOn.mouseenter = this.addEventHandle(nativeOn.mouseenter, this.show); nativeOn.focus = on.focus = this.addEventHandle(on.focus, this.handleFocus);
nativeOn.mouseleave = this.addEventHandle(nativeOn.mouseleave, this.hide); nativeOn.blur = on.blur = this.addEventHandle(on.blur, this.handleBlur);
nativeOn.click = on.click = this.addEventHandle(on.click, () => { this.focusing = false; });
return vnode; return vnode;
}, },
mounted() { mounted() {
this.referenceElm = this.$el; this.referenceElm = this.$el;
if (this.$el.nodeType === 1) {
this.$el.setAttribute('aria-describedby', this.tooltipId);
this.$el.setAttribute('tabindex', 0);
}
},
watch: {
focusing(val) {
if (val) {
this.referenceElm.className += ' focusing';
} else {
this.referenceElm.className = this.referenceElm.className.replace('focusing', '');
}
}
}, },
methods: { methods: {
show() { show() {
this.setExpectedState(true); this.setExpectedState(true);
@ -115,7 +138,14 @@ export default {
this.setExpectedState(false); this.setExpectedState(false);
this.debounceClose(); this.debounceClose();
}, },
handleFocus() {
this.focusing = true;
this.show();
},
handleBlur() {
this.focusing = false;
this.hide();
},
addEventHandle(old, fn) { addEventHandle(old, fn) {
if (!old) { if (!old) {
return fn; return fn;

View File

@ -198,9 +198,10 @@ export default class TreeStore {
const node = this.nodesMap[key]; const node = this.nodesMap[key];
if (!node) return; if (!node) return;
const childNodes = node.childNodes; const childNodes = node.childNodes;
childNodes.forEach(child => { for (let i = childNodes.length - 1; i >= 0; i--) {
const child = childNodes[i];
this.remove(child.data); this.remove(child.data);
}); }
for (let i = 0, j = data.length; i < j; i++) { for (let i = 0, j = data.length; i < j; i++) {
const child = data[i]; const child = data[i];
this.append(child, node.data); this.append(child, node.data);

View File

@ -1,12 +1,21 @@
<template> <template>
<div class="el-tree-node" <div
class="el-tree-node"
@click.stop="handleClick" @click.stop="handleClick"
v-show="node.visible" v-show="node.visible"
:class="{ :class="{
'is-expanded': expanded, 'is-expanded': expanded,
'is-current': tree.store.currentNode === node, 'is-current': tree.store.currentNode === node,
'is-hidden': !node.visible 'is-hidden': !node.visible,
}"> 'is-focusable': !node.disabled,
'is-checked': !node.disabled && node.checked
}"
role="treeitem"
tabindex="-1"
:aria-expanded="expanded"
:aria-disabled="node.disabled"
:aria-checked="node.checked"
>
<div class="el-tree-node__content" <div class="el-tree-node__content"
:style="{ 'padding-left': (node.level - 1) * tree.indent + 'px' }"> :style="{ 'padding-left': (node.level - 1) * tree.indent + 'px' }">
<span <span
@ -20,7 +29,8 @@
:indeterminate="node.indeterminate" :indeterminate="node.indeterminate"
:disabled="!!node.disabled" :disabled="!!node.disabled"
@click.native.stop @click.native.stop
@change="handleCheckChange"> @change="handleCheckChange"
>
</el-checkbox> </el-checkbox>
<span <span
v-if="node.loading" v-if="node.loading"
@ -32,7 +42,10 @@
<div <div
class="el-tree-node__children" class="el-tree-node__children"
v-if="childNodeRendered" v-if="childNodeRendered"
v-show="expanded"> v-show="expanded"
role="group"
:aria-expanded="expanded"
>
<el-tree-node <el-tree-node
:render-content="renderContent" :render-content="renderContent"
v-for="child in node.childNodes" v-for="child in node.childNodes"

View File

@ -1,5 +1,9 @@
<template> <template>
<div class="el-tree" :class="{ 'el-tree--highlight-current': highlightCurrent }"> <div
class="el-tree"
:class="{ 'el-tree--highlight-current': highlightCurrent }"
role="tree"
>
<el-tree-node <el-tree-node
v-for="child in root.childNodes" v-for="child in root.childNodes"
:node="child" :node="child"
@ -33,7 +37,9 @@
return { return {
store: null, store: null,
root: null, root: null,
currentNode: null currentNode: null,
treeItems: null,
checkboxItems: []
}; };
}, },
@ -101,6 +107,9 @@
get() { get() {
return this.data; return this.data;
} }
},
treeItemArray() {
return Array.prototype.slice.call(this.treeItems);
} }
}, },
@ -115,6 +124,11 @@
}, },
data(newVal) { data(newVal) {
this.store.setData(newVal); this.store.setData(newVal);
},
checkboxItems(val) {
Array.prototype.forEach.call(val, (checkbox) => {
checkbox.setAttribute('tabindex', -1);
});
} }
}, },
@ -171,6 +185,42 @@
updateKeyChildren(key, data) { updateKeyChildren(key, data) {
if (!this.nodeKey) throw new Error('[Tree] nodeKey is required in updateKeyChild'); if (!this.nodeKey) throw new Error('[Tree] nodeKey is required in updateKeyChild');
this.store.updateChildren(key, data); this.store.updateChildren(key, data);
},
initTabindex() {
this.treeItems = this.$el.querySelectorAll('.is-focusable[role=treeitem]');
this.checkboxItems = this.$el.querySelectorAll('input[type=checkbox]');
const checkedItem = this.$el.querySelectorAll('.is-checked[role=treeitem]');
if (checkedItem.length) {
checkedItem[0].setAttribute('tabindex', 0);
return;
}
this.treeItems[0].setAttribute('tabindex', 0);
},
handelKeydown(ev) {
const currentItem = ev.target;
const keyCode = ev.keyCode;
this.treeItems = this.$el.querySelectorAll('.is-focusable[role=treeitem]');
const currentIndex = this.treeItemArray.indexOf(currentItem);
let nextIndex;
if ([38, 40].indexOf(keyCode) > -1) { // updown
if (keyCode === 38) { // up
nextIndex = currentIndex !== 0 ? currentIndex - 1 : 0;
} else {
nextIndex = (currentIndex < this.treeItemArray.length - 1) ? currentIndex + 1 : 0;
}
this.treeItemArray[nextIndex].focus(); //
}
const hasInput = currentItem.querySelector('[type="checkbox"]');
if ([37, 39].indexOf(keyCode) > -1) { // leftright
currentItem.click(); //
}
if ([13, 32].indexOf(keyCode) > -1) { // space entercheckbox
if (hasInput) {
hasInput.click();
}
ev.stopPropagation();
ev.preventDefault();
}
} }
}, },
@ -194,6 +244,14 @@
}); });
this.root = this.store.root; this.root = this.store.root;
},
mounted() {
this.initTabindex();
this.$el.addEventListener('keydown', this.handelKeydown);
},
updated() {
this.treeItems = this.$el.querySelectorAll('[role=treeitem]');
this.checkboxItems = this.$el.querySelectorAll('input[type=checkbox]');
} }
}; };
</script> </script>

View File

@ -1,9 +1,9 @@
function getError(action, option, xhr) { function getError(action, option, xhr) {
let msg; let msg;
if (xhr.response) { if (xhr.response) {
msg = `${xhr.status} ${xhr.response.error || xhr.response}`; msg = `${xhr.response.error || xhr.response}`;
} else if (xhr.responseText) { } else if (xhr.responseText) {
msg = `${xhr.status} ${xhr.responseText}`; msg = `${xhr.responseText}`;
} else { } else {
msg = `fail to post ${action} ${xhr.status}`; msg = `fail to post ${action} ${xhr.status}`;
} }

View File

@ -173,7 +173,7 @@ if (typeof window !== 'undefined' && window.Vue) {
}; };
module.exports = { module.exports = {
version: '2.0.3', version: '2.0.4',
locale: locale.use, locale: locale.use,
i18n: locale.i18n, i18n: locale.i18n,
install, install,

View File

@ -65,5 +65,6 @@ export default {
break; break;
} }
} }
delete el[ctx];
} }
}; };

View File

@ -41,7 +41,7 @@ describe('ajax', () => {
}); });
it('40x code should be error', done => { it('40x code should be error', done => {
option.onError = e => { option.onError = e => {
expect(e.toString()).to.contain('404 Not found'); expect(e.toString()).to.contain('Not found');
done(); done();
}; };