You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/v2/guide/list.md
+47-47Lines changed: 47 additions & 47 deletions
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,14 @@
1
1
---
2
-
title: List Rendering
2
+
title: Renderizado de Listas
3
3
type: guide
4
4
order: 8
5
5
---
6
6
7
7
## `v-for`
8
8
9
-
We can use the`v-for`directive to render a list of items based on an array. The `v-for`directive requires a special syntax in the form of `item in items`, where`items`is the source data array and `item`is an**alias**for the array element being iterated on:
9
+
Podemos usar la directiva`v-for`para renderizar una lista de elementos usando un array. La directiva `v-for`requiere de una sintaxis especial de la forma `item in items`, dónde`items`es el array de datos fuente, e `item`es un**alias**para el elemento del array sobre el cuál se está iterando.
10
10
11
-
### Basic Usage
11
+
### Uso Básico
12
12
13
13
```html
14
14
<ulid="example-1">
@@ -30,7 +30,7 @@ var example1 = new Vue({
30
30
})
31
31
```
32
32
33
-
Result:
33
+
Resulta en:
34
34
35
35
{% raw %}
36
36
<ulid="example-1"class="demo">
@@ -56,7 +56,7 @@ var example1 = new Vue({
56
56
</script>
57
57
{% endraw %}
58
58
59
-
Inside `v-for`blocks we have full access to parent scope properties. `v-for`also supports an optional second argument for the index of the current item.
59
+
Dentro de los bloques `v-for`tenemos acceso completo a las propiedades del ámbito del padre. `v-for`también soporta un segundo argumento opcional para el índice del elemento actual.
60
60
61
61
```html
62
62
<ulid="example-2">
@@ -79,7 +79,7 @@ var example2 = new Vue({
79
79
})
80
80
```
81
81
82
-
Result:
82
+
Resulta en:
83
83
84
84
{% raw%}
85
85
<ulid="example-2"class="demo">
@@ -106,15 +106,15 @@ var example2 = new Vue({
106
106
</script>
107
107
{% endraw %}
108
108
109
-
You can also use `of`as the delimiter instead of `in`, so that it is closer to JavaScript's syntax for iterators:
109
+
También puede usar `of`como el delimitador en vez de `in`, de forma que sea similar al sintaxis de JavaScript para iteradores:
110
110
111
111
```html
112
112
<divv-for="item of items"></div>
113
113
```
114
114
115
-
### Template v-for
115
+
### v-for en template
116
116
117
-
Similar to template`v-if`, you can also use a `<template>` tag with `v-for`to render a block of multiple elements. For example:
117
+
Similar a usar`v-if` en un `<template>`, también se puede usar la directiva `v-for`para renderizar un bloque de múltiples elementos. Por ejemplo:
118
118
119
119
```html
120
120
<ul>
@@ -125,9 +125,9 @@ Similar to template `v-if`, you can also use a `<template>` tag with `v-for` to
125
125
</ul>
126
126
```
127
127
128
-
### Object v-for
128
+
### v-for en objetos
129
129
130
-
You can also use `v-for`to iterate through the properties of an object.
130
+
También puede usar `v-for`para iterar sobre las propiedades de un objeto.
131
131
132
132
```html
133
133
<ulid="repeat-object"class="demo">
@@ -150,7 +150,7 @@ new Vue({
150
150
})
151
151
```
152
152
153
-
Result:
153
+
Resulta en:
154
154
155
155
{% raw %}
156
156
<ulid="repeat-object"class="demo">
@@ -172,35 +172,35 @@ new Vue({
172
172
</script>
173
173
{% endraw %}
174
174
175
-
You can also provide a second argument for the key:
175
+
También puede usar un segundo parámetro para la clave:
176
176
177
177
```html
178
178
<divv-for="(value, key) in object">
179
179
{{ key }} : {{ value }}
180
180
</div>
181
181
```
182
182
183
-
And another for the index:
183
+
Y otro para el índice
184
184
185
185
```html
186
186
<divv-for="(value, key, index) in object">
187
187
{{ index }}. {{ key }} : {{ value }}
188
188
</div>
189
189
```
190
190
191
-
<pclass="tip">When iterating over an object, the order is based on the key enumeration order of `Object.keys()`, which is **not** guaranteed to be consistent across JavaScript engine implementations.</p>
191
+
<pclass="tip">Cuando itere sobre un objeto, el orden es basado en el orden de enumeración de claves de `Object.keys()`, el cual **no** tiene garantía de ser consistente a través de implementaciones de JavaScript.</p>
192
192
193
-
### Range v-for
193
+
### v-for de rango
194
194
195
-
`v-for`can also take an integer. In this case it will repeat the template that many times.
195
+
`v-for`puede también tomar un entero. En este caso se repetirá la plantilla ésa cantidad de veces.
196
196
197
197
```html
198
198
<div>
199
199
<spanv-for="n in 10">{{ n }}</span>
200
200
</div>
201
201
```
202
202
203
-
Result:
203
+
Resulta en:
204
204
205
205
{% raw %}
206
206
<divid="range"class="demo">
@@ -211,17 +211,17 @@ new Vue({ el: '#range' })
211
211
</script>
212
212
{% endraw %}
213
213
214
-
### Components and v-for
214
+
### Componentes y v-for
215
215
216
-
> This section assumes knowledge of [Components](components.html). Feel free to skip it and come back later.
216
+
> Esta sección asume conocimiento en [Componentes](components.html). Siéntase de libre de saltarla y regresar más adelante.
217
217
218
-
You can directly use `v-for`on a custom component, like any normal element:
218
+
Puede usar directamente `v-for`en un componente a medida, como en cualquier elemento normal:
219
219
220
220
```html
221
221
<my-componentv-for="item in items"></my-component>
222
222
```
223
223
224
-
However, this won't automatically pass any data to the component, because components have isolated scopes of their own. In order to pass the iterated data into the component, we should also use props:
224
+
Sin embargo, esto no pasa automáticamente datos al componente, ya que los componentes tienen ámbitos aislados propios. Para poder transferir los datos iterados al componente, debemos usar los props:
225
225
226
226
```html
227
227
<my-component
@@ -231,9 +231,9 @@ However, this won't automatically pass any data to the component, because compon
231
231
</my-component>
232
232
```
233
233
234
-
The reason for not automatically injecting`item`into the component is because that makes the component tightly coupled to how `v-for` works. Being explicit about where its data comes from makes the component reusable in other situations.
234
+
La razón para no inyectar automáticamente`item`en el componente, es por que haría que el componente sea muy acoplado a cómo funciona `v-for`. Siendo explícito sobre de dónde vienen sus datos hace que el componente sea reusable en otras situaciones.
235
235
236
-
Here's a complete example of a simple todo list:
236
+
Aquí tenemos un ejemplo completo de una lista de tareas:
237
237
238
238
```html
239
239
<divid="todo-list-example">
@@ -329,29 +329,29 @@ new Vue({
329
329
</script>
330
330
{% endraw %}
331
331
332
-
## key
332
+
## key (clave)
333
333
334
-
When Vue.js is updating a list of elements rendered with`v-for`, it by default uses an "in-place patch" strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will simply patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of `track-by="$index"`in Vue 1.x.
334
+
Cuando Vue.js está actualizando una lista de elementos renderizados con`v-for`, por defecto usa una estrategia "in-place patch". Si el orden de los elementos de datos cambia, en vez de mover los elementos DOM para ajustar el orden de los elementos, Vue sencillamente arregla cada elemento en su lugar y se asegura que refleje lo que debe ser renderizado en ése índice particular. Ésto es similar al comportamiento de `track-by="$index"`en Vue 1.x.
335
335
336
-
This default mode is efficient, but only suitable**when your list render output does not rely on child component state or temporary DOM state (e.g. form input values)**.
336
+
Este modo por defecto es eficiente, pero sólo recomendable**cuando el renderizado de la lista no dependa del estado de componentes hijos o estado temporal DOM (p.e. valores de campos de formulario)**.
337
337
338
-
To give Vue a hint so that it can track each node's identity, and thus reuse and reorder existing elements, you need to provide a unique `key`attribute for each item. An ideal value for `key`would be the unique id of each item. This special attribute is a rough equivalent to`track-by`in 1.x, but it works like an attribute, so you need to use`v-bind`to bind it to dynamic values (using shorthand here):
338
+
Para darle a Vue una indicación para que pueda rastrear la identidad de cada nodo, y así re-usar y re-ordenar elementos existentes, necesita poveer un atributo único `key`para cada elemento. Un valor ideal para `key`sería el id único de cada elemento. Este atributo especial es un equivalente similar a`track-by`de la versión 1.x, pero funciona como un atributo, de modo que necesita usar`v-bind`para asignar valores dinámicos (usando una versión corta aquí):
339
339
340
340
```html
341
341
<divv-for="item in items":key="item.id">
342
342
<!-- content -->
343
343
</div>
344
344
```
345
345
346
-
It is recommended to provide a `key`with`v-for`whenever possible, unless the iterated DOM content is simple, or you are intentionally relying on the default behavior for performance gains.
346
+
Es recomendable usar `key`con`v-for`siempre que sea posible, a menos que el contenido DOM iterado sea sencillo, o intencionalmente dependa del funcionamiento por defecto para aprovechar la eficiencia.
347
347
348
-
Since it's a generic mechanism for Vue to identify nodes, the `key`also has other uses that are not specifically tied to`v-for`, as we will see later in the guide.
348
+
Como es un mecanismo genérico para que Vue identifique nodos, `key`también tiene otros usos que no están específicamente amarrados a`v-for`, como veremos más adelante en la guía.
349
349
350
-
## Array Change Detection
350
+
## Detección de cambio de array
351
351
352
-
### Mutation Methods
352
+
### Métodos de mutación
353
353
354
-
Vue wraps an observed array's mutation methods so they will also trigger view updates. The wrapped methods are:
354
+
Vue envuelve los métodos de mutación de un array observado, de modo que dispare actualizaciones de vista. Los métodos de envoltura son:
355
355
356
356
-`push()`
357
357
-`pop()`
@@ -361,28 +361,28 @@ Vue wraps an observed array's mutation methods so they will also trigger view up
361
361
-`sort()`
362
362
-`reverse()`
363
363
364
-
You can open the console and play with the previous examples' `items`array by calling their mutation methods. For example: `example1.items.push({ message: 'Baz' })`.
364
+
Puede abrir la consola y jugar con los arrays `items`de los ejemplos anteriores llamando sus métodos de mutación. Por ejemplo: `example1.items.push({ message: 'Baz' })`.
365
365
366
-
### Replacing an Array
366
+
### Reemplazando un Array
367
367
368
-
Mutation methods, as the name suggests, mutate the original array they are called on. In comparison, there are also non-mutating methods, e.g.`filter()`, `concat()`and`slice()`, which do not mutate the original Array but **always return a new array**. When working with non-mutating methods, you can just replace the old array with the new one:
368
+
Los métodos de mutación, como su nombre lo sugiere, mutan el array original del cuál han sido llamados. En comparación, también hay métodos no-mutadores, p.e.`filter()`, `concat()`y`slice()`, los cuales no cambian el array original pero **siempre retornan un nuevo array**. Cuando trabaje con métodos no mutadores, simplemente puede reemplazar el array viejo con el nuevo:
You might think this will cause Vue to throw away the existing DOM and re-render the entire list - luckily, that is not the case. Vue implements some smart heuristics to maximize DOM element reuse, so replacing an array with another array containing overlapping objects is a very efficient operation.
376
+
Puede estar inclinado a pensar que esto causará que Vue deseche el DOM existente y re-renderice la lista completa - por suerte, ese no es el caso. Vue implementa heurística inteligente para maximizar el re-uso de elementos DOM, de modo que reemplazar un array con otro que contenga algunos elementos en común es una operación muy eficiente.
377
377
378
-
### Caveats
378
+
### Problemas
379
379
380
-
Due to limitations in JavaScript, Vue **cannot**detect the following changes to an array:
380
+
Debido a las limitaciones en JavaScript, Vue **no puede**detectar los siguientes cambios en un array:
381
381
382
-
1.When you directly set an item with the index, e.g. `vm.items[indexOfItem] = newValue`
383
-
2.When you modify the length of the array, e.g. `vm.items.length = newLength`
382
+
1.Cuando directamente se cambia un elemento con el índice, p.e. `vm.items[indexOfItem] = newValue`
383
+
2.Cuando se modifica el tamaño del array, p.e. `vm.items.length = newLength`
384
384
385
-
To overcome caveat 1, both of the following will accomplish the same as `vm.items[indexOfItem] = newValue`, but will also trigger state updates in the reactivity system:
385
+
Para solventar el problema 1, los siguientes arreglos pueden lograr lo mismo que `vm.items[indexOfItem] = newValue`, pero a su vez activan actualizaciones de estado en el sistema reactivo:
Para circunvenir el problema 2, puede usar`splice`:
397
397
398
398
```js
399
399
example1.items.splice(newLength)
400
400
```
401
401
402
-
## Displaying Filtered/Sorted Results
402
+
## Mostrando Resultados Filtrados/Ordenados
403
403
404
-
Sometimes we want to display a filtered or sorted version of an array without actually mutating or resetting the original data. In this case, you can create a computed property that returns the filtered or sorted array.
404
+
A veces queremos mostrar una versión filtrada u ordenada de un array sin mutarlo o cambiando los datos originales. En este caso, podemos crear una propiedad calculada que retorne el array filtrado u ordenado.
405
405
406
-
For example:
406
+
Por ejemplo:
407
407
408
408
```html
409
409
<liv-for="n in evenNumbers">{{ n }}</li>
@@ -422,7 +422,7 @@ computed: {
422
422
}
423
423
```
424
424
425
-
Alternatively, you can also just use a method where computed properties are not feasible (e.g. inside nested `v-for` loops):
425
+
Alternativamente, puede sencillamente usar un método si las propiedades calculadas no son la mejor opción (p.e. anidadadas en ciclos `v-for`):
0 commit comments