-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[feature/composition-api-intro] Translate composition api introduction guide #9
base: master
Are you sure you want to change the base?
Conversation
|
||
## Why Composition API? | ||
## Por qué la API de Composición? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A minor change here.
## Por qué la API de Composición? | |
## ¿Por qué la API de Composición? |
|
||
Creating Vue components allows us to extract repeatable parts of the interface coupled with its functionality into reusable pieces of code. This alone can get our application pretty far in terms of maintainability and flexibility. However, our collective experience has proved that this alone might not be enough, especially when your application is getting really big – think several hundred components. When dealing with such large applications, sharing and reusing code becomes especially important. | ||
Crear componentes de Vue nos permite extraer partes repetibles de la interfaz junto con su funcionalidad en partes reusables de código. Esto puedo hacer que su aplicación llegue bastante lejos en términos de mantenibilidad y flexibilidad. Sin embargo, nuestra experiencia ha provado que solo esto puede no ser suficiente, especialmente cuando nuestra aplicación se está volviendo realmente grade - piense varios cientos de componentes. Al lidiar con este tipo de aplicaciones, compartir y reusar código se vuelve crucial. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some minor changes 😄.
Crear componentes de Vue nos permite extraer partes repetibles de la interfaz junto con su funcionalidad en partes reusables de código. Esto puedo hacer que su aplicación llegue bastante lejos en términos de mantenibilidad y flexibilidad. Sin embargo, nuestra experiencia ha provado que solo esto puede no ser suficiente, especialmente cuando nuestra aplicación se está volviendo realmente grade - piense varios cientos de componentes. Al lidiar con este tipo de aplicaciones, compartir y reusar código se vuelve crucial. | |
Crear componentes de Vue nos permite extraer partes repetibles de la interfaz junto con su funcionalidad en partes reusables de código. Esto puede hacer que su aplicación llegue bastante lejos en términos de mantenibilidad y flexibilidad. Sin embargo, nuestra experiencia ha probado que solo esto puede no ser suficiente, especialmente cuando nuestra aplicación se está volviendo realmente grade - piense varios cientos de componentes. Al lidiar con este tipo de aplicaciones, compartir y reusar código se vuelve crucial |
|
||
Let’s imagine that in our app, we have a view to show a list of repositories of a certain user. On top of that, we want to apply search and filter capabilities. Our component handling this view could look like this: | ||
Imaginemos que en nuestra aplicación, tenemos una vista que muestra una lista de repositorios de un cierto usuario. Sobre esto, quizas querramos agregar capacidad para buscar o filtrar la misma. Nuestra componente para dicha vista podría verse de la siguiente manera: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this change?
Imaginemos que en nuestra aplicación, tenemos una vista que muestra una lista de repositorios de un cierto usuario. Sobre esto, quizas querramos agregar capacidad para buscar o filtrar la misma. Nuestra componente para dicha vista podría verse de la siguiente manera: | |
Imaginemos que en nuestra aplicación, tenemos una vista que muestra una lista de repositorios de un cierto usuario. Sobre esto, quizás queramos agregar capacidad para buscar o filtrar la misma. Nuestra componente para dicha vista podría verse de la siguiente manera: |
|
||
Example presenting a large component where its **logical concerns** are grouped by colors. | ||
Ejemplo presentado una componente grande donde sus **responsabilidades lógicas** están agrupadas por color. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor change.
Ejemplo presentado una componente grande donde sus **responsabilidades lógicas** están agrupadas por color. | |
Ejemplo presentado un componente grande donde sus **responsabilidades lógicas** están agrupadas por color. |
|
||
It would be much nicer if we could collocate code related to the same logical concern. And this is exactly what the Composition API enables us to do. | ||
Sería mucho mejor si pudieron colocar el código relacionado a la misma responsabilidad lógica junto. Y esto es exactamente lo que la API de Composición nos permite hacer. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this?
Sería mucho mejor si pudieron colocar el código relacionado a la misma responsabilidad lógica junto. Y esto es exactamente lo que la API de Composición nos permite hacer. | |
Sería mucho mejor si pudiésemos colocar junto el código relacionado a la misma responsabilidad lógica. Y esto es exactamente lo que la API de Composición nos permite hacer. |
|
||
Now that we know the **why** we can get to the **how**. To start working with the Composition API we first need a place where we can actually use it. In a Vue component, we call this place the `setup`. | ||
Ahora que sabemos el **por qué** podemos entrar en el **cómo**. Para comenzar a trabajo con la API de Composición primero necesitamos un lugar donde la podamos utilizar. En un componente Vue, nosotros llamamos a este lugar el `setup`. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
After a little bit of research, I found that here porqué
is the appropiate translation. What do you guys think? @Tintef @migsalazar @sxcamacho
Ahora que sabemos el **por qué** podemos entrar en el **cómo**. Para comenzar a trabajo con la API de Composición primero necesitamos un lugar donde la podamos utilizar. En un componente Vue, nosotros llamamos a este lugar el `setup`. | |
Ahora que sabemos el **porqué** podemos entrar en el **cómo**. Para comenzar a trabajar con la API de Composición primero necesitamos un lugar donde la podamos utilizar. En un componente Vue, nosotros llamamos a este lugar el `setup`. |
|
||
The new `setup` component option is executed **before** the component is created, once the `props` are resolved, and serves as the entry point for composition API's. | ||
La nueva opción de componente `setup` se ejecuta **antes** de que el componente sea creado, una vez que las `props` fueron resultadas, y sirve como punto de entrada para la API de Composición. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this?
La nueva opción de componente `setup` se ejecuta **antes** de que el componente sea creado, una vez que las `props` fueron resultadas, y sirve como punto de entrada para la API de Composición. | |
La nueva opción de componente `setup` se ejecuta **antes** de que el componente sea creado, una vez que las `props` fueron resueltas, y sirve como punto de entrada para la API de Composición. |
|
||
::: warning | ||
Because the component instance is not yet created when `setup` is executed, there is no `this` inside a `setup` option. This means, with the exception of `props`, you won't be able to access any properties declared in the component – **local state**, **computed properties** or **methods**. | ||
Dado que la instancia de componente todavía no está creada cuando `setup` es ejecutado, no existe `this` dentro de la opción `setup`. Esto quiere decir que, con la excepción de las `props`, usted no tendra acceso a ninguna propiedad declarada en la componente -- **estado local**, **propiedades computadas** o **métodos**. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor changes here! 😄
Dado que la instancia de componente todavía no está creada cuando `setup` es ejecutado, no existe `this` dentro de la opción `setup`. Esto quiere decir que, con la excepción de las `props`, usted no tendra acceso a ninguna propiedad declarada en la componente -- **estado local**, **propiedades computadas** o **métodos**. | |
Dado que la instancia de componente todavía no está creada cuando `setup` es ejecutado, no existe `this` dentro de la opción `setup`. Esto quiere decir que, con la excepción de las `props`, usted no tendrá acceso a ninguna propiedad declarada en el componente -- **estado local**, **propiedades computadas** o **métodos**. |
::: | ||
|
||
The `setup` option should be a function that accepts `props` and `context` which we will talk about [later](composition-api-setup.html#arguments). Additionally, everything that we return from `setup` will be exposed to the rest of our component (computed properties, methods, lifecycle hooks and so on) as well as to the component's template. | ||
La opción `setup` debe ser una función que acepte `props` y `context`, sobre los cuales hablaremos [luego](composition-api-setup.html#arguments). También, todo lo que sea retornado desde `setup` sera expuesto al resto de nuestro componente (propiedades computadas, métodos, _hooks_ del ciclo de video y más) así como a la plantilla del componente. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor changes here 👍.
La opción `setup` debe ser una función que acepte `props` y `context`, sobre los cuales hablaremos [luego](composition-api-setup.html#arguments). También, todo lo que sea retornado desde `setup` sera expuesto al resto de nuestro componente (propiedades computadas, métodos, _hooks_ del ciclo de video y más) así como a la plantilla del componente. | |
La opción `setup` debe ser una función que acepte `props` y `context`, sobre los cuales hablaremos [luego](composition-api-setup.html#arguments). También, todo lo que sea retornado desde `setup` será expuesto al resto de nuestro componente (propiedades computadas, métodos, _hooks_ del ciclo de vida y más) así como a la plantilla del componente. |
} | ||
``` | ||
|
||
Now let’s start with extracting the first logical concern (marked as "1" in the original snippet). | ||
Ahora comencemos a extraer nuestra primer responsabilidad lógica (marcada como "1" en el _snippet_ original). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ahora comencemos a extraer nuestra primer responsabilidad lógica (marcada como "1" en el _snippet_ original). | |
Ahora comencemos a extraer nuestra primera responsabilidad lógica (marcada como "1" en el _snippet_ original). |
@@ -120,24 +120,24 @@ setup (props) { | |||
|
|||
return { | |||
repositories, | |||
getUserRepositories // functions returned behave the same as methods | |||
getUserRepositories // funciones retornas se comportan igual que los métodos |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor change here 😄.
getUserRepositories // funciones retornas se comportan igual que los métodos | |
getUserRepositories // funciones retornadas se comportan igual que los métodos |
} | ||
} | ||
``` | ||
|
||
This is our starting point, except it's not working yet because our `repositories` variable is not reactive. This means from a user's perspective, the repository list would remain empty. Let's fix that! | ||
Este es nuestro punto de partida, excepto que todavía no funciona dado que nuestra variable `repositories` no es reactiva. Esto quiere decir que, desde el punto de vista del usuarios, la lista de repositorios se mantendrá vacía. Arreglemoslo! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor changes here.
Este es nuestro punto de partida, excepto que todavía no funciona dado que nuestra variable `repositories` no es reactiva. Esto quiere decir que, desde el punto de vista del usuarios, la lista de repositorios se mantendrá vacía. Arreglemoslo! | |
Este es nuestro punto de partida, excepto que todavía no funciona dado que nuestra variable `repositories` no es reactiva. Esto quiere decir que, desde el punto de vista del usuarios, la lista de repositorios se mantendrá vacía. ¡Arreglémoslo! |
|
||
In Vue 3.0 we can make any variable reactive anywhere with a new `ref` function, like this: | ||
En Vue 3.0 podemos crear una variable reactiva en cualquier lado que la nueva función `ref`, de la siguiente manera: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this?
En Vue 3.0 podemos crear una variable reactiva en cualquier lado que la nueva función `ref`, de la siguiente manera: | |
En Vue 3.0 podemos crear una variable reactiva en cualquier lado con la nueva función `ref`, de la siguiente manera: |
|
||
```js | ||
import { ref } from 'vue' | ||
|
||
const counter = ref(0) | ||
``` | ||
|
||
`ref` takes the argument and returns it wrapped within an object with a `value` property, which can then be used to access or mutate the value of the reactive variable: | ||
`ref` toma el argumento y lo retorna envuelto en un objeto que una propiedad `value`, la cual puede ser usada luego para acceder o mutar el valor de la variable reactiva: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this?
`ref` toma el argumento y lo retorna envuelto en un objeto que una propiedad `value`, la cual puede ser usada luego para acceder o mutar el valor de la variable reactiva: | |
`ref` toma el argumento y lo retorna envuelto en un objeto con una propiedad `value`, la cual puede ser usada luego para acceder o mutar el valor de la variable reactiva: |
@@ -182,7 +182,7 @@ setup (props) { | |||
} | |||
``` | |||
|
|||
Done! Now whenever we call `getUserRepositories`, `repositories` will be mutated and the view will be updated to reflect the change. Our component should now look like this: | |||
Listo! Ahora siempre que llamemos `getUserRepositories`, `repositories` será mutada y la vista se actualizará para reflejar el cambio. Nuestro componente debería verse de la siguiente manera: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor change here 😄.
Listo! Ahora siempre que llamemos `getUserRepositories`, `repositories` será mutada y la vista se actualizará para reflejar el cambio. Nuestro componente debería verse de la siguiente manera: | |
¡Listo! Ahora siempre que llamemos `getUserRepositories`, `repositories` será mutada y la vista se actualizará para reflejar el cambio. Nuestro componente debería verse de la siguiente manera: |
@@ -227,17 +227,17 @@ export default { | |||
} | |||
``` | |||
|
|||
We have moved several pieces of our first logical concern into the `setup` method, nicely put close to each other. What’s left is calling `getUserRepositories` in the `mounted` hook and setting up a watcher to do that whenever the `user` prop changes. | |||
Hemos movidas unas cuantas partes de nuestra primera responsabilidad lógica dentro del método `setup`, muy cerca una de la otra. Lo que nos queda es invocar `getUserRepositories` dentro del _hook_ `mounted` y configurar un _watcher_ para realizarlo cada vez que nuestra prop `user` cambie. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this? 😄
Hemos movidas unas cuantas partes de nuestra primera responsabilidad lógica dentro del método `setup`, muy cerca una de la otra. Lo que nos queda es invocar `getUserRepositories` dentro del _hook_ `mounted` y configurar un _watcher_ para realizarlo cada vez que nuestra prop `user` cambie. | |
Hemos movido unas cuantas partes de nuestra primera responsabilidad lógica dentro del método `setup`, muy cerca una de la otra. Lo que nos queda es invocar `getUserRepositories` dentro del _hook_ `mounted` y configurar un _watcher_ para que sea invocado cada vez que nuestra prop `user` cambie. |
|
||
These functions accept a callback that will be executed when the hook is called by the component. | ||
Estas funciones aceptan un `callback` que será ejecutado cuando el _hook_ es llamad por el componente. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo here.
Estas funciones aceptan un `callback` que será ejecutado cuando el _hook_ es llamad por el componente. | |
Estas funciones aceptan un `callback` que será ejecutado cuando el _hook_ es llamado por el componente. |
@@ -251,7 +251,7 @@ setup (props) { | |||
repositories.value = await fetchUserRepositories(props.user) | |||
} | |||
|
|||
onMounted(getUserRepositories) // on `mounted` call `getUserRepositories` | |||
onMounted(getUserRepositories) // al "montarse" invoca `getUserRepositories` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this? This is to keep it consistent with the original docs.
onMounted(getUserRepositories) // al "montarse" invoca `getUserRepositories` | |
onMounted(getUserRepositories) // al `montarse` invoca `getUserRepositories` |
} | ||
} | ||
} | ||
``` | ||
|
||
For more details on `watch`, refer to our [in-depth guide](). | ||
Por más detalles sobre `watch`, vea nuestra [guía en profundidad](). |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this?
Por más detalles sobre `watch`, vea nuestra [guía en profundidad](). | |
Para más detalles sobre `watch`, vea nuestra [guía en profundidad](). |
|
||
**Let’s now apply it to our example:** | ||
**Ahora apliquemoslo a nuestro ejemplo:** |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor change here 😄.
**Ahora apliquemoslo a nuestro ejemplo:** | |
**Ahora apliquémoslo a nuestro ejemplo:** |
|
||
```js | ||
// src/components/UserRepositories.vue `setup` function | ||
import { fetchUserRepositories } from '@/api/repositories' | ||
import { ref, onMounted, watch, toRefs } from 'vue' | ||
|
||
// in our component | ||
// en nuestro componentes |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo here.
// en nuestro componentes | |
// en nuestro componente |
repositories.value = await fetchUserRepositories(user.value) | ||
} | ||
|
||
onMounted(getUserRepositories) | ||
|
||
// set a watcher on the Reactive Reference to user prop | ||
// configurar un watcher en la Referencia Reactica para la prop user |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo here.
// configurar un watcher en la Referencia Reactica para la prop user | |
// configurar un watcher en la Referencia Reactiva para la prop user |
|
||
With those changes in place, we've just moved the whole first logical concern into a single place. We can now do the same with the second concern – filtering based on `searchQuery`, this time with a computed property. | ||
Con estos cambios, hemos movido toda la primer responsabilidad lógica a un único lugar. Ahora podemos realizar lo mismo con la segunda responsabilidad - filtrar según `searchQuery`, esta vez con una propiedad computada. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo here 😄
Con estos cambios, hemos movido toda la primer responsabilidad lógica a un único lugar. Ahora podemos realizar lo mismo con la segunda responsabilidad - filtrar según `searchQuery`, esta vez con una propiedad computada. | |
Con estos cambios, hemos movido toda la primera responsabilidad lógica a un único lugar. Ahora podemos realizar lo mismo con la segunda responsabilidad - filtrar según `searchQuery`, esta vez con una propiedad computada. |
|
||
### Standalone `computed` properties | ||
### Propiedad Computadas Independientes |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What do you think about this?
### Propiedad Computadas Independientes | |
### Propiedades Computadas Independientes |
repositories.value = await fetchUserRepositories(user.value) | ||
} | ||
|
||
onMounted(getUserRepositories) | ||
|
||
// set a watcher on the Reactive Reference to user prop | ||
// configurar un watcher en la Referencia Reactica para la prop user |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo here.
// configurar un watcher en la Referencia Reactica para la prop user | |
// configurar un watcher en la Referencia Reactiva para la prop user |
@@ -392,7 +392,7 @@ setup (props) { | |||
} | |||
``` | |||
|
|||
We could do the same for other **logical concerns** but you might be already asking the question – _Isn’t this just moving the code to the `setup` option and making it extremely big?_ Well, that’s true. That’s why before moving on with the other responsibilities, we will first extract the above code into a standalone **composition function**. Let's start with creating `useUserRepositories`: | |||
Podríamos realizar lo mismo para la atra **responsabilidad lógica**, pero usted seguramente se este realizando la siguiente pregunta - _¿Esto no es simplemente mover el código a la opción `setup` y hacer la misma extremadamente grande?_ Bueno, eso es cierto. Es por esto que antes de mover las otras responsabilidades, primero extraeremos el código de arribo en una **función de composición** independiente. Comencemos por crear `useUserRepositories`: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Typo here.
Podríamos realizar lo mismo para la atra **responsabilidad lógica**, pero usted seguramente se este realizando la siguiente pregunta - _¿Esto no es simplemente mover el código a la opción `setup` y hacer la misma extremadamente grande?_ Bueno, eso es cierto. Es por esto que antes de mover las otras responsabilidades, primero extraeremos el código de arribo en una **función de composición** independiente. Comencemos por crear `useUserRepositories`: | |
Podríamos realizar lo mismo para la otra **responsabilidad lógica**, pero usted seguramente se esté realizando la siguiente pregunta - _¿Esto no es simplemente mover el código a la opción `setup` y hacer la misma extremadamente grande?_ Bueno, eso es cierto. Es por esto que antes de mover las otras responsabilidades, primero extraeremos el código de arriba en una **función de composición** independiente. Comencemos por crear `useUserRepositories`: |
@@ -483,7 +483,7 @@ export default { | |||
} | |||
``` | |||
|
|||
At this point you probably already know the drill, so let’s skip to the end and migrate the leftover filtering functionality. We don’t really need to get into the implementation details as it’s not the point of this guide. | |||
En este punto usted ya sabe como va la cosa, así que vayamos al final y migremos la funcionalidad de filtrado restante. No tenemos que entrar en los detalles de implementación, puesto que no va al caso de esta guía. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor change here 😄.
En este punto usted ya sabe como va la cosa, así que vayamos al final y migremos la funcionalidad de filtrado restante. No tenemos que entrar en los detalles de implementación, puesto que no va al caso de esta guía. | |
En este punto usted ya sabe cómo va la cosa, así que vayamos al final y migremos la funcionalidad de filtrado restante. No tenemos que entrar en los detalles de implementación, puesto que no va al caso de esta guía. |
@@ -526,6 +526,6 @@ export default { | |||
} | |||
``` | |||
|
|||
And we are done! | |||
Y terminamos! |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Minor change 😄.
Y terminamos! | |
¡Y terminamos! |
Excellent work @Tintef! 🎉👍 |
Description of Problem
None.
Proposed Solution
Translate
src/guide/composition-api-introduction.md
Additional Information
None.