` in order to fix this error.
+Na v2.x, componentes multi-raiz não eram suportados e iriam emitir um aviso no caso de um usuário acidentalmente criar um. Como resultado, vários componentes são envolvidos em uma única `
` de forma a corrigir esse erro.
```html
@@ -24,9 +24,9 @@ In 2.x, multi-root components were not supported and would emit a warning when a
```
-## 3.x Syntax
+## Sintaxe v3.x
-In 3.x, components now can have multiple root nodes! However, this does require developers to explicitly define where attributes should be distributed.
+Na v3.x, componentes agora podem ter vários nós raiz! No entanto, isso requer aos desenvolvedores definir explicitamente onde os atributos deveriam ser distribuídos.
```html
@@ -37,4 +37,4 @@ In 3.x, components now can have multiple root nodes! However, this does require
```
-For more information on how attribute inheritance works, see [Non-Prop Attributes](/guide/component-attrs.html).
+Para mais informações sobre como a herança de atributos funciona, veja [Atributos Não-Propriedades](/guide/component-attrs.html).
diff --git a/src/guide/migration/functional-components.md b/src/guide/migration/functional-components.md
index f84aa94b20..fe319e67b6 100644
--- a/src/guide/migration/functional-components.md
+++ b/src/guide/migration/functional-components.md
@@ -3,36 +3,36 @@ badges:
- breaking
---
-# Functional Components
+# Componentes Funcionais
-## Overview
+## Visão Geral
-In terms of what has changed, at a high level:
+Sobre o que mudou, em visão geral:
-- Performance gains from 2.x for functional components are now negligible in 3.x, so we recommend just using stateful components
-- Functional components can only be created using a plain function that receives `props` and `context` (i.e., `slots`, `attrs`, `emit`)
-- **BREAKING:** `functional` attribute on single-file component (SFC) `
` is removed
-- **BREAKING:** `{ functional: true }` option in components created by functions is removed
+- O ganho de performance com componentes funcionais na v2.x, se tornou insignificante na v3.x, então recomendamos o uso normal de componentes com estado
+- Componentes Funcionais só podem ser criados com uma função simples que recebe `props` e `context` (i.e., `slots`, `attrs`, `emit`)
+- **BREAKING:** O atributo `functional` na tag `` em componentes single-file (SFC) foi removido
+- **BREAKING:** A opção `{ functional: true }` em componentes criados por funções foi removida
-For more information, read on!
+Para mais informações, continue lendo!
-## Introduction
+## Introdução
-In Vue 2, functional components had two primary use cases:
+No Vue 2, componentes funcionais tinham dois casos de uso primários:
-- as a performance optimization, because they initialized much faster than stateful components
-- to return multiple root nodes
+- Como otimização de performance, pois inicializavam muito mais rápido que componentes com estado
+- Para retornar múltiplos nós raiz (root nodes)
-However, in Vue 3, the performance of stateful components has improved to the point that the difference is negligible. In addition, stateful components now also include the ability to return multiple root nodes.
+Porém, no Vue 3, a performance de componentes com estado melhorou, a ponto de a diferença ser insignificante. Além disso, componentes com estado agora também incluem a possibilidade de retornar multiplos nós raiz (root nodes).
-As a result, the only remaining use case for functional components is simple components, such as a component to create a dynamic heading. Otherwise, it is recommended to use stateful components as you normally would.
+Como resultado, o único caso de uso restante para componentes funcionais é um componente simples, como um componente para um cabeçalho dinâmico. Caso contrário, é recomendável usar componentes com estado, como você normalmente faria.
-## 2.x Syntax
+## Sintaxe v2.x
-Using the `` component, which is responsible for rendering out the appropriate heading (i.e., `h1`, `h2`, `h3`, etc.), this could have been written as a single-file component in 2.x as:
+Considerando o componente ``, que é responsável por renderizar o cabeçalho apropriado (i.e., `h1`, `h2`, `h3`, etc.), poderia ser escrito como um componente single-file na v2.x da seguinte forma:
```js
-// Vue 2 Functional Component Example
+// Exemplo de Componente Funcional no Vue 2
export default {
functional: true,
props: ['level'],
@@ -42,10 +42,10 @@ export default {
}
```
-Or, for those who preferred the `` in a single-file component:
+Ou, para aqueles que preferem a tag `` em um componente single-file:
```vue
-
+
```
-## 3.x Syntax
+## Sintaxe v3.x
-### Components Created by Functions
+### Componentes Criados por Funções
-Now in Vue 3, all functional components are created with a plain function. In other words, there is no need to define the `{ functional: true }` component option.
+Agora no Vue 3, todos os componentes funcionais são criados com uma função simples. Em outras palavras, não há mais a necessidade de definir a opção `{ functional: true }` no componente.
-They will receive two arguments: `props` and `context`. The `context` argument is an object that contains a component's `attrs`, `slots`, and `emit` properties.
+As funções receberão dois argumentos: `props` e `context`. O argumento `context` é um objeto que contém as propriedados `attrs`, `slots`, e `emit` de um componente.
-In addition, rather than implicitly provide `h` in a `render` function, `h` is now imported globally.
+Além disso, ao invés de fornecer implicitamente o argumento `h` em uma função `render`, `h` agora é importado globalmente.
-Using the previously mentioned example of a `` component, here is how it looks now.
+Usando o exemplo mencionado anteriormente de um componente ``, aqui está como ficou agora:
```js
import { h } from 'vue'
@@ -85,11 +85,11 @@ DynamicHeading.props = ['level']
export default DynamicHeading
```
-### Single File Components (SFCs)
+### Componentes Single-File (SFCs)
-In 3.x, the performance difference between stateful and functional components has been drastically reduced and will be insignificant in most use cases. As a result, the migration path for developers using `functional` on SFCs is to remove the attribute and rename all references of `props` to `$props` and `attrs` to `$attrs`.
+Na v3.x, a diferença de performance entre componentes funcionais e de estado foi reduzida drasticamente, e será insignificante na maioria dos casos. Como resultado, o caminho de migração para desenvolvedores usando o atributo `functional` em componentes single-page é remover o atributo e renomear as referências de `props` para `$props` e `attrs` para `$attrs`.
-Using our `` example from before, here is how it would look now.
+Usando o exemplo `` de antes, aqui está como ficaria agora:
```vue{1,3,4}
@@ -106,15 +106,15 @@ export default {
```
-The main differences are that:
+As principais diferenças são:
-1. `functional` attribute removed on ``
-1. `listeners` are now passed as part of `$attrs` and can be removed
+1. Atributo `functional` removido da tag ``
+1. `listeners` agora são passados como parte de `$attrs` e pode ser removido
-## Next Steps
+## Próximos Passos
-For more information on the usage of the new functional components and the changes to render functions in general, see:
+Para mais informação sobre o uso dos novos componentes funcionais e as mudanças nas funções de renderização em geral, acesse:
-- [Migration: Render Functions](/guide/migration/render-function-api.html)
-- [Guide: Render Functions](/guide/render-function.html)
-- [Migration build flag: `COMPONENT_FUNCTIONAL`](migration-build.html#compat-configuration)
+- [Migração: API da Função de Renderização](/guide/migration/render-function-api.html)
+- [Guia: Funções de Renderização](/guide/render-function.html)
+- [Sinalizador na compilação de migração: `COMPONENT_FUNCTIONAL`](migration-build.html#configuracao-de-compatibilidade)
diff --git a/src/guide/migration/global-api-treeshaking.md b/src/guide/migration/global-api-treeshaking.md
index 502a272334..a0500e0081 100644
--- a/src/guide/migration/global-api-treeshaking.md
+++ b/src/guide/migration/global-api-treeshaking.md
@@ -3,119 +3,119 @@ badges:
- breaking
---
-# Global API Treeshaking
+# TreeShaking da API Global
-## 2.x Syntax
+## Sintaxe v2.x
-If you’ve ever had to manually manipulate DOM in Vue, you might have come across this pattern:
+Se você já teve que manipular manualmente o DOM no Vue, pode ter encontrado este padrão:
```js
import Vue from 'vue'
Vue.nextTick(() => {
- // something DOM-related
+ // algo relacionado ao DOM
})
```
-Or, if you’ve been unit-testing an application involving [async components](/guide/component-dynamic-async.html), chances are you’ve written something like this:
+Ou, se você fez testes unitários em seu aplicativo envolvendo [componentes assíncronos](/guide/component-dynamic-async.html), provavelmente você escreveu algo assim:
```js
import { shallowMount } from '@vue/test-utils'
import { MyComponent } from './MyComponent.vue'
-test('an async feature', async () => {
+test('um recurso assíncrono', async () => {
const wrapper = shallowMount(MyComponent)
- // execute some DOM-related tasks
+ // execute alguma tarefa relacionada ao DOM
await wrapper.vm.$nextTick()
- // run your assertions
+ // execute suas asserções
})
```
-`Vue.nextTick()` is a global API exposed directly on a single Vue object – in fact, the instance method `$nextTick()` is just a handy wrapper around `Vue.nextTick()` with the callback’s `this` context automatically bound to the current instance for convenience.
+`Vue.nextTick()` é uma API global exposta diretamente em um único objeto Vue - na verdade, o método de instância `$nextTick()` é apenas um *wrapper* em torno de `Vue.nextTick()` com o contexto `this` do retorno de chamada automaticamente vinculado à instância atual por conveniência.
-But what if you’ve never had to deal with manual DOM manipulation, nor are you using or testing async components in your app? Or, what if, for whatever reason, you prefer to use the good old `window.setTimeout()` instead? In such a case, the code for `nextTick()` will become dead code – that is, code that’s written but never used. And dead code is hardly a good thing, especially in our client-side context where every kilobyte matters.
+Mas e se você nunca teve que lidar com manipulação manual do DOM, nem está usando ou testando componentes assíncronos em seu aplicativo? Ou, e se, por qualquer motivo, você preferir usar o bom e velho `window.setTimeout()` em vez disso? Nesse caso, o código para `nextTick()` se tornará um código morto - ou seja, o código que foi escrito, mas nunca usado. E código morto dificilmente é uma coisa boa, especialmente em nosso contexto do lado do cliente, onde cada kilobyte é importante.
-Module bundlers like [webpack](https://webpack.js.org/) support [tree-shaking](https://webpack.js.org/guides/tree-shaking/), which is a fancy term for “dead code elimination.” Unfortunately, due to how the code is written in previous Vue versions, global APIs like `Vue.nextTick()` are not tree-shakeable and will be included in the final bundle regardless of where they are actually used or not.
+Os empacotadores de módulo, como o [webpack](https://webpack.js.org/), oferecem suporte à [tree-shaking](https://webpack.js.org/guides/tree-shaking/), que é um termo sofisticado para “eliminação de código morto”. Infelizmente, devido à forma como o código é escrito nas versões anteriores do Vue, APIs globais como `Vue.nextTick()` não podem ser eliminadas com *tree-shaking* e serão incluídas no pacote final, independentemente de onde sejam realmente usadas ou não.
-## 3.x Syntax
+## Sintaxe v3.x
-In Vue 3, the global and internal APIs have been restructured with tree-shaking support in mind. As a result, the global APIs can now only be accessed as named exports for the ES Modules build. For example, our previous snippets should now look like this:
+No Vue 3, as APIs globais e internas foram reestruturadas tendo em mente o suporte à *tree-shaking*. Como resultado, as APIs globais agora podem ser acessadas apenas como exportações nomeadas para a construção de Módulos ES. Por exemplo, nossos blocos de códigos anteriores agora devem ser semelhantes a este:
```js
import { nextTick } from 'vue'
nextTick(() => {
- // something DOM-related
+ // algo relacionado ao DOM
})
```
-and
+e
```js
import { shallowMount } from '@vue/test-utils'
import { MyComponent } from './MyComponent.vue'
import { nextTick } from 'vue'
-test('an async feature', async () => {
+test('um recurso assíncrono', async () => {
const wrapper = shallowMount(MyComponent)
- // execute some DOM-related tasks
+ // execute alguma tarefa relacionada ao DOM
await nextTick()
- // run your assertions
+ // execute suas asserções
})
```
-Calling `Vue.nextTick()` directly will now result in the infamous `undefined is not a function` error.
+Chamar `Vue.nextTick()` diretamente agora resultará no abominável erro `undefined is not a function`.
-With this change, provided the module bundler supports tree-shaking, global APIs that are not used in a Vue application will be eliminated from the final bundle, resulting in an optimal file size.
+Com essa mudança, dado que o empacotador de módulos suporte *tree-shaking*, APIs globais que não são usadas em seu aplicativo Vue serão eliminadas do pacote final, resultando em um ótimo tamanho de arquivo.
-## Affected APIs
+## APIs Afetadas
-These global APIs in Vue 2.x are affected by this change:
+Essas APIs globais no Vue 2.x são afetadas por esta mudança:
- `Vue.nextTick`
-- `Vue.observable` (replaced by `Vue.reactive`)
+- `Vue.observable` (substituído por `Vue.reactive`)
- `Vue.version`
-- `Vue.compile` (only in full builds)
-- `Vue.set` (only in compat builds)
-- `Vue.delete` (only in compat builds)
+- `Vue.compile` (apenas em compilações completas)
+- `Vue.set` (apenas em compilações de compatibilidade)
+- `Vue.delete` (apenas em compilações de compatibilidade)
-## Internal Helpers
+## Ajudantes Internos
-In addition to public APIs, many of the internal components/helpers are now exported as named exports as well. This allows the compiler to output code that only imports features when they are used. For example the following template:
+Além das APIs públicas, muitos dos componentes/ajudantes internos agora também são exportados como exportações nomeadas. Isso permite que o compilador produza um código que importa apenas recursos quando eles são usados. Por exemplo, o seguinte template:
```html
- hello
+ olá
```
-is compiled into something similar to the following:
+é compilado em algo semelhante ao seguinte:
```js
import { h, Transition, withDirectives, vShow } from 'vue'
export function render() {
- return h(Transition, [withDirectives(h('div', 'hello'), [[vShow, this.ok]])])
+ return h(Transition, [withDirectives(h('div', 'olá'), [[vShow, this.ok]])])
}
```
-This essentially means the `Transition` component only gets imported when the application actually makes use of it. In other words, if the application doesn’t have any `` component, the code supporting this feature will not be present in the final bundle.
+Isso significa essencialmente que o componente `Transition` só é importado quando o aplicativo realmente faz uso dele. Em outras palavras, se o aplicativo não tiver nenhum componente ``, o código que suporta esse recurso não estará presente no pacote final.
-With global tree-shaking, the users only “pay” for the features they actually use. Even better, knowing that optional features won't increase the bundle size for applications not using them, framework size has become much less a concern for additional core features in the future, if at all.
+Com o *tree-shaking* global, os usuários “pagam” apenas pelos recursos que realmente usam. Melhor ainda, sabendo que os recursos opcionais não aumentarão o tamanho do pacote para aplicativos que não os utilizam, o tamanho do framework se tornou muito menos uma preocupação para recursos centrais adicionais no futuro, isso se houver.
-::: warning Important
-The above only applies to the [ES Modules builds](/guide/installation.html#explanation-of-different-builds) for use with tree-shaking capable bundlers - the UMD build still includes all features and exposes everything on the Vue global variable (and the compiler will produce appropriate output to use APIs off the global instead of importing).
+::: warning Importante
+O que foi dito acima se aplica apenas as [Construções de Módulos ES](/guide/installation.html#explanation-of-different-builds) para uso com empacotadores capazes de aplicar *tree-shaking* - o construtor UMD ainda inclui todos os recursos e expõe tudo na variável global Vue (e o compilador produzirá a saída apropriada para usar APIs fora do global em vez de importar).
:::
-## Usage in Plugins
+## Uso em Plugins
-If your plugin relies on an affected Vue 2.x global API, for instance:
+Se o seu plug-in depende de uma API global do Vue 2.x afetada, por exemplo:
```js
const plugin = {
@@ -127,7 +127,7 @@ const plugin = {
}
```
-In Vue 3, you’ll have to import it explicitly:
+No Vue 3, você terá que importá-lo explicitamente:
```js
import { nextTick } from 'vue'
@@ -141,7 +141,7 @@ const plugin = {
}
```
-If you use a module bundle like webpack, this may cause Vue’s source code to be bundled into the plugin, and more often than not that’s not what you'd expect. A common practice to prevent this from happening is to configure the module bundler to exclude Vue from the final bundle. In webpack's case, you can use the [`externals`](https://webpack.js.org/configuration/externals/) configuration option:
+Se você usar um empacotador de módulo como webpack, isso pode fazer com que o código-fonte do Vue seja agrupado no plug-in e, na maioria das vezes, não é o que você esperava. Uma prática comum para evitar que isso aconteça é configurar o empacotador de módulo para excluir Vue do pacote final. No caso do webpack, você pode usar a opção de configuração [`externals`](https://webpack.js.org/configuration/externals/):
```js
// webpack.config.js
@@ -153,9 +153,9 @@ module.exports = {
}
```
-This will tell webpack to treat the Vue module as an external library and not bundle it.
+Isso dirá ao webpack para tratar o módulo Vue como uma biblioteca externa e não empacotá-lo.
-If your module bundler of choice happens to be [Rollup](https://rollupjs.org/), you basically get the same effect for free, as by default Rollup will treat absolute module IDs (`'vue'` in our case) as external dependencies and not include them in the final bundle. During bundling though, it might emit a [“Treating vue as external dependency”](https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency) warning, which can be suppressed with the `external` option:
+Se o empacotador de módulo de sua escolha for [Rollup](https://rollupjs.org/), você basicamente obterá o mesmo efeito de graça, pois por padrão o Rollup tratará IDs de módulo absolutos (`'vue'` em nosso caso) como dependências externas e não incluí-las no pacote final. No entanto, durante o empacotamento, ele pode emitir um aviso [“Tratando vue como dependência externa”](https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency), que pode ser suprimido com a opção `external`:
```js
// rollup.config.js
diff --git a/src/guide/migration/global-api.md b/src/guide/migration/global-api.md
index 564247dcb1..1e912a5c65 100644
--- a/src/guide/migration/global-api.md
+++ b/src/guide/migration/global-api.md
@@ -3,20 +3,20 @@ badges:
- breaking
---
-# Global API
+# API Global
-Vue 2.x has a number of global APIs and configurations that globally mutate Vue’s behavior. For instance, to register a global component, you would use the `Vue.component` API like this:
+O Vue 2.x possui várias APIs e configurações globais que alteram globalmente o comportamento do Vue. Por exemplo, para registrar um componente global, você usaria a API `Vue.component` assim:
```js
Vue.component('button-counter', {
data: () => ({
count: 0
}),
- template: 'Clicked {{ count }} times. '
+ template: 'Clicado {{ count }} vezes. '
})
```
-Similarly, this is how a global directive is declared:
+Da mesma forma, é assim que uma diretiva global é declarada:
```js
Vue.directive('focus', {
@@ -24,27 +24,27 @@ Vue.directive('focus', {
})
```
-While this approach is convenient, it leads to a couple of problems. Technically, Vue 2 doesn't have a concept of an "app". What we define as an app is simply a root Vue instance created via `new Vue()`. Every root instance created from the same Vue constructor **shares the same global configuration**. As a result:
+Embora essa abordagem seja conveniente, ela leva a alguns problemas. Tecnicamente, o Vue 2 não tem um conceito de "aplicativo". O que definimos como um aplicativo é simplesmente uma instância raiz do Vue criada via `new Vue()`. Cada instância raiz criada a partir do mesmo construtor Vue **compartilha a mesma configuração global**. Como resultado:
-- Global configuration makes it easy to accidentally pollute other test cases during testing. Users need to carefully store original global configuration and restore it after each test (e.g. resetting `Vue.config.errorHandler`). Some APIs like `Vue.use` and `Vue.mixin` don't even have a way to revert their effects. This makes tests involving plugins particularly tricky. In fact, vue-test-utils has to implement a special API `createLocalVue` to deal with this:
+- A configuração global facilita a poluição acidental de outros casos de teste durante o teste. Os usuários precisam armazenar cuidadosamente a configuração global original e restaurá-la após cada teste (ex.: redefinindo `Vue.config.errorHandler`). Algumas APIs como `Vue.use` e `Vue.mixin` nem têm como reverter seus efeitos. Isso torna os testes envolvendo plugins particularmente complicados. Na verdade, vue-test-utils tem que implementar uma API especial `createLocalVue` para lidar com isso:
```js
import { createLocalVue, mount } from '@vue/test-utils'
- // create an extended `Vue` constructor
+ // cria um construtor `Vue` estendido
const localVue = createLocalVue()
- // install a plugin “globally” on the “local” Vue constructor
+ // instala um plugin “globalmente” no construtor “local” do Vue
localVue.use(MyPlugin)
- // pass the `localVue` to the mount options
+ // passa o `localVue` para as opções de montagem
mount(Component, { localVue })
```
-- Global configuration makes it difficult to share the same copy of Vue between multiple "apps" on the same page, but with different global configurations.
+- A configuração global dificulta o compartilhamento da mesma cópia do Vue entre vários "apps" na mesma página, mas com configurações globais diferentes.
```js
- // this affects both root instances
+ // isso afeta ambas as instâncias raiz
Vue.mixin({
/* ... */
})
@@ -53,11 +53,11 @@ While this approach is convenient, it leads to a couple of problems. Technically
const app2 = new Vue({ el: '#app-2' })
```
-To avoid these problems, in Vue 3 we introduce…
+Para evitar esses problemas, no Vue 3 apresentamos…
-## A New Global API: `createApp`
+## Uma Nova API Global: `createApp`
-Calling `createApp` returns an _app instance_, a new concept in Vue 3.
+Chamar `createApp` retorna uma _instância de aplicativo_, um novo conceito no Vue 3.
```js
import { createApp } from 'vue'
@@ -65,7 +65,7 @@ import { createApp } from 'vue'
const app = createApp({})
```
-If you're using a [CDN](/guide/installation.html#cdn) build of Vue then `createApp` is exposed via the global `Vue` object:
+Se você estiver usando uma versão [CDN](/guide/installation.html#cdn) do Vue, o `createApp` será exposto por meio do objeto global `Vue`:
```js
const { createApp } = Vue
@@ -73,84 +73,84 @@ const { createApp } = Vue
const app = createApp({})
```
-An app instance exposes a subset of the Vue 2 global APIs. The rule of thumb is _any APIs that globally mutate Vue's behavior are now moved to the app instance_. Here is a table of the Vue 2 global APIs and their corresponding instance APIs:
+Uma instância de aplicativo expõe um subconjunto das APIs globais do Vue 2. A regra geral é _qualquer API que altere globalmente o comportamento do Vue agora foi movida para a instância do aplicativo_. Aqui está uma tabela das APIs globais do Vue 2 e suas APIs de instância correspondentes:
-| 2.x Global API | 3.x Instance API (`app`) |
-| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
-| Vue.config | app.config |
-| Vue.config.productionTip | _removed_ ([see below](#config-productiontip-removed)) |
-| Vue.config.ignoredElements | app.config.compilerOptions.isCustomElement ([see below](#config-ignoredelements-is-now-config-compileroptions-iscustomelement)) |
-| Vue.component | app.component |
-| Vue.directive | app.directive |
-| Vue.mixin | app.mixin |
-| Vue.use | app.use ([see below](#a-note-for-plugin-authors)) |
-| Vue.prototype | app.config.globalProperties ([see below](#vue-prototype-replaced-by-config-globalproperties)) |
-| Vue.extend | _removed_ ([see below](#vue-extend-removed)) |
+| 2.x API Global | 3.x API de Instância (`app`) |
+| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
+| Vue.config | app.config |
+| Vue.config.productionTip | _removido_ ([veja abaixo](#config-productiontip-removido)) |
+| Vue.config.ignoredElements | app.config.compilerOptions.isCustomElement ([veja abaixo](#config-ignoredelements-agora-e-config-compileroptions-iscustomelement)) |
+| Vue.component | app.component |
+| Vue.directive | app.directiva |
+| Vue.mixin | app.mixin |
+| Vue.use | app.use ([veja abaixo](#uma-nota-para-autores-de-plugins)) |
+| Vue.prototype | app.config.globalProperties ([veja abaixo](#vue-prototype-substituido-por-config-globalproperties)) |
+| Vue.extend | _removido_ ([veja abaixo](#vue-extend-removido)) |
-All other global APIs that do not globally mutate behavior are now named exports, as documented in [Global API Treeshaking](./global-api-treeshaking.html).
+Todas as outras APIs globais que não alteram globalmente o comportamento agora são exportações nomeadas, conforme documentado em [_Treeshaking_ da API Global](./global-api-treeshaking.html).
-### `config.productionTip` Removed
+### `config.productionTip` Removido
-In Vue 3.x, the "use production build" tip will only show up when using the "dev + full build" (the build that includes the runtime compiler and has warnings).
+No Vue 3.x, a dica _"use production build"_ só aparecerá ao usar o _"dev + full build"_ (a versão que inclui o compilador em tempo de execução e tem avisos).
-For ES modules builds, since they are used with bundlers, and in most cases a CLI or boilerplate would have configured the production env properly, this tip will no longer show up.
+Para construções de módulos ES, como são usados com empacotadores e, na maioria dos casos, uma CLI ou _boilerplate_ configuraria o ambiente de produção corretamente, essa dica não aparecerá mais.
-[Migration build flag: `CONFIG_PRODUCTION_TIP`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `CONFIG_PRODUCTION_TIP`](migration-build.html#configuracao-de-compatibilidade)
-### `config.ignoredElements` Is Now `config.compilerOptions.isCustomElement`
+### `config.ignoredElements` Agora É `config.compilerOptions.isCustomElement`
-This config option was introduced with the intention to support native custom elements, so the renaming better conveys what it does. The new option also expects a function which provides more flexibility than the old string / RegExp approach:
+Essa opção de configuração foi introduzida com a intenção de oferecer suporte a elementos personalizados nativos, então a renomeação transmite melhor o que ela faz. A nova opção também espera uma função, o que fornece mais flexibilidade do que a antiga abordagem de string / RegExp:
```js
-// before
+// antes
Vue.config.ignoredElements = ['my-el', /^ion-/]
-// after
+// depois
const app = createApp({})
app.config.compilerOptions.isCustomElement = tag => tag.startsWith('ion-')
```
-::: tip Important
+::: tip Importante
-In Vue 3, the check of whether an element is a component or not has been moved to the template compilation phase, therefore this config option is only respected when using the runtime compiler. If you are using the runtime-only build, `isCustomElement` must be passed to `@vue/compiler-dom` in the build setup instead - for example, via the [`compilerOptions` option in vue-loader](https://vue-loader.vuejs.org/options.html#compileroptions).
+No Vue 3, a verificação de se um elemento é um componente foi movida para a fase de compilação do _template_, portanto esta opção de configuração só é respeitada quando se utiliza a compilação em tempo de execução. Se você estiver usando a compilação somente em tempo de execução, `isCustomElement` deve ser passado para `@vue/compiler-dom` na configuração da compilação - por exemplo, através da opção [`compilerOptions` no vue-loader](https://vue-loader.vuejs.org/options.html#compileroptions).
-- If `config.compilerOptions.isCustomElement` is assigned to when using a runtime-only build, a warning will be emitted instructing the user to pass the option in the build setup instead;
-- This will be a new top-level option in the Vue CLI config.
+- Se `config.compilerOptions.isCustomElement` for atribuído ao usar uma compilação somente em tempo de execução, um aviso será emitido instruindo o usuário a passar a opção na configuração da compilação;
+- Esta será uma nova opção de nível superior na configuração do Vue CLI.
:::
-[Migration build flag: `CONFIG_IGNORED_ELEMENTS`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `CONFIG_IGNORED_ELEMENTS`](migration-build.html#configuracao-de-compatibilidade)
-### `Vue.prototype` Replaced by `config.globalProperties`
+### `Vue.prototype` Substituído por `config.globalProperties`
-In Vue 2, `Vue.prototype` was commonly used to add properties that would be accessible in all components.
+No Vue 2, `Vue.prototype` era comumente usado para adicionar propriedades que seriam acessíveis em todos os componentes.
-The equivalent in Vue 3 is [`config.globalProperties`](/api/application-config.html#globalproperties). These properties will be copied across as part of instantiating a component within the application:
+O equivalente no Vue 3 é [`config.globalProperties`](/api/application-config.html#globalproperties). Essas propriedades serão copiadas como parte da instanciação de um componente dentro do aplicativo:
```js
-// before - Vue 2
+// antes - Vue 2
Vue.prototype.$http = () => {}
```
```js
-// after - Vue 3
+// depois - Vue 3
const app = createApp({})
app.config.globalProperties.$http = () => {}
```
-Using `provide` (discussed [below](#provide-inject)) should also be considered as an alternative to `globalProperties`.
+Usar `provide` (discutido [abaixo](#prover-injetar)) também deve ser considerado como uma alternativa para `globalProperties`.
-[Migration build flag: `GLOBAL_PROTOTYPE`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `GLOBAL_PROTOTYPE`](migration-build.html#configuracao-de-compatibilidade)
-### `Vue.extend` Removed
+### `Vue.extend` Removido
-In Vue 2.x, `Vue.extend` was used to create a "subclass" of the base Vue constructor with the argument that should be an object containing component options. In Vue 3.x, we don't have the concept of component constructors anymore. Mounting a component should always use the `createApp` global API:
+No Vue 2.x, `Vue.extend` era usado para criar uma "subclasse" do construtor Vue base com o argumento que deveria ser um objeto contendo opções de componente. No Vue 3.x, não temos mais o conceito de construtores de componente. A montagem de um componente deve sempre usar a API global `createApp`:
```js
-// before - Vue 2
+// antes - Vue 2
-// create constructor
+// cria construtor
const Profile = Vue.extend({
- template: '{{firstName}} {{lastName}} aka {{alias}}
',
+ template: '{{firstName}} {{lastName}} também conhecido como {{alias}}
',
data() {
return {
firstName: 'Walter',
@@ -159,14 +159,14 @@ const Profile = Vue.extend({
}
}
})
-// create an instance of Profile and mount it on an element
+// cria uma instância de Profile e monta em um elemento
new Profile().$mount('#mount-point')
```
```js
-// after - Vue 3
+// depois - Vue 3
const Profile = {
- template: '{{firstName}} {{lastName}} aka {{alias}}
',
+ template: '{{firstName}} {{lastName}} também conhecido como {{alias}}
',
data() {
return {
firstName: 'Walter',
@@ -179,21 +179,21 @@ const Profile = {
Vue.createApp(Profile).mount('#mount-point')
```
-#### Type Inference
+#### Inferência de Tipos
-In Vue 2, `Vue.extend` was also used for providing TypeScript type inference for the component options. In Vue 3, the `defineComponent` global API can be used in place of `Vue.extend` for the same purpose.
+No Vue 2, `Vue.extend` também era usado para fornecer a inferência de tipo do TypeScript para as opções do componente. No Vue 3, a API global `defineComponent` pode ser usada no lugar do `Vue.extend` para o mesmo propósito.
-Note that although the return type of `defineComponent` is a constructor-like type, it is only used for TSX inference. At runtime `defineComponent` is largely a noop and will return the options object as-is.
+Observe que, embora o tipo de retorno de `defineComponent` seja um tipo estilo construtor, ele é usado apenas para inferência do TSX. Em tempo de execução, o `defineComponent` é em grande parte um _noop_ e retornará o objeto de opções como está.
-#### Component Inheritance
+#### Herança de Componentes
-In Vue 3, we strongly recommend favoring composition via [Composition API](/api/composition-api.html) over inheritance and mixins. If for some reason you still need component inheritance, you can use the [`extends` option](/api/options-composition.html#extends) instead of `Vue.extend`.
+No Vue 3, é altamente recomendável favorecer a composição via [API de Composição](/api/composition-api.html) sobre herança e mixins. Se por algum motivo você ainda precisar de herança de componentes, você pode usar a [opção `extends`](/api/options-composition.html#extends) em vez de `Vue.extend`.
-[Migration build flag: `GLOBAL_EXTEND`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `GLOBAL_EXTEND`](migration-build.html#configuracao-de-compatibilidade)
-### A Note for Plugin Authors
+### Uma Nota para Autores de Plugins
-It is a common practice for plugin authors to install the plugins automatically in their UMD builds using `Vue.use`. For instance, this is how the official `vue-router` plugin installs itself in a browser environment:
+É uma prática comum para os autores de plugins instalarem os plugins automaticamente em suas compilações UMD usando `Vue.use`. Por exemplo, é assim que o plugin oficial `vue-router` se instala em um ambiente de navegador:
```js
var inBrowser = typeof window !== 'undefined'
@@ -203,16 +203,16 @@ if (inBrowser && window.Vue) {
}
```
-As the `use` global API is no longer available in Vue 3, this method will cease to work and calling `Vue.use()` will now trigger a warning. Instead, the end-user will now have to explicitly specify using the plugin on the app instance:
+Como a API global `use` não está mais disponível no Vue 3, este método deixará de funcionar e chamar `Vue.use()` agora acionará um aviso. Em vez disso, o usuário final terá que especificar explicitamente o uso do plugin na instância do aplicativo:
```js
const app = createApp(MyApp)
app.use(VueRouter)
```
-## Mounting App Instance
+## Montando a Instância do Aplicativo
-After being initialized with `createApp(/* options */)`, the app instance `app` can be used to mount a root component instance with `app.mount(domTarget)`:
+Após ser inicializado com `createApp(/* options */)`, a instância do aplicativo `app` pode ser usada para montar uma instância de componente raiz com `app.mount(domTarget)`:
```js
import { createApp } from 'vue'
@@ -222,7 +222,7 @@ const app = createApp(MyApp)
app.mount('#app')
```
-With all these changes, the component and directive we have at the beginning of the guide will be rewritten into something like this:
+Com todas essas mudanças, o componente e a diretiva que temos no início do guia serão reescritos em algo assim:
```js
const app = createApp(MyApp)
@@ -231,30 +231,30 @@ app.component('button-counter', {
data: () => ({
count: 0
}),
- template: 'Clicked {{ count }} times. '
+ template: 'Clicado {{ count }} vezes. '
})
app.directive('focus', {
mounted: el => el.focus()
})
-// now every application instance mounted with app.mount(), along with its
-// component tree, will have the same “button-counter” component
-// and “focus” directive without polluting the global environment
+// agora cada instância do aplicativo montada com app.mount(), junto com sua
+// árvore de componentes, terá o mesmo componente “button-counter”
+// e diretiva “focus” sem poluir o ambiente global
app.mount('#app')
```
-[Migration build flag: `GLOBAL_MOUNT`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `GLOBAL_MOUNT`](migration-build.html#configuracao-de-compatibilidade)
-## Provide / Inject
+## Prover / Injetar
-Similar to using the `provide` option in a 2.x root instance, a Vue 3 app instance can also provide dependencies that can be injected by any component inside the app:
+Semelhante ao uso da opção `provide` em uma instância raiz 2.x, uma instância de aplicativo Vue 3 também pode fornecer dependências que podem ser injetadas por qualquer componente dentro do aplicativo:
```js
-// in the entry
-app.provide('guide', 'Vue 3 Guide')
+// na entrada
+app.provide('guide', 'Guia do Vue 3')
-// in a child component
+// em um componente filho
export default {
inject: {
book: {
@@ -265,11 +265,11 @@ export default {
}
```
-Using `provide` is especially useful when writing a plugin, as an alternative to `globalProperties`.
+Usar `provide` é especialmente útil ao escrever um plugin, como uma alternativa para `globalProperties`.
-## Share Configurations Among Apps
+## Compartilhe Configurações Entre Aplicativos
-One way to share configurations e.g. components or directives among apps is to create a factory function, like this:
+Uma maneira de compartilhar configurações, como componentes ou diretivas entre apps é criar uma função fabricadora, assim:
```js
import { createApp } from 'vue'
@@ -287,4 +287,4 @@ createMyApp(Foo).mount('#foo')
createMyApp(Bar).mount('#bar')
```
-Now the `focus` directive will be available in both `Foo` and `Bar` instances and their descendants.
+Agora a diretiva `focus` estará disponível em ambas as instâncias `Foo` e `Bar` e seus descendentes.
diff --git a/src/guide/migration/inline-template-attribute.md b/src/guide/migration/inline-template-attribute.md
index 05cf6f126c..2c48ace791 100644
--- a/src/guide/migration/inline-template-attribute.md
+++ b/src/guide/migration/inline-template-attribute.md
@@ -3,38 +3,38 @@ badges:
- breaking
---
-# Inline Template Attribute
+# Atributo _Inline Template_
-## Overview
+## Visão Geral
-Support for the [inline-template feature](https://vuejs.org/v2/guide/components-edge-cases.html#Inline-Templates) has been removed.
+O suporte ao [recurso _inline-template_](https://br.vuejs.org/v2/guide/components-edge-cases.html#Templates-Inline) foi removido.
-## 2.x Syntax
+## Sintaxe v2.x
-In 2.x, Vue provided the `inline-template` attribute on child components to use its inner content as its template instead of treating it as distributed content.
+Na versão 2.x, o Vue disponibilizava o atributo `inline-template` em componentes filhos para usar seu conteúdo interno como _template_ ao invés de o tratar como conteúdo distribuído.
```html
-
These are compiled as the component's own template.
-
Not parent's transclusion content.
+
Estes são compilados como template do próprio componente.
+
Não como conteúdo da transclusão do componente pai.
```
-## 3.x Syntax
+## Sintaxe v3.x
-This feature will no longer be supported.
+Esta funcionalidade não receberá mais suporte.
-## Migration Strategy
+## Estratégia de Migração
-Most of the use cases for `inline-template` assumes a no-build-tool setup, where all templates are written directly inside the HTML page.
+A maioria dos casos de uso de `inline-template` assume um ambiente sem ferramentas de compilação, onde todos os _templates_ são escritos diretamente dentro da página HTML.
-[Migration build flag: `COMPILER_INLINE_TEMPLATE`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `COMPILER_INLINE_TEMPLATE`](migration-build.html#configuracao-de-compatibilidade)
-### Option #1: Use `
```
-And in the component, target the template using a selector:
+E no componente, aponte para o _template_ utilizando um seletor:
```js
const MyComp = {
@@ -51,34 +51,34 @@ const MyComp = {
}
```
-This doesn't require any build setup, works in all browsers, is not subject to any in-DOM HTML parsing caveats (e.g. you can use camelCase prop names), and provides proper syntax highlighting in most IDEs. In traditional server-side frameworks, these templates can be split out into server template partials (included into the main HTML template) for better maintainability.
+Isto não requer nenhuma configuração de compilação, funciona em todos os navegadores, não está sujeito a quaisquer limitações da análise de HTML no-DOM (ex.: você pode usar nomes de propriedades em camelCase) e fornece destaque de sintaxe na maioria das IDEs. Em frameworks tradicionais que trabalham no lado do servidor, estes _templates_ podem ser divididos em partes de _templates_ do servidor (incluídas no _template_ HTML principal) para uma melhor manutenção.
-### Option #2: Default Slot
+### Opção #2: _Slot_ _Default_
-A component previously using `inline-template` can also be refactored using the default slot - which makes the data scoping more explicit while preserving the convenience of writing child content inline:
+Um componente que anteriormente utilizava `inline-template` também pode ser refatorado utilizando o _slot_ _default_ - o que torna a definição do escopo de dados mais explícita enquanto preserva a conveniência de escrever o conteúdo filho _inline_:
```html
-
+
{{ msg }} {{ childState }}
-
+
{{ parentMsg }} {{ childState }}
```
-The child, instead of providing no template, should now render the default slot\*:
+O componente filho, ao invés de não fornecer nenhum _template_, agora deve renderizar o _slot_ _default_\*:
```html
```
-> - Note: In 3.x, slots can be rendered as the root with native [fragments](/guide/migration/fragments) support!
+> - Nota: na versão 3.x, _slots_ podem ser renderizados como raiz com suporte nativo a [fragmentos](/guide/migration/fragments)!
diff --git a/src/guide/migration/introduction.md b/src/guide/migration/introduction.md
index d86c317795..0243565f64 100644
--- a/src/guide/migration/introduction.md
+++ b/src/guide/migration/introduction.md
@@ -1,145 +1,144 @@
-# Introduction
+# Introdução
::: info
-New to Vue.js? Check out our [Essentials Guide](/guide/introduction.html) to get started.
+Novo no Vue.js? Veja nosso [Guia Essencial](/guide/introduction.html) para começar.
:::
-This guide is primarily for users with prior Vue 2 experience who want to learn about the new features and changes in Vue 3. **This is not something you have to read from top to bottom before trying out Vue 3.** While it looks like a lot has changed, a lot of what you know and love about Vue is still the same; but we wanted to be as thorough as possible and provide detailed explanations and examples for every documented change.
+Este guia é sobretudo para usuários com experiência prévia em Vue 2 que desejam aprender sobre os novos recursos e mudanças do Vue 3. **Este não é um artigo que você precise ler do começo ao fim antes de experimentar o Vue 3.** Embora pareça que muita coisa mudou, muito do que você conhece e ama no Vue ainda é o mesmo; mas queríamos ser tão minuciosos quanto possível fornecendo explicações detalhadas e exemplos para cada alteração documentada.
-- [Quickstart](#quickstart)
+- [Início rápido](#inicio-rapido)
- [Migration Build](#migration-build)
-- [Notable New Features](#notable-new-features)
-- [Breaking Changes](#breaking-changes)
-- [Supporting Libraries](#supporting-libraries)
+- [Principais recursos novos](#principais-recursos-novos)
+- [Incompatibilidades](#incompatibilidades)
+- [Bibliotecas suportadas](#bibliotecas-suportadas)
-## Overview
+## Visão Geral
-Start learning Vue 3 at [Vue Mastery](https://www.vuemastery.com/courses-path/vue3).
+Comece aprendendo Vue 3 com [Vue Mastery](https://www.vuemastery.com/courses-path/vue3).
-## Quickstart
+## Início Rápido
-If you want to quickly try out Vue 3 in a new project:
+Se você quiser testar rapidamente o Vue 3 em um novo projeto:
- Via CDN: ``
-- In-browser playground on [Codepen](https://codepen.io/yyx990803/pen/OJNoaZL)
-- In-browser Sandbox on [CodeSandbox](https://v3.vue.new)
-- Scaffold via [Vite](https://github.com/vitejs/vite):
+- Pelo navegador, via _playground_ em [Codepen](https://codepen.io/yyx990803/pen/OJNoaZL)
+- Pelo navegador, via Sandbox em [CodeSandbox](https://v3.vue.new)
+- Pré-estruturado, via [Vite](https://github.com/vitejs/vite):
```bash
- npm init vite hello-vue3 -- --template vue # OR yarn create vite hello-vue3 --template vue
- ```
+ npm init vite hello-vue3 -- --template vue # OU yarn create vite hello-vue3 --template vue
+ ```
-- Scaffold via [vue-cli](https://cli.vuejs.org/):
+- Pré-estruturado, via [vue-cli](https://cli.vuejs.org/):
```bash
- npm install -g @vue/cli # OR yarn global add @vue/cli
+ npm install -g @vue/cli # OU yarn global add @vue/cli
vue create hello-vue3
- # select vue 3 preset
+ # selecione a predefinição vue 3
```
-## Migration Build
+## Compilação de Migração
-If you have an existing Vue 2 project or library that you intend to upgrade to Vue 3, we provide a build of Vue 3 that offers Vue 2 compatible APIs. Check out the [Migration Build](./migration-build.html) page for more details.
+Se você tem um projeto ou biblioteca do Vue 2 existente que pretende atualizar para o Vue 3, fornecemos uma versão do Vue 3 que oferece APIs compatíveis com o Vue 2. Verifique a página [Compilação de Migração](./migration-build.html) para obter mais detalhes.
-## Notable New Features
+## Principais Recursos Novos
-Some of the new features to keep an eye on in Vue 3 include:
+Alguns dos recursos novos para ficar de olho no Vue 3 incluem:
-- [Composition API](/guide/composition-api-introduction.html)
-- [Teleport](/guide/teleport.html)
-- [Fragments](/guide/migration/fragments.html)
-- [Emits Component Option](/guide/component-custom-events.html)
-- [`createRenderer` API from `@vue/runtime-core`](https://github.com/vuejs/vue-next/tree/master/packages/runtime-core) to create custom renderers
-- [SFC Composition API Syntax Sugar (`
```
-## 3.x Syntax
+## Sintaxe v3.x
-In Vue 3's virtual DOM, event listeners are now just attributes, prefixed with `on`, and as such are part of the `$attrs` object, so `$listeners` has been removed.
+No DOM virtual do Vue 3, os escutadores de eventos agora são apenas atributos, prefixados com `on`, e como tal são parte do objeto `$attrs`, então `$listeners` foi removido.
```vue
@@ -52,25 +52,25 @@ export default {
```
-If this component received an `id` attribute and a `v-on:close` listener, the `$attrs` object will now look like this:
+Se este componente recebeu um atributo `id` e um escutador `v-on:close`, o objeto `$attrs` agora ficará assim:
```js
{
id: 'my-input',
- onClose: () => console.log('close Event triggered')
+ onClose: () => console.log('Evento close acionado')
}
```
-## Migration Strategy
+## Estratégia de Migração
-Remove all usages of `$listeners`.
+Remova todos os usos de `$listeners`.
-[Migration build flag: `INSTANCE_LISTENERS`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `INSTANCE_LISTENERS`](migration-build.html#configuracao-de-compatibilidade)
-## See also
+## Veja também
-- [Relevant RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0031-attr-fallthrough.md)
-- [Migration guide - `$attrs`includes `class` & `style` ](./attrs-includes-class-style.md)
-- [Migration guide - Changes in the Render Functions API](./render-function-api.md)
-- [Migration guide - New Emits Option](./emits-option.md)
-- [Migration guide - `.native` modifier removed](./v-on-native-modifier-removed.md)
+- [RFC relevante](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0031-attr-fallthrough.md)
+- [Guia de migração - `$attrs` inclui `class` & `style`](./attrs-includes-class-style.md)
+- [Guia de migração - Alterações na API de Funções de Renderização](./render-function-api.md)
+- [Guia de migração - Nova Opção Emits](./emits-option.md)
+- [Guia de migração - Modificador `.native` removido](./v-on-native-modifier-removed.md)
diff --git a/src/guide/migration/migration-build.md b/src/guide/migration/migration-build.md
index 54fe9edd11..6414817204 100644
--- a/src/guide/migration/migration-build.md
+++ b/src/guide/migration/migration-build.md
@@ -1,54 +1,54 @@
-# Migration Build
+# Compilação de Migração
-## Overview
+## Visão Geral
-`@vue/compat` (aka "the migration build") is a build of Vue 3 that provides configurable Vue 2 compatible behavior.
+`@vue/compat` (também conhecido como "a compilação de migração") é uma versão do Vue 3 que fornece um comportamento configurável compatível com Vue 2.
-The migration build runs in Vue 2 mode by default - most public APIs behave exactly like Vue 2, with only a few exceptions. Usage of features that have changed or been deprecated in Vue 3 will emit runtime warnings. A feature's compatibility can also be enabled/disabled on a per-component basis.
+A compilação de migração é executada no modo Vue 2 por padrão - a maioria das APIs públicas se comportam exatamente como no Vue 2, com apenas algumas exceções. O uso de recursos que foram alterados ou obsoletos no Vue 3 emitirá avisos em tempo de execução. A compatibilidade de um recurso também pode ser ativada/desativada por componente.
-### Intended Use Cases
+### Casos de Uso Pretendidos
-- Upgrading a Vue 2 application to Vue 3 (with [limitations](#known-limitations))
-- Migrating a library to support Vue 3
-- For experienced Vue 2 developers who have not tried Vue 3 yet, the migration build can be used in place of Vue 3 to help learn the difference between versions.
+- Atualizando um aplicativo Vue 2 para Vue 3 (com [limitações](#limitacoes-conhecidas))
+- Migrando uma biblioteca para suportar Vue 3
+- Para desenvolvedores experientes do Vue 2 que ainda não experimentaram o Vue 3, a compilação de migração pode ser usada no lugar do Vue 3 para ajudar a aprender a diferença entre as versões.
-### Known Limitations
+### Limitações Conhecidas
-While we've tried hard to make the migration build mimic Vue 2 behavior as much as possible, there are some limitations that may prevent your app from being eligible for upgrading:
+Embora tenhamos nos esforçado para fazer a compilação de migração imitar o comportamento do Vue 2 o máximo possível, existem algumas limitações que podem impedir que seu aplicativo seja qualificado para atualização:
-- Dependencies that rely on Vue 2 internal APIs or undocumented behavior. The most common case is usage of private properties on `VNodes`. If your project relies on component libraries like [Vuetify](https://vuetifyjs.com/en/), [Quasar](https://quasar.dev/) or [ElementUI](https://element.eleme.io/#/en-US), it is best to wait for their Vue 3 compatible versions.
+- Dependências que dependem de APIs internas do Vue 2 ou comportamento não documentado. O caso mais comum é o uso de propriedades privadas em `VNodes`. Se o seu projeto depende de bibliotecas de componentes como [Vuetify](https://vuetifyjs.com/en/), [Quasar](https://quasar.dev/) ou [ElementUI](https://element.eleme.io/#/en-US), é melhor esperar por suas versões compatíveis com Vue 3.
-- Internet Explorer 11 support: [Vue 3 has officially dropped the plan for IE11 support](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0038-vue3-ie11-support.md). If you still need to support IE11 or below, you will have to stay on Vue 2.
+- Suporte ao Internet Explorer 11: [O Vue 3 abandonou oficialmente o plano de suporte ao IE11](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0038-vue3-ie11-support.md). Se você ainda precisar dar suporte ao IE11 ou abaixo, terá que permanecer no Vue 2.
-- Server-side rendering: the migration build can be used for SSR, but migrating a custom SSR setup is much more involved. The general idea is replacing `vue-server-renderer` with [`@vue/server-renderer`](https://github.com/vuejs/vue-next/tree/master/packages/server-renderer). Vue 3 no longer provides a bundle renderer and it is recommended to use Vue 3 SSR with [Vite](https://vitejs.dev/guide/ssr.html). If you are using [Nuxt.js](https://nuxtjs.org/), you can try [Nuxt Bridge, a Nuxt.js 2 to 3 compatibility layer](https://v3.nuxtjs.org/getting-started/bridge/). For complex, production projects, it is probably best to wait for [Nuxt 3 (currently in beta)](https://v3.nuxtjs.org/getting-started/introduction).
+- Renderização do lado do servidor: a compilação de migração pode ser usada para SSR, mas a migração de uma configuração de SSR personalizada é muito mais complexa. A ideia geral é substituir `vue-server-renderer` por [`@vue/server-renderer`](https://github.com/vuejs/vue-next/tree/master/packages/server-renderer). O Vue 3 não fornece mais um renderizador de pacote (_bundle_) e é recomendado usar o Vue 3 SSR com [Vite](https://vitejs.dev/guide/ssr.html). Se estiver usando [Nuxt.js](https://nuxtjs.org/), você pode testar [Nuxt Bridge, uma camada de compatibilidade do Nuxt.js 2 para 3](https://v3.nuxtjs.org/getting-started/bridge/). Para projetos de produção complexos, provavelmente é melhor esperar pelo [Nuxt 3 (atualmente em beta)](https://v3.nuxtjs.org/getting-started/introduction).
-### Expectations
+### Expectativas
-Please note that the migration build aims to cover only publicly documented Vue 2 APIs and behavior. If your application fails to run under the migration build due to reliance on undocumented behavior, it is unlikely that we'll tweak the migration build to cater to your specific case. Consider refactoring to remove reliance on the behavior in question instead.
+Observe que a compilação de migração visa cobrir apenas as APIs e o comportamento do Vue 2 documentados publicamente. Se seu aplicativo não for executado na compilação de migração devido à dependência de comportamento não documentado, é improvável que ajustemos a compilação de migração para atender ao seu caso específico. Considere refatorar para remover a dependência do comportamento em questão.
-A word of caution: if your application is large and complex, migration will likely be a challenge even with the migration build. If your app is unfortunately not suitable for upgrade, do note that we are planning to backport Composition API and some other Vue 3 features to the 2.7 release (estimated late Q3 2021).
+Uma palavra de aviso: se seu aplicativo for grande e complexo, a migração provavelmente será um desafio mesmo com a compilação da migração. Se seu aplicativo infelizmente não for adequado para atualização, observe que estamos planejando fazer o _backport_ da API de composição e alguns outros recursos do Vue 3 para a v2.7 (estimada para o terceiro trimestre de 2021).
-If you do get your app running on the migration build, you **can** ship it to production before the migration is complete. Although there is a small performance/size overhead, it should not noticeably affect production UX. You may have to do so when you have dependencies that rely on Vue 2 behavior, and cannot be upgraded/replaced.
+Se você executar seu aplicativo na compilação de migração, **pode** enviá-lo para produção antes que a migração seja concluída. Embora haja uma pequena sobrecarga de desempenho/tamanho, ela não deve afetar visivelmente a UX de produção. Talvez você precise fazer isso quando tiver dependências que dependem do comportamento do Vue 2 e não podem ser atualizadas/substituídas.
-The migration build will be provided starting with 3.1, and will continue to be published alongside the 3.2 release line. We do plan to eventually stop publishing the migration build in a future minor version (no earlier than EOY 2021), so you should still aim to switch to the standard build before then.
+A compilação de migração será fornecida a partir da v3.1 e continuará a ser publicada junto com a linha de lançamento da v3.2. Planejamos eventualmente parar de publicar a compilação de migração em uma versão menor futura (não antes do fim de 2021), portanto, você ainda deve tentar mudar para a compilação padrão antes disso.
-## Upgrade Workflow
+## Fluxo de Trabalho da Atualização
-The following workflow walks through the steps of migrating an actual Vue 2 app (Vue HackerNews 2.0) to Vue 3. The full commits can be found [here](https://github.com/vuejs/vue-hackernews-2.0/compare/migration). Note that the actual steps required for your project may vary, and these steps should be treated as general guidance rather than strict instructions.
+O fluxo de trabalho a seguir percorre as etapas de migração de um aplicativo Vue 2 real (Vue HackerNews 2.0) para o Vue 3. Os commits completos podem ser encontrados [aqui](https://github.com/vuejs/vue-hackernews-2.0/compare/migration). Observe que as etapas reais necessárias para o seu projeto podem variar, e essas etapas devem ser tratadas como orientação geral em vez de instruções estritas.
-### Preparations
+### Preparações
-- If you are still using the [deprecated named / scoped slot syntax](https://vuejs.org/v2/guide/components-slots.html#Deprecated-Syntax), update it to the latest syntax first (which is already supported in 2.6).
+- Se você ainda estiver usando a [sintaxe obsoleta de slot nomeado/com escopo](https://br.vuejs.org/v2/guide/components-slots.html#Sintaxe-Obsoleta), atualize primeiro para a sintaxe mais recente (que já é suportada na 2.6).
-### Installation
+### Instalação
-1. Upgrade tooling if applicable.
+1. Atualize as ferramentas, se aplicável.
- - If using custom webpack setup: Upgrade `vue-loader` to `^16.0.0`.
- - If using `vue-cli`: upgrade to the latest `@vue/cli-service` with `vue upgrade`
- - (Alternative) migrate to [Vite](https://vitejs.dev/) + [vite-plugin-vue2](https://github.com/underfin/vite-plugin-vue2). [[Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/565b948919eb58f22a32afca7e321b490cb3b074)]
+ - Se estiver usando uma configuração de webpack personalizada: Atualize o `vue-loader` para `^16.0.0`.
+ - Se estiver usando `vue-cli`: atualize para o `@vue/cli-service` mais recente com `vue upgrade`
+ - (Alternativa) migrar para [Vite](https://vitejs.dev/) + [vite-plugin-vue2](https://github.com/underfin/vite-plugin-vue2). [[Commit de exemplo](https://github.com/vuejs/vue-hackernews-2.0/commit/565b948919eb58f22a32afca7e321b490cb3b074)]
-2. In `package.json`, update `vue` to 3.1, install `@vue/compat` of the same version, and replace `vue-template-compiler` (if present) with `@vue/compiler-sfc`:
+2. No `package.json`, atualize `vue` para 3.1, instale `@vue/compat` da mesma versão e substitua `vue-template-compiler` (se presente) por `@vue/compiler-sfc`:
```diff
"dependencies": {
@@ -63,11 +63,11 @@ The following workflow walks through the steps of migrating an actual Vue 2 app
}
```
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/14f6f1879b43f8610add60342661bf915f5c4b20)
+ [Commit de exemplo](https://github.com/vuejs/vue-hackernews-2.0/commit/14f6f1879b43f8610add60342661bf915f5c4b20)
-3. In the build setup, alias `vue` to `@vue/compat` and enable compat mode via Vue compiler options.
+3. Na configuração da compilação, crie o apelido `vue` para `@vue/compat` e habilite o modo de compatibilidade através das opções do compilador Vue.
- **Example Configs**
+ **Exemplos de Configurações**
vue-cli
@@ -98,7 +98,7 @@ The following workflow walks through the steps of migrating an actual Vue 2 app
- Plain webpack
+ Webpack puro
```js
// webpack.config.js
@@ -155,7 +155,7 @@ The following workflow walks through the steps of migrating an actual Vue 2 app
-4. If you are using TypeScript, you will also need to modify `vue`'s typing to expose the default export (which is no longer present in Vue 3) by adding a `*.d.ts` file with the following:
+4. Se você estiver usando TypeScript, também precisará modificar a tipagem do `vue` para expor a exportação padrão (que não está mais presente no Vue 3) adicionando um arquivo `*.d.ts` com o seguinte:
```ts
declare module 'vue' {
@@ -166,71 +166,71 @@ The following workflow walks through the steps of migrating an actual Vue 2 app
}
```
-5. At this point, your application may encounter some compile-time errors / warnings (e.g. use of filters). Fix them first. If all compiler warnings are gone, you can also set the compiler to Vue 3 mode.
+5. Neste ponto, seu aplicativo pode encontrar alguns erros/avisos em tempo de compilação (ex.: uso de filtros). Corrija-os primeiro. Se todos os avisos do compilador desaparecerem, você também poderá definir o compilador para o modo Vue 3.
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/b05d9555f6e115dea7016d7e5a1a80e8f825be52)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/b05d9555f6e115dea7016d7e5a1a80e8f825be52)
-6. After fixing the errors, the app should be able to run if it is not subject to the [limitations](#known-limitations) mentioned above.
+6. Depois de corrigir os erros, o aplicativo poderá ser executado se não estiver sujeito às [limitações](#limitacoes-conhecidas) mencionadas acima.
- You will likely see a LOT of warnings from both the command line and the browser console. Here are some general tips:
+ Você provavelmente verá MUITOS avisos na linha de comando e no console do navegador. Aqui estão algumas dicas gerais:
- - You can filter for specific warnings in the browser console. It's a good idea to use the filter and focus on fixing one item at a time. You can also use negated filters like `-GLOBAL_MOUNT`.
+ - Você pode filtrar por avisos específicos no console do navegador. É uma boa ideia usar o filtro e focar na correção de um item de cada vez. Você também pode usar filtros negados como `-GLOBAL_MOUNT`.
- - You can suppress specific deprecations via [compat configuration](#compat-configuration).
+ - Você pode suprimir itens obsoletos específicos por meio de [configuração de compatibilidade](#configuracao-de-compatibilidade).
- - Some warnings may be caused by a dependency that you use (e.g. `vue-router`). You can check this from the warning's component trace or stack trace (expanded on click). Focus on fixing the warnings that originate from your own source code first.
+ - Alguns avisos podem ser causados por uma dependência que você usa (ex.: `vue-router`). Você pode verificar isso no rastro do componente com aviso ou rastro da pilha de erros (expandido ao clicar). Concentre-se primeiro em corrigir os avisos originados de seu próprio código-fonte.
- - If you are using `vue-router`, note `` and `` will not work with `` until you upgrade to `vue-router` v4.
+ - Se você estiver usando `vue-router`, observe que `` e `` não funcionarão com `` até que você atualize para `vue-router` v4.
-7. Update [`` class names](/guide/migration/transition.html). This is the only feature that does not have a runtime warning. You can do a project-wide search for `.*-enter` and `.*-leave` CSS class names.
+7. Atualize [nomes de classe em ``](/guide/migration/transition.html). Este é o único recurso que não possui um aviso de tempo de execução. Você pode fazer uma pesquisa em todo o projeto para nomes de classes CSS `.*-enter` e `.*-leave`.
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/d300103ba622ae26ac26a82cd688e0f70b6c1d8f)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/d300103ba622ae26ac26a82cd688e0f70b6c1d8f)
-8. Update app entry to use [new global mounting API](/guide/migration/global-api.html#a-new-global-api-createapp).
+8. Atualize a entrada do aplicativo para usar a [nova API de montagem global](/guide/migration/global-api.html#uma-nova-api-global-createapp).
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/a6e0c9ac7b1f4131908a4b1e43641f608593f714)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/a6e0c9ac7b1f4131908a4b1e43641f608593f714)
-9. [Upgrade `vuex` to v4](https://next.vuex.vuejs.org/guide/migrating-to-4-0-from-3-x.html).
+9. [Atualize `vuex` para v4](https://vuex.vuejs.org/ptbr/guide/migrating-to-4-0-from-3-x.html).
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/5bfd4c61ee50f358cd5daebaa584f2c3f91e0205)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/5bfd4c61ee50f358cd5daebaa584f2c3f91e0205)
-10. [Upgrade `vue-router` to v4](https://next.router.vuejs.org/guide/migration/index.html). If you also use `vuex-router-sync`, you can replace it with a store getter.
+10. [Atualize o `vue-router` para v4](https://next.router.vuejs.org/guide/migration/index.html). Se você também usa `vuex-router-sync`, você pode substituí-lo por um _store getter_.
- After the upgrade, to use `` and `` with `` requires using the new [scoped-slot based syntax](https://next.router.vuejs.org/guide/migration/index.html#router-view-keep-alive-and-transition).
+ Após a atualização, para usar `` e `` com `` requer o uso da nova [sintaxe baseada em slot com escopo](https://next.router.vuejs.org/guide/migration/index.html#router-view-keep-alive-and-transition).
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/758961e73ac4089890079d4ce14996741cf9344b)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/758961e73ac4089890079d4ce14996741cf9344b)
-11. Pick off individual warnings. Note some features have conflicting behavior between Vue 2 and Vue 3 - for example, the render function API, or the functional component vs. async component change. To migrate to Vue 3 API without affecting the rest of the application, you can opt-in to Vue 3 behavior on a per-component basis with the [`compatConfig` option](#per-component-config).
+11. Retire os avisos individuais. Observe que alguns recursos têm comportamento conflitante entre o Vue 2 e o Vue 3 - por exemplo, a API da função de renderização ou o componente funcional vs. a alteração de componente assíncrona. Para migrar para a API do Vue 3 sem afetar o restante do aplicativo, você pode optar pelo comportamento do Vue 3 por componente com a [opção `compatConfig`](#configuracao-por-componente).
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/d0c7d3ae789be71b8fd56ce79cb4cb1f921f893b)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/d0c7d3ae789be71b8fd56ce79cb4cb1f921f893b)
-12. When all warnings are fixed, you can remove the migration build and switch to Vue 3 proper. Note you may not be able to do so if you still have dependencies that rely on Vue 2 behavior.
+12. Quando todos os avisos forem corrigidos, você poderá remover a compilação de migração e alternar para o Vue 3 propriamente dito. Observe que você pode não conseguir fazer isso se ainda tiver dependências que dependem do comportamento do Vue 2.
- [Example commit](https://github.com/vuejs/vue-hackernews-2.0/commit/9beb45490bc5f938c9e87b4ac1357cfb799565bd)
+ [Exemplo de commit](https://github.com/vuejs/vue-hackernews-2.0/commit/9beb45490bc5f938c9e87b4ac1357cfb799565bd)
-## Compat Configuration
+## Configuração de Compatibilidade
-### Global Config
+### Configuração Global
-Compat features can be disabled individually:
+Os recursos da compatibilidade podem ser desativados individualmente:
```js
import { configureCompat } from 'vue'
-// disable compat for certain features
+// desabilita a compatibilidade para certos recursos
configureCompat({
FEATURE_ID_A: false,
FEATURE_ID_B: false
})
```
-Alternatively, the entire application can default to Vue 3 behavior, with only certain compat features enabled:
+Alternativamente, todo o aplicativo pode padronizar o comportamento do Vue 3, com apenas alguns recursos de compatibilidade ativados:
```js
import { configureCompat } from 'vue'
-// default everything to Vue 3 behavior, and only enable compat
-// for certain features
+// padroniza tudo para o comportamento do Vue 3 e habilita compatibilidade apenas
+// para certos recursos
configureCompat({
MODE: 3,
FEATURE_ID_A: true,
@@ -238,105 +238,105 @@ configureCompat({
})
```
-### Per-Component Config
+### Configuração por Componente
-A component can use the `compatConfig` option, which expects the same options as the global `configureCompat` method:
+Um componente pode usar a opção `compatConfig`, que espera as mesmas opções que o método global `configureCompat`:
```js
export default {
compatConfig: {
- MODE: 3, // opt-in to Vue 3 behavior for this component only
- FEATURE_ID_A: true // features can also be toggled at component level
+ MODE: 3, // ativa o comportamento do Vue 3 apenas para este componente
+ FEATURE_ID_A: true // recursos também podem ser alternados no nível do componente
}
// ...
}
```
-### Compiler-specific Config
-
-Features that start with `COMPILER_` are compiler-specific: if you are using the full build (with in-browser compiler), they can be configured at runtime. However if using a build setup, they must be configured via the `compilerOptions` in the build config instead (see example configs above).
-
-## Feature Reference
-
-### Compatibility Types
-
-- ✔ Fully compatible
-- ◐ Partially Compatible with caveats
-- ⨂ Incompatible (warning only)
-- ⭘ Compat only (no warning)
-
-### Incompatible
-
-> Should be fixed upfront or will likely lead to errors
-
-| ID | Type | Description | Docs |
-| ------------------------------------- | ---- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
-| GLOBAL_MOUNT_CONTAINER | ⨂ | Mounted application does not replace the element it's mounted to | [link](/guide/migration/mount-changes.html) |
-| CONFIG_DEVTOOLS | ⨂ | production devtools is now a build-time flag | [link](https://github.com/vuejs/vue-next/tree/master/packages/vue#bundler-build-feature-flags) |
-| COMPILER_V_IF_V_FOR_PRECEDENCE | ⨂ | `v-if` and `v-for` precedence when used on the same element has changed | [link](/guide/migration/v-if-v-for.html) |
-| COMPILER_V_IF_SAME_KEY | ⨂ | `v-if` branches can no longer have the same key | [link](/guide/migration/key-attribute.html#on-conditional-branches) |
-| COMPILER_V_FOR_TEMPLATE_KEY_PLACEMENT | ⨂ | `` key should now be placed on `` | [link](/guide/migration/key-attribute.html#with-template-v-for) |
-| COMPILER_SFC_FUNCTIONAL | ⨂ | `` is no longer supported in SFCs | [link](/guide/migration/functional-components.html#single-file-components-sfcs) |
-
-### Partially Compatible with Caveats
-
-| ID | Type | Description | Docs |
-| ------------------------ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- |
-| CONFIG_IGNORED_ELEMENTS | ◐ | `config.ignoredElements` is now `config.compilerOptions.isCustomElement` (only in browser compiler build). If using build setup, `isCustomElement` must be passed via build configuration. | [link](/guide/migration/global-api.html#config-ignoredelements-is-now-config-compileroptions-iscustomelement) |
-| COMPILER_INLINE_TEMPLATE | ◐ | `inline-template` removed (compat only supported in browser compiler build) | [link](/guide/migration/inline-template-attribute.html) |
-| PROPS_DEFAULT_THIS | ◐ | props default factory no longer have access to `this` (in compat mode, `this` is not a real instance - it only exposes props, `$options` and injections) | [link](/guide/migration/props-default-this.html) |
-| INSTANCE_DESTROY | ◐ | `$destroy` instance method removed (in compat mode, only supported on root instance) | |
-| GLOBAL_PRIVATE_UTIL | ◐ | `Vue.util` is private and no longer available | |
-| CONFIG_PRODUCTION_TIP | ◐ | `config.productionTip` no longer necessary | [link](/guide/migration/global-api.html#config-productiontip-removed) |
-| CONFIG_SILENT | ◐ | `config.silent` removed | |
-
-### Compat only (no warning)
-
-| ID | Type | Description | Docs |
-| ------------------ | ---- | -------------------------------------- | ---------------------------------------- |
-| TRANSITION_CLASSES | ⭘ | Transition enter/leave classes changed | [link](/guide/migration/transition.html) |
-
-### Fully Compatible
-
-| ID | Type | Description | Docs |
-| ---------------------------- | ---- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
-| GLOBAL_MOUNT | ✔ | new Vue() -> createApp | [link](/guide/migration/global-api.html#mounting-app-instance) |
-| GLOBAL_EXTEND | ✔ | Vue.extend removed (use `defineComponent` or `extends` option) | [link](/guide/migration/global-api.html#vue-extend-removed) |
-| GLOBAL_PROTOTYPE | ✔ | `Vue.prototype` -> `app.config.globalProperties` | [link](/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties) |
-| GLOBAL_SET | ✔ | `Vue.set` removed (no longer needed) | |
-| GLOBAL_DELETE | ✔ | `Vue.delete` removed (no longer needed) | |
-| GLOBAL_OBSERVABLE | ✔ | `Vue.observable` removed (use `reactive`) | [link](/api/basic-reactivity.html) |
-| CONFIG_KEY_CODES | ✔ | config.keyCodes removed | [link](/guide/migration/keycode-modifiers.html) |
-| CONFIG_WHITESPACE | ✔ | In Vue 3 whitespace defaults to `"condense"` | |
-| INSTANCE_SET | ✔ | `vm.$set` removed (no longer needed) | |
-| INSTANCE_DELETE | ✔ | `vm.$delete` removed (no longer needed) | |
-| INSTANCE_EVENT_EMITTER | ✔ | `vm.$on`, `vm.$off`, `vm.$once` removed | [link](/guide/migration/events-api.html) |
-| INSTANCE_EVENT_HOOKS | ✔ | Instance no longer emits `hook:x` events | [link](/guide/migration/vnode-lifecycle-events.html) |
-| INSTANCE_CHILDREN | ✔ | `vm.$children` removed | [link](/guide/migration/children.html) |
-| INSTANCE_LISTENERS | ✔ | `vm.$listeners` removed | [link](/guide/migration/listeners-removed.html) |
-| INSTANCE_SCOPED_SLOTS | ✔ | `vm.$scopedSlots` removed; `vm.$slots` now exposes functions | [link](/guide/migration/slots-unification.html) |
-| INSTANCE_ATTRS_CLASS_STYLE | ✔ | `$attrs` now includes `class` and `style` | [link](/guide/migration/attrs-includes-class-style.html) |
-| OPTIONS_DATA_FN | ✔ | `data` must be a function in all cases | [link](/guide/migration/data-option.html) |
-| OPTIONS_DATA_MERGE | ✔ | `data` from mixin or extension is now shallow merged | [link](/guide/migration/data-option.html) |
-| OPTIONS_BEFORE_DESTROY | ✔ | `beforeDestroy` -> `beforeUnmount` | |
-| OPTIONS_DESTROYED | ✔ | `destroyed` -> `unmounted` | |
-| WATCH_ARRAY | ✔ | watching an array no longer triggers on mutation unless deep | [link](/guide/migration/watch.html) |
-| V_FOR_REF | ✔ | `ref` inside `v-for` no longer registers array of refs | [link](/guide/migration/array-refs.html) |
-| V_ON_KEYCODE_MODIFIER | ✔ | `v-on` no longer supports keyCode modifiers | [link](/guide/migration/keycode-modifiers.html) |
-| CUSTOM_DIR | ✔ | Custom directive hook names changed | [link](/guide/migration/custom-directives.html) |
-| ATTR_FALSE_VALUE | ✔ | No longer removes attribute if binding value is boolean `false` | [link](/guide/migration/attribute-coercion.html) |
-| ATTR_ENUMERATED_COERCION | ✔ | No longer special case enumerated attributes | [link](/guide/migration/attribute-coercion.html) |
-| TRANSITION_GROUP_ROOT | ✔ | `` no longer renders a root element by default | [link](/guide/migration/transition-group.html) |
-| COMPONENT_ASYNC | ✔ | Async component API changed (now requires `defineAsyncComponent`) | [link](/guide/migration/async-components.html) |
-| COMPONENT_FUNCTIONAL | ✔ | Functional component API changed (now must be plain functions) | [link](/guide/migration/functional-components.html) |
-| COMPONENT_V_MODEL | ✔ | Component v-model reworked | [link](/guide/migration/v-model.html) |
-| RENDER_FUNCTION | ✔ | Render function API changed | [link](/guide/migration/render-function-api.html) |
-| FILTERS | ✔ | Filters removed (this option affects only runtime filter APIs) | [link](/guide/migration/filters.html) |
-| COMPILER_IS_ON_ELEMENT | ✔ | `is` usage is now restricted to `` only | [link](/guide/migration/custom-elements-interop.html) |
-| COMPILER_V_BIND_SYNC | ✔ | `v-bind.sync` replaced by `v-model` with arguments | [link](/guide/migration/v-model.html) |
-| COMPILER_V_BIND_PROP | ✔ | `v-bind.prop` modifier removed | |
-| COMPILER_V_BIND_OBJECT_ORDER | ✔ | `v-bind="object"` is now order sensitive | [link](/guide/migration/v-bind.html) |
-| COMPILER_V_ON_NATIVE | ✔ | `v-on.native` modifier removed | [link](/guide/migration/v-on-native-modifier-removed.html) |
-| COMPILER_V_FOR_REF | ✔ | `ref` in `v-for` (compiler support) | |
-| COMPILER_NATIVE_TEMPLATE | ✔ | `` with no special directives now renders as native element | |
-| COMPILER_FILTERS | ✔ | filters (compiler support) | |
+### Configuração Específica de Compilador
+
+Os recursos que começam com `COMPILER_` são específicos do compilador: se você estiver usando a compilação completa (com compilador _in-browser_), eles podem ser configurados em tempo de execução. No entanto, se estiver usando um ambiente de compilação, eles devem ser configurados por meio de `compilerOptions` na configuração de compilação (veja as configurações de exemplo acima).
+
+## Referência de Recurso
+
+### Tipos de Compatibilidade
+
+- ✔ Totalmente compatível
+- ◐ Parcialmente compatível com ressalvas
+- ⨂ Incompatível (somente aviso)
+- ⭘ Somente modo de compatibilidade (sem aviso)
+
+### Incompatível
+
+> Deve ser corrigido antecipadamente ou provavelmente levará a erros
+
+| ID | Tipo | Descrição | Documentação |
+| ------------------------------------- | ---- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
+| GLOBAL_MOUNT_CONTAINER | ⨂ | O aplicativo montado não substitui o elemento no qual está montado | [link](/guide/migration/mount-changes.html) |
+| CONFIG_DEVTOOLS | ⨂ | devtools de produção agora é um sinalizador em tempo de compilação | [link](https://github.com/vuejs/vue-next/tree/master/packages/vue#bundler-build-feature-flags) |
+| COMPILER_V_IF_V_FOR_PRECEDENCE | ⨂ | A precedência `v-if` e `v-for` quando usada no mesmo elemento foi alterada | [link](/guide/migration/v-if-v-for.html) |
+| COMPILER_V_IF_SAME_KEY | ⨂ | Ramos `v-if` não podem mais ter a mesma chave | [link](/guide/migration/key-attribute.html#em-branches-condicionais) |
+| COMPILER_V_FOR_TEMPLATE_KEY_PLACEMENT | ⨂ | A chave de `` agora deve ser colocada no `` | [link](/guide/migration/key-attribute.html#com-template-v-for) |
+| COMPILER_SFC_FUNCTIONAL | ⨂ | `` não é mais suportado em SFCs | [link](/guide/migration/functional-components.html#componentes-single-file-sfcs) |
+
+### Parcialmente Compatível com Ressalvas
+
+| ID | Tipo | Descrição | Documentação |
+| ------------------------ | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
+| CONFIG_IGNORED_ELEMENTS | ◐ | `config.ignoredElements` agora é `config.compilerOptions.isCustomElement` (somente na versão do compilador _in-browser_). Se estiver usando ambiente de compilação, `isCustomElement` deve ser passado na configuração da compilação. | [link](/guide/migration/global-api.html#config-ignoredelements-agora-e-config-compileroptions-iscustomelement) |
+| COMPILER_INLINE_TEMPLATE | ◐ | `inline-template` removido (compatibilidade suportada apenas na compilação _in-browser_) | [link](/guide/migration/inline-template-attribute.html) |
+| PROPS_DEFAULT_THIS | ◐ | Função-fábrica padrão de props não tem mais acesso a `this` (no modo de compatibilidade, `this` não é uma instância real - apenas expõe props, `$options` e injeções) | [link](/guide/migration/props-default-this.html) |
+| INSTANCE_DESTROY | ◐ | Método de instância `$destroy` removido (no modo de compatibilidade, suportado apenas na instância raiz) | |
+| GLOBAL_PRIVATE_UTIL | ◐ | `Vue.util` é privado e não está mais disponível | |
+| CONFIG_PRODUCTION_TIP | ◐ | `config.productionTip` não é mais necessário | [link](/guide/migration/global-api.html#config-productiontip-removido) |
+| CONFIG_SILENT | ◐ | `config.silent` removido | |
+
+### Somente Modo de Compatibilidade (sem aviso)
+
+| ID | Tipo | Descrição | Documentação |
+| ------------------ | ---- | ----------------------------------------------- | ---------------------------------------- |
+| TRANSITION_CLASSES | ⭘ | Classes de entrada/saída da transição alteradas | [link](/guide/migration/transition.html) |
+
+### Totalmente Compatível
+
+| ID | Tipo | Descrição | Documentação |
+| ------------------------------------- | ---- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
+| GLOBAL_MOUNT | ✔ | new Vue() -> createApp | [link](/guide/migration/global-api.html#montando-a-instancia-do-aplicativo) |
+| GLOBAL_EXTEND | ✔ | Vue.extend removido (use a opção `defineComponent` ou `extends`) | [link](/guide/migration/global-api.html#vue-extend-removido) |
+| GLOBAL_PROTOTYPE | ✔ | `Vue.prototype` -> `app.config.globalProperties` | [link](/guide/migration/global-api.html#vue-prototype-substituido-por-config-globalproperties) |
+| GLOBAL_SET | ✔ | `Vue.set` removido (não é mais necessário) | |
+| GLOBAL_DELETE | ✔ | `Vue.delete` removido (não é mais necessário) | |
+| GLOBAL_OBSERVÁVEL | ✔ | `Vue.observable` removido (use `reactive`) | [link](/api/basic-reactivity.html) |
+| CONFIG_KEY_CODES | ✔ | config.keyCodes removidos | [link](/guide/migration/keycode-modifiers.html) |
+| CONFIG_WHITESPACE | ✔ | No Vue 3, o espaço em branco padrão é `"condense"` | |
+| INSTANCE_SET | ✔ | `vm.$set` removido (não é mais necessário) | |
+| INSTANCE_DELETE | ✔ | `vm.$delete` removido (não é mais necessário) | |
+| INSTANCE_EVENT_EMITTER | ✔ | `vm.$on`, `vm.$off`, `vm.$once` removido | [link](/guide/migration/events-api.html) |
+| INSTANCE_EVENT_HOOKS | ✔ | A instância não emite mais eventos `hook:x` | [link](/guide/migration/vnode-lifecycle-events.html) |
+| INSTANCE_CHILDREN | ✔ | `vm.$children` removido | [link](/guide/migration/children.html) |
+| INSTANCE_LISTENERS | ✔ | `vm.$listeners` removido | [link](/guide/migration/listeners-removed.html) |
+| INSTANCE_SCOPED_SLOTS | ✔ | `vm.$scopedSlots` removido; `vm.$slots` agora expõe funções | [link](/guide/migration/slots-unification.html) |
+| INSTANCE_ATTRS_CLASS_STYLE | ✔ | `$attrs` agora inclui `class` e `style` | [link](/guide/migration/attrs-includes-class-style.html) |
+| OPTIONS_DATA_FN | ✔ | `data` deve ser uma função em todos os casos | [link](/guide/migration/data-option.html) |
+| OPTIONS_DATA_MERGE | ✔ | `data` do mixin ou extensão agora é mesclado superficialmente | [link](/guide/migration/data-option.html) |
+| OPTIONS_BEFORE_DESTROY | ✔ | `beforeDestroy` -> `beforeUnmount` | |
+| OPTIONS_DESTROYED | ✔ | `destroyed` -> `unmounted` | |
+| WATCH_ARRAY | ✔ | Observar um array não dispara mais na mutação, a menos que seja profundo | [link](/guide/migration/watch.html) |
+| V_FOR_REF | ✔ | `ref` dentro de `v-for` não registra mais array de refs | [link](/guide/migration/array-refs.html) |
+| V_ON_KEYCODE_MODIFIER | ✔ | `v-on` não suporta mais modificadores keyCode | [link](/guide/migration/keycode-modifiers.html) |
+| CUSTOM_DIR | ✔ | Nomes de gatilhos de diretiva personalizada alterados | [link](/guide/migration/custom-directives.html) |
+| ATTR_FALSE_VALUE | ✔ | Não remove mais o atributo se o valor do vínculo for booleano `false` | [link](/guide/migration/attribute-coercion.html) |
+| ATTR_ENUMERATED_COERCION | ✔ | Caso especial de atributos enumerados não funciona mais | [link](/guide/migration/attribute-coercion.html) |
+| TRANSITION_GROUP_ROOT | ✔ | `` não renderiza mais um elemento raiz por padrão | [link](/guide/migration/transition-group.html) |
+| COMPONENT_ASYNC | ✔ | API do componente assíncrono alterada (agora requer `defineAsyncComponent`) | [link](/guide/migration/async-components.html) |
+| COMPONENT_FUNCTIONAL | ✔ | API de componente funcional alterada (agora devem ser funções simples) | [link](/guide/migration/functional-components.html) |
+| COMPONENT_V_MODEL | ✔ | Componente `v-model` retrabalhado | [link](/guide/migration/v-model.html) |
+| RENDER_FUNCTION | ✔ | API da função de renderização alterada | [link](/guide/migration/render-function-api.html) |
+| FILTROS | ✔ | Filtros removidos (afeta apenas APIs de filtro em tempo de execução) | [link](/guide/migration/filters.html) |
+| COMPILER_IS_ON_ELEMENT | ✔ | O uso de `is` agora está restrito apenas a `` | [link](/guide/migration/custom-elements-interop.html) |
+| COMPILER_V_BIND_SYNC | ✔ | `v-bind.sync` substituído por `v-model` com argumentos | [link](/guide/migration/v-model.html) |
+| COMPILER_V_BIND_PROP | ✔ | Modificador `v-bind.prop` removido | |
+| COMPILER_V_BIND_OBJECT_ORDER | ✔ | `v-bind="object"` agora é sensível à ordem | [link](/guide/migration/v-bind.html) |
+| COMPILER_V_ON_NATIVE | ✔ | Modificador `v-on.native` removido | [link](/guide/migration/v-on-native-modifier-removed.html) |
+| COMPILER_V_FOR_REF | ✔ | `ref` em `v-for` (suporte no compilador) | |
+| COMPILER_NATIVE_TEMPLATE | ✔ | `` sem diretivas especiais agora renderiza como elemento nativo | |
+| COMPILER_FILTERS | ✔ | Filtros (suporte no compilador) | |
diff --git a/src/guide/migration/mount-changes.md b/src/guide/migration/mount-changes.md
index b762bb4a14..f612e3a556 100644
--- a/src/guide/migration/mount-changes.md
+++ b/src/guide/migration/mount-changes.md
@@ -1,25 +1,25 @@
---
-title: 'Mount API changes'
+title: 'Alterações na API de Montagem'
badges:
- breaking
---
-# Mounted application does not replace the element
+# O aplicativo montado não substitui o elemento
-## Overview
+## Visão Geral
-In Vue 2.x, when mounting an application that has a `template`, the rendered content replaces the element we mount to. In Vue 3.x, the rendered application is appended as a child of such an element, replacing element's `innerHTML`.
+No Vue 2.x, ao montar uma aplicação que tem um `template`, o conteúdo renderizado substitui o elemento em que montamos. No Vue 3.x, o aplicativo renderizado é anexado como filho de tal elemento, substituindo o `innerHTML` do elemento.
-## 2.x Syntax
+## Sintaxe v2.x
-In Vue 2.x, we pass an HTML element selector to `new Vue()` or `$mount`:
+No Vue 2.x, passamos um seletor de elemento HTML para `new Vue()` ou `$mount`:
```js
new Vue({
el: '#app',
data() {
return {
- message: 'Hello Vue!'
+ message: 'Olá Vue!'
}
},
template: `
@@ -27,11 +27,11 @@ new Vue({
`
})
-// or
+// ou
const app = new Vue({
data() {
return {
- message: 'Hello Vue!'
+ message: 'Olá Vue!'
}
},
template: `
@@ -42,33 +42,33 @@ const app = new Vue({
app.$mount('#app')
```
-When we mount this application to the page that has a `div` with the passed selector (in our case, it's `id="app"`):
+Quando montamos esta aplicação na página que tem um `div` com o seletor passado (no nosso caso, é `id="app"`):
```html
- Some app content
+ Algum conteúdo de aplicativo
```
-in the rendered result, the mentioned `div` will be replaced with the rendered application content:
+no resultado renderizado, o `div` mencionado será substituído pelo conteúdo do aplicativo renderizado:
```html
- Hello Vue!
+ Olá Vue!
```
-## 3.x Syntax
+## Sintaxe v3.x
-In Vue 3.x, when we mount an application, its rendered content will replace the `innerHTML` of the element we pass to `mount`:
+No Vue 3.x, quando montamos uma aplicação, seu conteúdo renderizado substituirá o `innerHTML` do elemento que passamos para `mount`:
```js
const app = Vue.createApp({
data() {
return {
- message: 'Hello Vue!'
+ message: 'Olá Vue!'
}
},
template: `
@@ -79,20 +79,20 @@ const app = Vue.createApp({
app.mount('#app')
```
-When this app is mounted to the page that has a `div` with `id="app"`, this will result in:
+Quando este aplicativo é montado na página que tem um `div` com `id="app"`, isso resultará em:
```html
```
-## Migration Strategy
+## Estratégia de Migração
-[Migration build flag: `GLOBAL_MOUNT_CONTAINER`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `GLOBAL_MOUNT_CONTAINER`](migration-build.html#configuracao-de-compatibilidade)
-## See Also
+## Veja também
-- [`mount` API](/api/application-api.html#mount)
+- [API `mount`](/api/application-api.html#mount)
diff --git a/src/guide/migration/props-data.md b/src/guide/migration/props-data.md
index 8c12d3ff0a..bb603dcb7e 100644
--- a/src/guide/migration/props-data.md
+++ b/src/guide/migration/props-data.md
@@ -5,13 +5,13 @@ badges:
# `propsData`
-## Overview
+## Visão Geral
-The `propsData` option, used to pass props to the Vue instance during its creation, is removed. To pass props to the root component of a Vue 3 application, use the second argument of [createApp](/api/global-api.html#createapp).
+A opção `propsData`, usada para passar props para a instância Vue durante sua criação, foi removida. Para passar props para o componente raiz de um aplicativo Vue 3, use o segundo argumento de [createApp](/api/global-api.html#createapp).
-## 2.x Syntax
+## Sintaxe v2.x
-In 2.x, we were able to pass props to a Vue instance during its creation:
+Na versão 2.x, conseguíamos passar props para uma instância do Vue durante sua criação:
```js
const Comp = Vue.extend({
@@ -26,9 +26,9 @@ new Comp({
})
```
-## 3.x Update
+## Atualização 3.x
-The `propsData` option has been removed. If you need to pass props to the root component instance during its creation, you should use the second argument of `createApp`:
+A opção `propsData` foi removida. Se você precisar passar props para a instância do componente raiz durante sua criação, você deve usar o segundo argumento de `createApp`:
```js
const app = createApp(
diff --git a/src/guide/migration/props-default-this.md b/src/guide/migration/props-default-this.md
index fd4485d93f..7db0a2fc4c 100644
--- a/src/guide/migration/props-default-this.md
+++ b/src/guide/migration/props-default-this.md
@@ -1,18 +1,18 @@
---
-title: Props Default Function this Access
+title: Acesso ao this na Função Padrão de Props
badges:
- breaking
---
-# Props Default Function `this` Access
+# Acesso ao `this` na Função Padrão de Props
-Props default value factory functions no longer have access to `this`.
+As funções fabricadoras de valores padrão de `props` não têm mais acesso à `this`.
-Instead:
+Ao invés disso:
-- Raw props received by the component are passed to the default function as argument;
+- `props` brutas recebidas pelo componente são passadas para as funções padrão como argumento;
-- The [inject](../composition-api-provide-inject.md) API can be used inside default functions.
+- A API de [injeção](../composition-api-provide-inject.md) pode ser utilizada dentro de funções padrão.
```js
import { inject } from 'vue'
@@ -21,9 +21,9 @@ export default {
props: {
theme: {
default (props) {
- // `props` is the raw values passed to the component,
- // before any type / default coercions
- // can also use `inject` to access injected properties
+ // `props` são os valores brutos passados para o componente,
+ // antes de qualquer tipo / coerção padrão.
+ // Também pode ser utilizado `inject` para acessar propriedades injetadas
return inject('theme', 'default-theme')
}
}
@@ -31,6 +31,6 @@ export default {
}
```
-## Migration Strategy
+## Estratégia de Migração
-[Migration build flag: `PROPS_DEFAULT_THIS`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `PROPS_DEFAULT_THIS`](migration-build.html#configuracao-de-compatibilidade)
diff --git a/src/guide/migration/render-function-api.md b/src/guide/migration/render-function-api.md
index bc6ade66c2..0405d12b79 100644
--- a/src/guide/migration/render-function-api.md
+++ b/src/guide/migration/render-function-api.md
@@ -3,28 +3,28 @@ badges:
- breaking
---
-# Render Function API
+# API da Função de Renderização
-## Overview
+## Visão Geral
-This change will not affect `` users.
+Esta mudança não vai afetar usuários de ``.
-Here is a quick summary of what has changed:
+Aqui está um rápido resumo do que mudou:
-- `h` is now globally imported instead of passed to render functions as an argument
-- render function arguments changed to be more consistent between stateful and functional components
-- VNodes now have a flat props structure
+- `h` agora é globalmente importado em vez de passado como argumento para funções de renderização
+- Argumentos da função de renderização mudaram para serem mais consistentes entre componentes funcionais e com estado
+- VNodes agora têm uma estrutura plana de props
-For more information, read on!
+Para mais informações, continue lendo!
-## Render Function Argument
+## Argumento da Função de Renderização
-### 2.x Syntax
+### Sintaxe v2.x
-In 2.x, the `render` function would automatically receive the `h` function (which is a conventional alias for `createElement`) as an argument:
+Na v2.x, a função `render` receberia automaticamente a função `h` (que é um _alias_ para `createElement`) como argumento:
```js
-// Vue 2 Render Function Example
+// Exemplo da Função de Renderização no Vue 2
export default {
render(h) {
return h('div')
@@ -32,12 +32,12 @@ export default {
}
```
-### 3.x Syntax
+### Sintaxe v3.x
-In 3.x, `h` is now globally imported instead of being automatically passed as an argument.
+Na v3.x, o `h` agora é importado globalmente em vez de automaticamente passado como um argumento.
```js
-// Vue 3 Render Function Example
+// Exemplo da Função de Renderização no Vue 3
import { h } from 'vue'
export default {
@@ -47,14 +47,14 @@ export default {
}
```
-## Render Function Signature Change
+## Mudança da Assinatura da Função de Renderização
-### 2.x Syntax
+### Sintaxe v2.x
-In 2.x, the `render` function automatically received arguments such as `h`.
+Na v2.x, a função `render` recebeu automaticamente argumentos como o `h`.
```js
-// Vue 2 Render Function Example
+// Exemplo da Função Render no Vue 2
export default {
render(h) {
return h('div')
@@ -62,9 +62,9 @@ export default {
}
```
-### 3.x Syntax
+### Sintaxe v3.x
-In 3.x, since the `render` function no longer receives any arguments, it will primarily be used inside of the `setup()` function. This has the added benefit of gaining access to reactive state and functions declared in scope, as well as the arguments passed to `setup()`.
+Na v3.x, desde que a função `render` já não recebe argumentos, ela será primeiramente usada dentro da função `setup()`. Isso traz o benefício adicional em ganhar acesso ao estado reativo e às funções declaradas no escopo, assim como argumentos passados para o `setup()`.
```js
import { h, reactive } from 'vue'
@@ -79,7 +79,7 @@ export default {
state.count++
}
- // return the render function
+ // retorna a função de renderização
return () =>
h(
'div',
@@ -92,16 +92,16 @@ export default {
}
```
-For more information on how `setup()` works, see our [Composition API Guide](/guide/composition-api-introduction.html).
+Para mais informações em como o `setup()` funciona, veja nosso [Guia da API de Composição](/guide/composition-api-introduction.html).
-## VNode Props Format
+## Formato de Props VNode
-### 2.x Syntax
+### Sintaxe v2.x
-In 2.x, `domProps` contained a nested list within the VNode props:
+Na v2.x, o `domProps` continha uma lista aninhada dentro dos props VNode:
```js
-// 2.x
+// v2.x
{
staticClass: 'button',
class: {'is-outlined': isOutlined },
@@ -114,12 +114,12 @@ In 2.x, `domProps` contained a nested list within the VNode props:
}
```
-### 3.x Syntax
+### Sintaxe v3.x
-In 3.x, the entire VNode props structure is flattened. Using the example from above, here is what it would look like now.
+Na v3.x, toda a estrutura de props do VNode é achatada. Usando o exemplo acima, agora ele ficaria algo assim.
```js
-// 3.x Syntax
+// Sintaxe v3.x
{
class: ['button', { 'is-outlined': isOutlined }],
style: [{ color: '#34495E' }, { backgroundColor: buttonColor }],
@@ -130,11 +130,11 @@ In 3.x, the entire VNode props structure is flattened. Using the example from ab
}
```
-## Registered Component
+## Componente Registrado
-### 2.x Syntax
+### Sintaxe v2.x
-In 2.x, when a component has been registered, the render function would work well when passing the component's name as a string to the first argument:
+Na v2.x, quando um componente é registrado, a função de renderização funcionaria bem quando passado o nome do componente como uma string para o primeiro argumento:
```js
// 2.x
@@ -146,7 +146,7 @@ Vue.component('button-counter', {
}
template: `
- Clicked {{ count }} times.
+ Clicado {{ count }} vezes.
`
})
@@ -158,12 +158,12 @@ export default {
}
```
-### 3.x Syntax
+### Sintaxe v3.x
-In 3.x, with VNodes being context-free, we can no longer use a string ID to implicitly lookup registered components. Instead, we need to use an imported `resolveComponent` method:
+Na v3.x, com os VNodes sendo livres de contexto, não podemos usar um ID como string para implicitamente buscar por componentes registrados. Em vez disso, precisamos usar o método importado `resolveComponent`:
```js
-// 3.x
+// v3.x
import { h, resolveComponent } from 'vue'
export default {
@@ -174,20 +174,22 @@ export default {
}
```
-For more information, see [The Render Function Api Change RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0008-render-function-api-change.md#context-free-vnodes).
+Para mais informações, veja [O RFC* das mudanças da API da Função de Renderização](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0008-render-function-api-change.md#context-free-vnodes).
+
+* **Nota da tradução**: RFC significa _Request For Comments_ (Solicitação de Comentários), e é um processo que visa prover um caminho consistente e controlado para as novas funcionalidades de um framework.
-## Migration Strategy
+## Estratégia de Migração
-[Migration build flag: `RENDER_FUNCTION`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `RENDER_FUNCTION`](migration-build.html#configuracao-de-compatibilidade)
-### Library Authors
+### Autores de Biblioteca
-`h` being globally imported means that any library that contains Vue components will include `import { h } from 'vue'` somewhere. As a result, this creates a bit of overhead since it requires library authors to properly configure the externalization of Vue in their build setup:
+A importação global do `h` significa que qualquer biblioteca que contenha componentes Vue vão incluir `import { h } from 'vue'` em algum lugar. Como resultado, isso cria um pouco de sobrecarga, pois requer que os autores de biblioteca configurem corretamente a externalização do Vue em suas configurações de compilação:
-- Vue should not be bundled into the library
-- For module builds, the import should be left alone and be handled by the end user bundler
-- For UMD / browser builds, it should try the global Vue.h first and fallback to require calls
+- o Vue não deve estar empacotado na biblioteca
+- Para construções de módulo, a importação deve ser deixada sozinha e tratada pelo empacotador do usuário final
+- Para UMD / compilações de navegador, deve-se tentar o Vue.h global primeiro e alternar para exigir chamadas se necessário
-## Next Steps
+## Próximos Passos
-See [Render Function Guide](/guide/render-function) for more detailed documentation!
+Veja [O Guia da Função de Renderização](/guide/render-function) para documentação mais detalhada!
diff --git a/src/guide/migration/slots-unification.md b/src/guide/migration/slots-unification.md
index dabeb034ed..c77067e09c 100644
--- a/src/guide/migration/slots-unification.md
+++ b/src/guide/migration/slots-unification.md
@@ -3,65 +3,65 @@ badges:
- breaking
---
-# Slots Unification
+# Unificação de Slots
-## Overview
+## Visão Geral
-This change unifies normal and scoped slots in 3.x.
+Esta modificação unifica _slots_ normais e _slots_ com escopo na v3.x.
-Here is a quick summary of what has changed:
+Aqui um pequeno sumário sobre o que mudou:
-- `this.$slots` now exposes slots as functions
-- **BREAKING**: `this.$scopedSlots` is removed
+- `this.$slots` agora exibe os _slots_ como funções
+- **QUEBRA**: `this.$scopedSlots` foi removido
-For more information, read on!
+Para mais informações, continue lendo!
-## 2.x Syntax
+## Sintaxe v2.x
-When using the render function, i.e., `h`, 2.x used to define the `slot` data property on the content nodes.
+Ao utilizar uma função de renderização, como `h`, a v2.x definia a propriedade `slot` nos nós do conteúdo.
```js
-// 2.x Syntax
+// Sintaxe v2.x
h(LayoutComponent, [
h('div', { slot: 'header' }, this.header),
h('div', { slot: 'content' }, this.content)
])
```
-In addition, when referencing scoped slots, they could be referenced using the following syntax:
+Além disso, ao referenciar _slots_ com escopo definido, eles poderiam ser referenciados usando a seguinte sintaxe:
```js
-// 2.x Syntax
+// Sintaxe v2.x
this.$scopedSlots.header
```
-## 3.x Syntax
+## Sintaxe v3.x
-In 3.x, slots are defined as children of the current node as an object:
+Na v3.x, os _slots_ são definidos como um objeto, filhos do nó atual:
```js
-// 3.x Syntax
+// Sintaxe v3.x
h(LayoutComponent, {}, {
header: () => h('div', this.header),
content: () => h('div', this.content)
})
```
-And when you need to reference scoped slots programmatically, they are now unified into the `$slots` option.
+E quando você precisar referenciar _slots_ com escopo programaticamente, estes agora estão unificados na opção `$slots`.
```js
-// 2.x Syntax
+// Sintaxe v2.x
this.$scopedSlots.header
-// 3.x Syntax
+// Sintaxe v3.x
this.$slots.header()
```
-## Migration Strategy
+## Estratégia de Migração
-A majority of the change has already been shipped in 2.6. As a result, the migration can happen in one step:
+A maioria das alterações já estão presentes na versão 2.6. Desta forma, a migração pode acontecer em uma etapa:
-1. Replace all `this.$scopedSlots` occurrences with `this.$slots` in 3.x.
-2. Replace all occurrences of `this.$slots.mySlot` with `this.$slots.mySlot()`
+1. Susbstitua todas as ocorrências de `this.$scopedSlots` por `this.$slots` na v3.x.
+2. Susbstitua todas as ocorrências de `this.$slots.mySlot` por `this.$slots.mySlot()`.
-[Migration build flag: `INSTANCE_SCOPED_SLOTS`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `INSTANCE_SCOPED_SLOTS`](migration-build.html#configuracao-de-compatibilidade)
diff --git a/src/guide/migration/suspense.md b/src/guide/migration/suspense.md
index 4122f423e0..0b81aba969 100644
--- a/src/guide/migration/suspense.md
+++ b/src/guide/migration/suspense.md
@@ -6,18 +6,18 @@ badges:
# Suspense
:::warning Experimental
-Suspense is an experimental new feature and the API could change at any time. It is documented here so that the community can provide feedback on the current implementation.
+Suspense é um novo recurso experimental e a API pode mudar a qualquer momento. Está documentado aqui para que a comunidade possa fornecer feedback sobre a implementação atual.
-It should not be used in production applications.
+Não deve ser usado em aplicativos em produção.
:::
-## Introduction
+## Introdução
-It is common for components to need to perform some kind of asynchronous request before they can be rendered properly. Components often handle this locally and in many cases that is a perfectly good approach.
+É comum que os componentes precisem realizar algum tipo de solicitação assíncrona antes de serem renderizados corretamente. Os componentes geralmente lidam com isso localmente e, em muitos casos, essa é uma abordagem perfeitamente boa.
-The `` component provides an alternative, allowing for the waiting to be handled further up the component tree rather than in each individual component.
+O componente `` fornece uma alternativa, permitindo que a espera seja tratada mais adiante na árvore de componentes em vez de em cada componente individual.
-A common use case involves [async components](/guide/component-dynamic-async.html#async-components):
+Um caso de uso comum envolve [componentes assíncronos](/guide/component-dynamic-async.html#componentes-assincronos):
```vue{2-4,6,17}
@@ -27,7 +27,7 @@ A common use case involves [async components](/guide/component-dynamic-async.htm
- Loading...
+ Carregando...
@@ -42,22 +42,22 @@ export default {
```
-The `` component has two slots. Both slots only allow for one immediate child node. The node in the `default` slot is shown if possible. If not, the node in the `fallback` slot will be shown instead.
+O componente `` tem dois slots. Ambos os slots permitem apenas um nó filho imediato. O nó no slot `default` é mostrado se possível. Caso contrário, o nó no slot `fallback` será exibido.
-Importantly, the async component doesn't need to be the immediate child of the ``. It can be at any depth within the component tree and doesn't need to appear in the same template as the `` itself. The content is only considered resolved once all descendants are ready.
+Importante, o componente assíncrono não precisa ser o filho imediato do ``. Ele pode estar em qualquer profundidade dentro da árvore de componentes e não precisa aparecer no mesmo _template_ que o próprio ``. O conteúdo só é considerado resolvido quando todos os descendentes estiverem prontos.
-The other way to trigger the `fallback` slot is for a descendant component to return a promise from its `setup` function. This is typically implemented using `async` rather than explicitly returning a promise:
+A outra maneira de acionar o slot `fallback` é um componente descendente retornar uma promise de sua função `setup`. Isso geralmente é implementado usando `async` em vez de retornar explicitamente uma promise:
```js{2}
export default {
async setup() {
- // Be very careful using `await` inside `setup` as
- // most Composition API functions will only work
- // prior to the first `await`
+ // Tenha muito cuidado ao usar `await` dentro de `setup` como
+ // a maioria das funções da API de Composição só funcionará
+ // antes do primeiro `await`
const data = await loadData()
- // This is implicitly wrapped in a promise because
- // the function is `async`
+ // Isso está implicitamente envolvido em uma promise porque
+ // a função é `assíncrona`
return {
// ...
}
@@ -65,25 +65,25 @@ export default {
}
```
-## Child Updates
+## Atualizações em Filhos
-Once a `` has resolved the contents of its `default` slot, it can only be triggered again if the `default` root node is replaced. New components nested deeper in the tree are not sufficient to move the `` back into a pending state.
+Uma vez que um `` tenha resolvido o conteúdo de seu slot `default`, ele só pode ser acionado novamente se o nó raiz `default` for substituído. Novos componentes aninhados mais profundamente na árvore não são suficientes para mover o `` de volta para um estado pendente.
-If the root node does change it will trigger the `pending` event. However, by default, it won't update the DOM to show the `fallback` content. Instead, it will continue to show the old DOM until the new components are ready. This can be controlled using the `timeout` prop. This value, expressed in milliseconds, tells the `` component how long to wait before showing the `fallback`. A value of `0` will show it immediately when the `` enters the pending state.
+Se o nó raiz mudar, ele acionará o evento `pending`. No entanto, por padrão, ele não atualizará o DOM para mostrar o conteúdo `fallback`. Em vez disso, ele continuará mostrando o DOM antigo até que os novos componentes estejam prontos. Isso pode ser controlado usando a prop `timeout`. Este valor, expresso em milissegundos, diz ao componente `` quanto tempo esperar antes de mostrar o `fallback`. Um valor de `0` irá mostrá-lo imediatamente quando o `` entrar no estado pendente.
-## Events
+## Eventos
-In addition to the `pending` event, the `` component also has `resolve` and `fallback` events. The `resolve` event is emitted when new content has finished resolving in the `default` slot. The `fallback` event is fired when the contents of the `fallback` slot are shown.
+Além do evento `pending`, o componente `` também possui eventos `resolve` e `fallback`. O evento `resolve` é emitido quando o novo conteúdo termina de resolver no slot `default`. O evento `fallback` é acionado quando o conteúdo do slot `fallback` é mostrado.
-The events could be used, for example, to show a loading indicator in front of the old DOM while new components are loading.
+Os eventos podem ser usados, por exemplo, para mostrar um indicador de carregamento na frente do DOM antigo enquanto novos componentes estão sendo carregados.
-## Combining with Other Components
+## Combinando com Outros Componentes
-It is common to want to use `` in combination with the [``](/api/built-in-components.html#transition) and [``](/api/built-in-components.html#keep-alive) components. The nesting order of these components is important to get them all working correctly.
+É comum querer usar `` em combinação com os componentes [``](/api/built-in-components.html#transition) e [``](/api/built-in-components.html#keep-alive). A ordem de aninhamento desses componentes é importante para que todos funcionem corretamente.
-In addition, these components are often used in conjunction with the `` component from [Vue Router](https://next.router.vuejs.org/).
+Além disso, esses componentes são frequentemente usados em conjunto com o componente `` do [Vue Router](https://next.router.vuejs.org/).
-The following example shows how to nest these components so that they all behave as expected. For simpler combinations you can remove the components that you don't need:
+O exemplo a seguir mostra como aninhar esses componentes para que todos se comportem conforme o esperado. Para combinações mais simples, você pode remover os componentes desnecessários:
```html
@@ -94,7 +94,7 @@ The following example shows how to nest these components so that they all behave
- Loading...
+ Carregando...
@@ -104,4 +104,4 @@ The following example shows how to nest these components so that they all behave
```
-Vue Router has built-in support for [lazily loading components](https://next.router.vuejs.org/guide/advanced/lazy-loading.html) using dynamic imports. These are distinct from async components and currently they will not trigger ``. However, they can still have async components as descendants and those can trigger `` in the usual way.
+O Vue Router tem suporte embutido para [carregar componentes preguiçosamente](https://next.router.vuejs.org/guide/advanced/lazy-loading.html) usando importações dinâmicas. Eles são distintos dos componentes assíncronos e atualmente eles não acionarão ``. No entanto, eles ainda podem ter componentes assíncronos como descendentes e esses podem acionar `` da maneira usual.
diff --git a/src/guide/migration/transition-as-root.md b/src/guide/migration/transition-as-root.md
index bb15893766..b1e73b2e69 100644
--- a/src/guide/migration/transition-as-root.md
+++ b/src/guide/migration/transition-as-root.md
@@ -3,18 +3,18 @@ badges:
- breaking
---
-# Transition as Root
+# `transition` como Raiz
-## Overview
+## Visão Geral
-Using a `` as a component's root will no longer trigger transitions when the component is toggled from the outside.
+O uso de um `` como raiz de um componente não acionará mais transições quando o componente for alternado de fora.
-## 2.x Behavior
+## Comportamento v2.x
-In Vue 2, it was possible to trigger a transition from outside a component by using a `` as the component's root:
+No Vue 2, era possível acionar uma transição de fora de um componente usando um `` como raiz do componente:
```html
-
+
@@ -23,19 +23,19 @@ In Vue 2, it was possible to trigger a transition from outside a component by us
```
```html
-
-hello
+
+olá
```
-Toggling the value of `showModal` would trigger a transition inside the modal component.
+Alternar o valor de `showModal` acionaria uma transição dentro do componente modal.
-This worked by accident, not by design. A `` is supposed to be triggered by changes to its children, not by toggling the `` itself.
+Isso funcionou por acidente, não por design. Uma `` deve ser desencadeada por alterações em seus filhos, não alternando a própria ``.
-This quirk has now been removed.
+Esta peculiaridade foi removida.
-## Migration Strategy
+## Estratégia de Migração
-A similar effect can be achieved by passing a prop to the component instead:
+Um efeito semelhante pode ser obtido passando uma prop para o componente:
```vue
@@ -51,11 +51,11 @@ export default {
```
```html
-
-hello
+
+olá
```
-## See also
+## Veja também
-- [Some transition classes got a rename](/guide/migration/transition.html)
-- [`` now renders no wrapper element by default](/guide/migration/transition-group.html)
+- [Algumas classes de transição foram renomeadas](/guide/migration/transition.html)
+- [`` agora não renderiza nenhum elemento _wrapper_ por padrão](/guide/migration/transition-group.html)
diff --git a/src/guide/migration/transition-group.md b/src/guide/migration/transition-group.md
index 4137ae4d5f..f6d483c7aa 100644
--- a/src/guide/migration/transition-group.md
+++ b/src/guide/migration/transition-group.md
@@ -1,18 +1,18 @@
---
-title: Transition Group Root Element
+title: Elemento Raiz para Transição em Grupo
badges:
- breaking
---
# {{ $frontmatter.title }}
-## Overview
+## Visão Geral
-`` no longer renders a root element by default, but can still create one with the `tag` attribute.
+`` não renderiza mais um elemento raiz por padrão, mas ainda pode criar um com o atributo `tag`.
-## 2.x Syntax
+## Sintaxe v2.x
-In Vue 2, ``, like other custom components, needed a root element, which by default was a `` but was customizable via the `tag` attribute.
+No Vue 2, ``, como outros componentes personalizados, precisava de um elemento raiz, que por padrão era um ``, mas era personalizável através do atributo `tag`.
```html
@@ -22,12 +22,12 @@ In Vue 2, ``, like other custom components, needed a root elem
```
-## 3.x Syntax
+## Sintaxe v3.x
-In Vue 3, we have [fragment support](/guide/migration/fragments.html), so components no longer _need_ a root node. Consequently, `` no longer renders one by default.
+No Vue 3, temos [suporte a fragmentos](/guide/migration/fragments.html), então os componentes não precisam mais de um nó raiz. Consequentemente, `` não renderiza mais um por padrão.
-- If you already have the `tag` attribute defined in your Vue 2 code, like in the example above, everything will work as before
-- If you didn't have one defined _and_ your styling or other behaviors relied on the presence of the `` root element to work properly, simply add `tag="span"` to the ``:
+- Se você já tem o atributo `tag` definido em seu código Vue 2, como no exemplo acima, tudo funcionará como antes
+- Se você não tem um definido _e_ seu estilo ou outros comportamentos dependem da presença do elemento raiz `` para funcionar corretamente, basta adicionar `tag="span"` ao ``:
```html
@@ -35,11 +35,11 @@ In Vue 3, we have [fragment support](/guide/migration/fragments.html), so compon
```
-## Migration Strategy
+## Estratégia de Migração
-[Migration build flag: `TRANSITION_GROUP_ROOT`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `TRANSITION_GROUP_ROOT`](migration-build.html#configuracao-de-compatibilidade)
-## See also
+## Veja também
-- [Some transition classes got a rename](/guide/migration/transition.html)
-- [`` as a root can no longer be toggled from the outside](/guide/migration/transition-as-root.html)
+- [Algumas classes de transição foram renomeadas](/guide/migration/transition.html)
+- [`` como root não pode mais ser alternado do lado de fora](/guide/migration/transition-as-root.html)
diff --git a/src/guide/migration/transition.md b/src/guide/migration/transition.md
index 1261c208b8..c9bf47661d 100644
--- a/src/guide/migration/transition.md
+++ b/src/guide/migration/transition.md
@@ -1,20 +1,20 @@
---
-title: Transition Class Change
+title: Mudança das Classes de Transição
badges:
- breaking
---
# {{ $frontmatter.title }}
-## Overview
+## Visão Geral
-The `v-enter` transition class has been renamed to `v-enter-from` and the `v-leave` transition class has been renamed to `v-leave-from`.
+A classe de transição `v-enter` foi renomeada para `v-enter-from` e a classe de transição `v-leave` foi renomeada para `v-leave-from`.
-## 2.x Syntax
+## Sintaxe v2.x
-Before v2.1.8, we had two transition classes for each transition direction: initial and active states.
+Antes da v2.1.8, nós tinhamos duas classes de transição para cada direção da transição: estados inicial e ativo.
-In v2.1.8, we introduced `v-enter-to` to address the timing gap between enter/leave transitions. However, for backward compatibility, the `v-enter` name was untouched:
+Na v2.1.8, nós introduzimos a `v-enter-to` para endereçar o intervalo de tempo entre as transições enter/leave. Entretanto, para compatibilidade com versões anteriores, o nome `v-enter` se manteve inalterado:
```css
.v-enter,
@@ -28,11 +28,11 @@ In v2.1.8, we introduced `v-enter-to` to address the timing gap between enter/le
}
```
-This became confusing, as _enter_ and _leave_ were broad and not using the same naming convention as their class hook counterparts.
+Isso se tornou confuso, como _enter_ e _leave_ eram amplos e não utilizavam a mesma convenção de nome que suas classes de ligação homólogas.
-## 3.x Update
+## Atualização v3.x
-In order to be more explicit and legible, we have now renamed these initial state classes:
+De forma à deixar mais explícito e legível, nós agora renomeamos essas classes de estado inicial:
```css
.v-enter-from,
@@ -46,22 +46,22 @@ In order to be more explicit and legible, we have now renamed these initial stat
}
```
-It's now much clearer what the difference between these states is.
+Agora é muito mais claro a diferença entre esses estados.
-
+
-The `` component's related prop names are also changed:
+Os nomes de propriedades do componente `` relacionadas também foram alterados:
-- `leave-class` is renamed to `leave-from-class` (can be written as `leaveFromClass` in render functions or JSX)
-- `enter-class` is renamed to `enter-from-class` (can be written as `enterFromClass` in render functions or JSX)
+- `leave-class` é renomeada para `leave-from-class` (pode ser escrita como `leaveFromClass` em funções de renderização ou JSX)
+- `enter-class` é renomeada para `enter-from-class` (pode ser escrita como `enterFromClass` em funções de renderização ou JSX)
-## Migration Strategy
+## Estratégia de Migração
-1. Replace instances of `.v-enter` to `.v-enter-from`
-2. Replace instances of `.v-leave` to `.v-leave-from`
-3. Replace instances of related prop names, as above.
+1. Substitua instâncias de `.v-enter` por `.v-enter-from`
+2. Substitua instâncias de `.v-leave` por `.v-leave-from`
+3. Substitua instâncias de nomes de propriedades relacionadas, como acima.
-## See also
+## Ver também
-- [`` as a root can no longer be toggled from the outside](/guide/migration/transition-as-root.html)
-- [`` now renders no wrapper element by default](/guide/migration/transition-group.html)
+- [`` como uma raiz não pode mais ser alternada do lado de fora](/guide/migration/transition-as-root.html)
+- [`` agora não renderiza nenhum elemento _wrapper_ por padrão](/guide/migration/transition-group.html)
diff --git a/src/guide/migration/v-bind.md b/src/guide/migration/v-bind.md
index 902e2ce4cb..2791d32e8f 100644
--- a/src/guide/migration/v-bind.md
+++ b/src/guide/migration/v-bind.md
@@ -1,48 +1,48 @@
---
-title: v-bind Merge Behavior
+title: Comportamento ao Combinar v-bind
badges:
- breaking
---
# {{ $frontmatter.title }}
-## Overview
+## Visão Geral
-- **BREAKING**: Order of bindings for v-bind will affect the rendering result.
+- **QUEBRA**: A ordem das vinculações para `v-bind` irá afetar o resultado da renderização.
-## Introduction
+## Visão Geral
-When dynamically binding attributes on an element, a common scenario involves using both the `v-bind="object"` syntax as well as individual attributes in the same element. However, this raises questions as far as the priority of merging.
+Quando se está dinamicamente vinculando atributos em um elemento, um cenário comum envolve utilizar tanto a sintaxe `v-bind="object"` quanto os atributos individuais no mesmo elemento. Contudo, isso gera questões tal como a prioridade na combinação.
-## 2.x Syntax
+## Sintaxe 2.x
-In 2.x, if an element has both `v-bind="object"` and an identical individual attribute defined, the individual attribute would always overwrite bindings in the `object`.
+No 2.x, se um elemento tem tanto o `v-bind="object"` quanto um atributo individual idêntico definido, o atributo individual sempre vai sobrescrever as vinculações do `object`.
```html
-
+
```
-## 3.x Syntax
+## Sintaxe v3.x
-In 3x, if an element has both `v-bind="object"` and an identical individual attribute defined, the order of how the bindings are declared determines how they are merged. In other words, rather than assuming developers want the individual attribute to always override what is defined in the `object`, developers now have more control over the desired merging behavior.
+Na v3.x, se um elemento tem tanto o `v-bind="object"` quanto um atributo individual idêntico definido, a ordem de como as vinculações são declaradas determina como elas serão combinadas. Em outras palavras, em vez de assumir que os desenvolvedores querem que o atributo individual sempre sobrescreva o que está definido no `object`, agora os desenvolvedores terão mais controle sobre qual o comportamento desejado na combinação.
```html
-
+
-
+
```
-## Migration Strategy
+## Estratégia de Migração
-If you are relying on this override functionality for `v-bind`, we currently recommend ensuring that your `v-bind` attribute is defined before individual attributes.
+Se você está confiando nessa funcionalidade de sobrescrita do `v-bind`, nós atualmente recomendamos você à garantir que seu atributo `v-bind` seja definido sempre antes dos atributos individuais.
-[Migration build flag: `COMPILER_V_BIND_OBJECT_ORDER`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `COMPILER_V_BIND_OBJECT_ORDER`](migration-build.html#configuracao-de-compatibilidade)
diff --git a/src/guide/migration/v-if-v-for.md b/src/guide/migration/v-if-v-for.md
index 8908083771..ef761aea7c 100644
--- a/src/guide/migration/v-if-v-for.md
+++ b/src/guide/migration/v-if-v-for.md
@@ -1,36 +1,36 @@
---
-title: v-if vs. v-for Precedence
+title: Precedência de v-if vs. v-for
badges:
- breaking
---
# {{ $frontmatter.title }}
-## Overview
+## Visão Geral
-- **BREAKING**: If used on the same element, `v-if` will have higher precedence than `v-for`
+- **QUEBRA**: Se usado no mesmo elemento, `v-if` terá uma maior precedência do que `v-for`
-## Introduction
+## Introdução
-Two of the most commonly used directives in Vue.js are `v-if` and `v-for`. So it's no surprise that there comes a time when developers want to use both together. While this is not a recommended practice, there may be times when this is necessary, so we wanted to provide guidance for how it works.
+Duas das diretivas mais comumente usadas em Vue.js são `v-if` e `v-for`. Portanto, não é surpresa que chegue um momento em que os desenvolvedores desejem usar os dois juntos. Embora não seja uma prática recomendada, pode haver momentos em que isso seja necessário, por isso gostaríamos de fornecer orientações sobre como isso funciona.
-## 2.x Syntax
+## Sintaxe v2.x
-In 2.x, when using `v-if` and `v-for` on the same element, `v-for` would take precedence.
+Na v2.x, quando utilizado `v-if` e `v-for` no mesmo elemento, `v-for` teria precedência.
-## 3.x Syntax
+## Sintaxe v3.x
-In 3.x, `v-if` will always have the higher precedence than `v-for`.
+Na v3.x, `v-if` terá sempre uma maior precedência do que `v-for`.
-## Migration Strategy
+## Estratégia de Migração
-It is recommended to avoid using both on the same element due to the syntax ambiguity.
+Recomenda-se evitar o uso de ambos no mesmo elemento devido à ambiguidade da sintaxe.
-Rather than managing this at the template level, one method for accomplishing this is to create a computed property that filters out a list for the visible elements.
+Em vez de gerenciar isso à nível de _template_, um método para realizar isso é criar um dado computado (computed property) que filtre uma lista para os elementos visíveis.
-[Migration build flag: `COMPILER_V_IF_V_FOR_PRECEDENCE`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `COMPILER_V_IF_V_FOR_PRECEDENCE`](migration-build.html#configuracao-de-compatibilidade)
-## See also
+## Veja também
-- [List Rendering - Displaying Filtered/Sorted Results](/guide/list.html#displaying-filtered-sorted-results)
-- [List Rendering - `v-for` with `v-if`](/guide/list.html#v-for-with-v-if)
+- [Renderização de Listas - Exibindo Resultados Filtrados/Ordenados](/guide/list.html#exibindo-resultados-filtrados-ordenados)
+- [Renderização de Listas - Utilizando `v-if` com `v-for`](/guide/list.html#utilizando-v-if-com-v-for)
diff --git a/src/guide/migration/v-model.md b/src/guide/migration/v-model.md
index 928a2b3169..3c49ad9ca9 100644
--- a/src/guide/migration/v-model.md
+++ b/src/guide/migration/v-model.md
@@ -5,40 +5,40 @@ badges:
# `v-model`
-## Overview
+## Visão Geral
-In terms of what has changed, at a high level:
+Olhando por cima o que mudou:
-- **BREAKING:** When used on custom components, `v-model` prop and event default names are changed:
+- **QUEBRA:** Quando usado em componentes customizados, o nome padrão da propriedade e do evento do `v-model` mudaram:
- prop: `value` -> `modelValue`;
- event: `input` -> `update:modelValue`;
-- **BREAKING:** `v-bind`'s `.sync` modifier and component `model` option are removed and replaced with an argument on `v-model`;
-- **NEW:** Multiple `v-model` bindings on the same component are possible now;
-- **NEW:** Added the ability to create custom `v-model` modifiers.
+- **QUEBRA:** O modificador `.sync` que existia no `v-bind` e a opção `model` de componentes foram substituídos pelo `v-model` com um argumento;
+- **NOVO:** Múltiplos vínculos do `v-model` no mesmo componente são possíveis agora;
+- **NOVO:** Adicionado a possibilidade de criar modificadores para o `v-model`.
-For more information, read on!
+Para mais informações, continue lendo!
-## Introduction
+## Introdução
-When Vue 2.0 was released, the `v-model` directive required developers to always use the `value` prop. And if developers required different props for different purposes, they would have to resort to using `v-bind.sync`. In addition, this hard-coded relationship between `v-model` and `value` led to issues with how native elements and custom elements were handled.
+Quando o Vue 2.0 foi lançado, a diretiva `v-model` exigia para os desenvolvedores sempre usar a propriedade `value`. E se os desenvolvedores precisassem usar uma propriedade diferente para um outro propósito, eles deveriam recorrer ao uso do `v-bind.sync`. Além disso, essa relação fixa entre `v-model` e` value` levou à problemas com a forma como os elementos nativos e personalizados eram tratados.
-In 2.2 we introduced the `model` component option that allows the component to customize the prop and event to use for `v-model`. However, this still only allowed a single `v-model` to be used on the component.
+Na versão 2.2, introduzimos a opção de componente `model` que permite ao componente personalizar a propriedade e o evento para usar no `v-model`. No entanto, isso ainda apenas permitia que um único `v-model` fosse usado no componente.
-With Vue 3, the API for two-way data binding is being standardized in order to reduce confusion and to allow developers more flexibility with the `v-model` directive.
+Com o Vue 3, a API para vinculação de dados bidirecional está sendo padronizada para reduzir a confusão e permitir aos desenvolvedores mais flexibilidade com a diretiva `v-model`.
-## 2.x Syntax
+## Sintaxe v2.x
-In 2.x, using a `v-model` on a component was an equivalent of passing a `value` prop and emitting an `input` event:
+Na v2.x, usando um `v-model` em um componente era equivalente a passar uma propriedade `value` e emitir um evento `input`:
```html
-
+
```
-If we wanted to change prop or event names to something different, we would need to add a `model` option to `ChildComponent` component:
+Se quiséssemos mudar os nomes da propriedade ou evento para algo diferente, precisaríamos adicionar uma opção `model` ao componente `ChildComponent`:
```html
@@ -55,51 +55,51 @@ export default {
event: 'change'
},
props: {
- // this allows using the `value` prop for a different purpose
+ // isso permite a utilização da propriedade `value` para um propósito diferente
value: String,
- // use `title` as the prop which take the place of `value`
+ // utilizando `title` como uma propriedade que irá tomar o lugar do `value`
title: {
type: String,
- default: 'Default title'
+ default: 'Título padrão'
}
}
}
```
-So, `v-model` in this case would be a shorthand to
+Então, o `v-model` nesse caso seria um atalho para:
```html
```
-### Using `v-bind.sync`
+### Usando `v-bind.sync`
-In some cases, we might need "two-way binding" for a prop (sometimes in addition to existing `v-model` for the different prop). To do so, we recommended emitting events in the pattern of `update:myPropName`. For example, for `ChildComponent` from the previous example with the `title` prop, we could communicate the intent of assigning a new value with:
+Em alguns casos, podemos precisar de uma "ligação bidirecional" para uma propriedade (às vezes além do `v-model` existente para uma propriedade diferente). Para fazer isso, recomendamos a emissão de eventos no padrão de `update:myPropName`. Por exemplo, para `ChildComponent` do exemplo anterior com a propriedade `title`, poderíamos comunicar a intenção de atribuir um novo valor com:
```js
this.$emit('update:title', newValue)
```
-Then the parent could listen to that event and update a local data property, if it wants to. For example:
+Em seguida, o pai pode ouvir esse evento e atualizar uma propriedade de dados local, se quiser. Por exemplo:
```html
```
-For convenience, we had a shorthand for this pattern with the `.sync` modifier:
+Por conveniência, tínhamos uma abreviatura para esse padrão com o modificador `.sync`:
```html
```
-## 3.x Syntax
+## Sintaxe v3.x
-In 3.x `v-model` on the custom component is an equivalent of passing a `modelValue` prop and emitting an `update:modelValue` event:
+Na versão 3.x o `v-model` em um componente personalizado é equivalente a passar um prop `modelValue` e emitir um evento `update:modelValue`:
```html
-
+
```
-### `v-model` arguments
+### Argumentos do `v-model`
-To change a model name, instead of a `model` component option, now we can pass an _argument_ to `v-model`:
+Para alterar o nome de um modelo, em vez de uma opção de componente `model`, agora podemos passar um _argumento_ para` v-model`:
```html
-
+
```
-
+
-This also serves as a replacement to `.sync` modifier and allows us to have multiple `v-model`s on the custom component.
+Isso também serve como um substituto para o modificador `.sync` e nos permite ter vários `v-model`s no componente personalizado.
```html
-
+
```
-### `v-model` modifiers
+### Modificadores do `v-model`
-In addition to 2.x hard-coded `v-model` modifiers like `.trim`, now 3.x supports custom modifiers:
+Além dos modificadores do `v-model` fixos já existentes na v2.x, como `.trim`, agora v3.x suporta modificadores personalizados:
```html
```
-Read more about custom `v-model` modifiers in the [Custom Events](../component-custom-events.html#handling-v-model-modifiers) section.
+Leia mais sobre modificadores do `v-model` customizados na seção [Eventos Customizados](../component-custom-events.html#handling-v-model-modifiers).
-## Migration Strategy
+## Estratégia de Migração
-We recommend:
+Nós recomendamos:
-- checking your codebase for `.sync` usage and replace it with `v-model`:
+- verificar seu código aonde utilizado o `.sync` e substituí-lo por `v-model`:
```html
-
+
```
-- for all `v-model`s without arguments, make sure to change props and events name to `modelValue` and `update:modelValue` respectively
+- para todos os `v-model`s sem argumentos, certifique-se de alterar o nome das propriedades e eventos para `modelValue` e `update:modelValue` respectivamente
```html
@@ -171,26 +171,26 @@ We recommend:
export default {
props: {
- modelValue: String // previously was `value: String`
+ modelValue: String // anteriormente era `value: String`
},
emits: ['update:modelValue'],
methods: {
changePageTitle(title) {
- this.$emit('update:modelValue', title) // previously was `this.$emit('input', title)`
+ this.$emit('update:modelValue', title) // anteriormente era `this.$emit('input', title)`
}
}
}
```
-[Migration build flags:](migration-build.html#compat-configuration)
+[Sinalizadores na compilação de migração:](migration-build.html#configuracao-de-compatibilidade)
- `COMPONENT_V_MODEL`
- `COMPILER_V_BIND_SYNC`
-## Next Steps
+## Próximos Passos
-For more information on the new `v-model` syntax, see:
+Para mais informações na nova sintaxe do `v-model`, veja:
-- [Using `v-model` on Components](../component-basics.html#using-v-model-on-components)
-- [`v-model` arguments](../component-custom-events.html#v-model-arguments)
-- [Handling `v-model` modifiers](../component-custom-events.html#handling-v-model-modifiers)
+- [Utilizando `v-model` em Componentes](../component-basics.html#usando-v-model-em-componentes)
+- [Argumentos do `v-model`](../component-custom-events.html#argumentos-do-v-model)
+- [Tratando modificadores do `v-model`](../component-custom-events.html#manipulando-modificadores-do-v-model)
diff --git a/src/guide/migration/v-on-native-modifier-removed.md b/src/guide/migration/v-on-native-modifier-removed.md
index fd9c153b49..a763e5e7b7 100644
--- a/src/guide/migration/v-on-native-modifier-removed.md
+++ b/src/guide/migration/v-on-native-modifier-removed.md
@@ -1,18 +1,18 @@
---
-title: v-on.native modifier removed
+title: Modificador v-on.native removido
badges:
- breaking
---
-# `v-on.native` modifier removed
+# Modificador `v-on.native` removido
-## Overview
+## Visão Geral
-The `.native` modifier for `v-on` has been removed.
+O modificador `.native` para `v-on` foi removido.
-## 2.x Syntax
+## Sintaxe v2.x
-Event listeners passed to a component with `v-on` are by default only triggered by emitting an event with `this.$emit`. To add a native DOM listener to the child component's root element instead, the `.native` modifier can be used:
+Os escutadores de eventos passados para um componente com `v-on` são por padrão apenas acionados pela emissão de um evento com `this.$emit`. Para adicionar um escutador nativo do DOM ao elemento raiz do componente filho, o modificador `.native` pode ser usado:
```html
```
-## 3.x Syntax
+## Sintaxe v3.x
-The `.native` modifier for `v-on` has been removed. At the same time, the [new `emits` option](./emits-option.md) allows the child to define which events it does indeed emit.
+O modificador `.native` para `v-on` foi removido. Ao mesmo tempo, a [nova opção `emits`](./emits-option.md) permite que o filho defina quais eventos ele de fato emite.
-Consequently, Vue will now add all event listeners that are _not_ defined as component-emitted events in the child as native event listeners to the child's root element (unless `inheritAttrs: false` has been set in the child's options).
+Consequentemente, o Vue agora adicionará todos os escutadores de eventos que _não_ são definidos como eventos emitidos por componentes no filho como escutadores de eventos nativos ao elemento raiz do filho (a menos que `inheritAttrs: false` tenha sido definido nas opções do filho).
```html
```
-## Migration Strategy
+## Estratégia de Migração
-- remove all instances of the `.native` modifier.
-- ensure that all your components document their events with the `emits` option.
+- remova todas as instâncias do modificador `.native`.
+- certifique-se de que todos os seus componentes documentem seus eventos com a opção `emits`.
-[Migration build flag: `COMPILER_V_ON_NATIVE`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `COMPILER_V_ON_NATIVE`](migration-build.html#configuracao-de-compatibilidade)
-## See also
+## Veja também
-- [Relevant RFC](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0031-attr-fallthrough.md#v-on-listener-fallthrough)
-- [Migration guide - New Emits Option](./emits-option.md)
-- [Migration guide - `$listeners` removed](./listeners-removed.md)
-- [Migration guide - Changes in the Render Functions API](./render-function-api.md)
+- [RFC Relevante](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0031-attr-fallthrough.md#v-on-listener-fallthrough)
+- [Guia de migração - Nova Opção Emits](./emits-option.md)
+- [Guia de migração - `$listeners` removido](./listeners-removed.md)
+- [Guia de migração - Alterações na API de funções de renderização](./render-function-api.md)
diff --git a/src/guide/migration/vnode-lifecycle-events.md b/src/guide/migration/vnode-lifecycle-events.md
index 8ad0b231b9..6baa5f5ac3 100644
--- a/src/guide/migration/vnode-lifecycle-events.md
+++ b/src/guide/migration/vnode-lifecycle-events.md
@@ -3,17 +3,17 @@ badges:
- breaking
---
-# VNode Lifecycle Events
+# Eventos de Ciclo de Vida do VNode
-## Overview
+## Visão Geral
-In Vue 2, it was possible to use events to listen for key stages in a component's lifecycle. These events had names that started with the prefix `hook:`, followed by the name of the corresponding lifecycle hook.
+No Vue 2, era possível usar eventos para escutar os principais estágios do ciclo de vida de um componente. Esses eventos tinham nomes que começavam com o prefixo `hook:`, seguido pelo nome do gatilho do ciclo de vida correspondente.
-In Vue 3, this prefix has been changed to `vnode-`. In addition, these events are now available for HTML elements as well as components.
+No Vue 3, esse prefixo foi alterado para `vnode-`. Além disso, esses eventos agora estão disponíveis para elementos HTML e componentes.
-## 2.x Syntax
+## Sintaxe v2.x
-In Vue 2, the event name is the same as the equivalent lifecycle hook, prefixed with `hook:`:
+No Vue 2, o nome do evento é o mesmo que o gatilho do ciclo de vida equivalente, prefixado com `hook:`:
```html
@@ -21,9 +21,9 @@ In Vue 2, the event name is the same as the equivalent lifecycle hook, prefixed
```
-## 3.x Syntax
+## Sintaxe v3.x
-In Vue 3, the event name is prefixed with `vnode-`:
+No Vue 3, o nome do evento é prefixado com `vnode-`:
```html
@@ -31,7 +31,7 @@ In Vue 3, the event name is prefixed with `vnode-`:
```
-Or just `vnode` if you're using camelCase:
+Ou apenas `vnode` se você estiver usando camelCase:
```html
@@ -39,12 +39,12 @@ Or just `vnode` if you're using camelCase:
```
-## Migration Strategy
+## Estratégia de Migração
-In most cases it should just require changing the prefix. The lifecycle hooks `beforeDestroy` and `destroyed` have been renamed to `beforeUnmount` and `unmounted` respectively, so the corresponding event names will also need to be updated.
+Na maioria dos casos, deve apenas exigir a alteração do prefixo. Os gatilhos do ciclo de vida `beforeDestroy` e `destroyed` foram renomeados para `beforeUnmount` e `unmounted` respectivamente, então os nomes dos eventos correspondentes também precisarão ser atualizados.
-[Migration build flags: `INSTANCE_EVENT_HOOKS`](migration-build.html#compat-configuration)
+[Sinalizadores na compilação de migração: `INSTANCE_EVENT_HOOKS`](migration-build.html#configuracao-de-compatibilidade)
-## See Also
+## Veja também
-- [Migration guide - Events API](/guide/migration/events-api.html)
+- [Guia de migração - API de eventos](/guide/migration/events-api.html)
diff --git a/src/guide/migration/watch.md b/src/guide/migration/watch.md
index 56d93be663..932dad0f51 100644
--- a/src/guide/migration/watch.md
+++ b/src/guide/migration/watch.md
@@ -1,32 +1,32 @@
---
-title: Watch on Arrays
+title: Observar Arrays
badges:
- breaking
---
# {{ $frontmatter.title }}
-## Overview
+## Visão Geral
-- **BREAKING**: When watching an array, the callback will only trigger when the array is replaced. If you need to trigger on mutation, the `deep` option must be specified.
+- **QUEBRA**: Ao observar um Array, o _callback_ só será acionado quando o Array for completamente substituído. Se você precisar acionar em mutação, a opção `deep` deve ser especificada.
-## 3.x Syntax
+## Sintaxe v3.x
-When using [the `watch` option](/api/options-data.html#watch) to watch an array, the callback will only trigger when the array is replaced. In other words, the watch callback will no longer be triggered on array mutation. To trigger on mutation, the `deep` option must be specified.
+Ao usar [a opção `watch`](/api/options-data.html#watch) para observar um Array, o _callback_ só será disparado quando o Array for substituído. Em outras palavras, o _callback_ do observador não será mais acionado na mutação do Array. Para acionar em mutação, a opção `deep` deve ser especificada.
```js
watch: {
bookList: {
handler(val, oldVal) {
- console.log('book list changed')
+ console.log('lista de livros alterada')
},
deep: true
},
}
```
-## Migration Strategy
+## Estratégia de Migração
-If you rely on watching array mutations, add the `deep` option to ensure that your callback is triggered correctly.
+Se você depende da observação de mutações de Arrays, adicione a opção `deep` para garantir que seu retorno de chamada (_callback_) seja disparado corretamente.
-[Migration build flag: `WATCH_ARRAY`](migration-build.html#compat-configuration)
+[Sinalizador na compilação de migração: `WATCH_ARRAY`](migration-build.html#configuracao-de-compatibilidade)
diff --git a/src/guide/mixins.md b/src/guide/mixins.md
index 8103c019b2..66678b18cb 100644
--- a/src/guide/mixins.md
+++ b/src/guide/mixins.md
@@ -1,43 +1,43 @@
# Mixins
-## Basics
+## Fundamentos
-Mixins distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be "mixed" into the component's own options.
+_Mixins_ distribuem funcionalidades reutilizáveis para componentes Vue. Um objeto _mixin_ pode conter quaisquer opções de componente. Quando um componente usa um _mixin_, todas as opções do _mixin_ serão "misturadas" com as opções do próprio componente.
-Example:
+Exemplo:
```js
-// define a mixin object
+// define um objeto mixin
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
- console.log('hello from mixin!')
+ console.log('olá do mixin!')
}
}
}
-// define an app that uses this mixin
+// definir um aplicativo que usa este mixin
const app = Vue.createApp({
mixins: [myMixin]
})
-app.mount('#mixins-basic') // => "hello from mixin!"
+app.mount('#mixins-basic') // => "olá do mixin!"
```
-## Option Merging
+## Mesclagem de Opções
-When a mixin and the component itself contain overlapping options, they will be "merged" using appropriate strategies.
+Quando um _mixin_ e o próprio componente contêm opções se sobrepondo, elas serão "mescladas" usando estratégias apropriadas.
-For example, each mixin can have its own `data` function. Each of them will be called, with the returned objects being merged. Properties from the component's own data will take priority in cases of conflicts.
+Por exemplo, cada _mixin_ pode ter sua própria função `data`. Cada uma delas será chamada, com os objetos retornados sendo mesclados. As propriedades dos próprios dados do componente terão prioridade em caso de conflitos.
```js
const myMixin = {
data() {
return {
- message: 'hello',
+ message: 'olá',
foo: 'abc'
}
}
@@ -47,37 +47,37 @@ const app = Vue.createApp({
mixins: [myMixin],
data() {
return {
- message: 'goodbye',
+ message: 'Tchau',
bar: 'def'
}
},
created() {
- console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" }
+ console.log(this.$data) // => { message: "Tchau", foo: "abc", bar: "def" }
}
})
```
-Hook functions with the same name are merged into an array so that all of them will be called. Mixin hooks will be called **before** the component's own hooks.
+Gatilhos de funções com o mesmo nome são mesclados em um Array para que todos sejam chamados. Os gatilhos do _Mixin_ serão chamados **antes** dos próprios gatilhos do componente.
```js
const myMixin = {
created() {
- console.log('mixin hook called')
+ console.log('gatilho do mixin chamado')
}
}
const app = Vue.createApp({
mixins: [myMixin],
created() {
- console.log('component hook called')
+ console.log('gatilho do componente chamado')
}
})
-// => "mixin hook called"
-// => "component hook called"
+// => "gatilho do mixin chamado"
+// => "gatilho do componente chamado"
```
-Options that expect object values, for example `methods`, `components` and `directives`, will be merged into the same object. The component's options will take priority when there are conflicting keys in these objects:
+Opções que esperam valores em objeto, por exemplo `methods`, `components` e `directives`, serão mescladas no mesmo objeto. As opções do componente terão prioridade quando houver chaves conflitantes nestes objetos:
```js
const myMixin = {
@@ -86,7 +86,7 @@ const myMixin = {
console.log('foo')
},
conflicting() {
- console.log('from mixin')
+ console.log('do mixin')
}
}
}
@@ -98,7 +98,7 @@ const app = Vue.createApp({
console.log('bar')
},
conflicting() {
- console.log('from self')
+ console.log('de si mesmo')
}
}
})
@@ -107,19 +107,19 @@ const vm = app.mount('#mixins-basic')
vm.foo() // => "foo"
vm.bar() // => "bar"
-vm.conflicting() // => "from self"
+vm.conflicting() // => "de si mesmo"
```
-## Global Mixin
+## Mixin Global
-You can also apply a mixin globally for a Vue application:
+Você também pode aplicar um _mixin_ globalmente para um aplicativo Vue:
```js
const app = Vue.createApp({
- myOption: 'hello!'
+ myOption: 'Olá!'
})
-// inject a handler for `myOption` custom option
+// injetar um manipulador para a opção personalizada `myOption`
app.mixin({
created() {
const myOption = this.$options.myOption
@@ -129,17 +129,17 @@ app.mixin({
}
})
-app.mount('#mixins-global') // => "hello!"
+app.mount('#mixins-global') // => "Olá!"
```
-Use with caution! Once you apply a mixin globally, it will affect **every** component instance created afterwards in the given app (for example, child components):
+Use com cuidado! Depois de aplicar um _mixin_ globalmente, ele afetará **cada** instância de componente criada posteriormente no aplicativo fornecido (por exemplo, componentes filhos):
```js
const app = Vue.createApp({
- myOption: 'hello!'
+ myOption: 'Olá!'
})
-// inject a handler for `myOption` custom option
+// injetar um manipulador para a opção personalizada `myOption`
app.mixin({
created() {
const myOption = this.$options.myOption
@@ -149,78 +149,78 @@ app.mixin({
}
})
-// add myOption also to child component
+// adicione myOption também ao componente filho
app.component('test-component', {
- myOption: 'hello from component!'
+ myOption: 'Olá do componente!'
})
app.mount('#mixins-global')
-// => "hello!"
-// => "hello from component!"
+// => "Olá!"
+// => "Olá do componente"
```
-In most cases, you should only use it for custom option handling like demonstrated in the example above. It's also a good idea to ship them as [Plugins](plugins.html) to avoid duplicate application.
+Na maioria dos casos, você só deve usá-lo para manipulação de opções personalizadas, conforme demonstrado no exemplo acima. Também é uma boa ideia entregá-los como [Plugins](plugins.html) para evitar aplicação duplicada.
-## Custom Option Merge Strategies
+## Estratégias de Mesclagem de Opções Personalizadas
-When custom options are merged, they use the default strategy which overwrites the existing value. If you want a custom option to be merged using custom logic, you need to attach a function to `app.config.optionMergeStrategies`:
+Quando as opções personalizadas são mescladas, elas usam a estratégia padrão que substitui o valor existente. Se você deseja que uma opção personalizada seja mesclada usando uma lógica personalizada, você precisa anexar uma função à `app.config.optionMergeStrategies`:
```js
const app = Vue.createApp({})
app.config.optionMergeStrategies.customOption = (toVal, fromVal) => {
- // return mergedVal
+ // retorna valorMesclado (mergedVal)
}
```
-The merge strategy receives the value of that option defined on the parent and child instances as the first and second arguments, respectively. Let's try to check what do we have in these parameters when we use a mixin:
+A estratégia de mesclagem recebe o valor dessa opção definida nas instâncias pai e filho como o primeiro e segundo argumentos, respectivamente. Vamos tentar verificar o que temos nesses parâmetros quando usamos um _mixin_:
```js
const app = Vue.createApp({
- custom: 'hello!'
+ custom: 'Olá!'
})
app.config.optionMergeStrategies.custom = (toVal, fromVal) => {
console.log(fromVal, toVal)
- // => "goodbye!", undefined
- // => "hello", "goodbye!"
+ // => "Tchau!", undefined
+ // => "Olá", "Tchau!"
return fromVal || toVal
}
app.mixin({
- custom: 'goodbye!',
+ custom: 'Tchau!',
created() {
- console.log(this.$options.custom) // => "hello!"
+ console.log(this.$options.custom) // => "Olá!"
}
})
```
-As you can see, in the console we have `toVal` and `fromVal` printed first from the mixin and then from the `app`. We always return `fromVal` if it exists, that's why `this.$options.custom` is set to `hello!` in the end. Let's try to change a strategy to _always return a value from the child instance_:
+Como você pode ver, no console temos `toVal` e `fromVal` impresso primeiro no _mixin_ e depois no `app`. Nós sempre retornamos `fromVal` se existir, é por isso que `this.$options.custom` está configurado para `hello!` no final. Vamos tentar mudar uma estratégia para _sempre retornar um valor da instância filha_:
```js
const app = Vue.createApp({
- custom: 'hello!'
+ custom: 'Olá!'
})
app.config.optionMergeStrategies.custom = (toVal, fromVal) => toVal || fromVal
app.mixin({
- custom: 'goodbye!',
+ custom: 'Tchau!',
created() {
- console.log(this.$options.custom) // => "goodbye!"
+ console.log(this.$options.custom) // => "Tchau!"
}
})
```
-## Drawbacks
+## Desvantagens
-In Vue 2, mixins were the primary tool to abstract parts of component logic into reusable chunks. However, they have a few issues:
+No Vue 2, os _mixins_ eram a principal ferramenta para abstrair partes da lógica de componentes em blocos reutilizáveis. No entanto, eles têm alguns problemas:
-- Mixins are conflict-prone: Since properties from each mixin are merged into the same component, you still have to know about every other mixin to avoid property name conflicts.
+- _Mixins_ são propensos à conflitos: como as propriedades de cada _mixin_ são mescladas no mesmo componente, você ainda precisa conhecer todos os outros _mixins_ para evitar conflitos de nome de propriedade e para depuração.
-- Properties seem to appear from nowhere: If a component uses multiple mixins it isn't necessarily obvious which properties came from which mixin.
+- As propriedades parecem surgir do nada: se um componente usa vários _mixins_, não é necessariamente óbvio quais propriedades vieram de cada _mixin_.
-- Reusability is limited: we cannot pass any parameters to the mixin to change its logic, which reduces their flexibility in terms of abstracting logic.
+- Reutilização é limitada: não podemos passar nenhum parâmetro ao _mixin_ para alterar sua lógica, o que reduz sua flexibilidade em termos de abstração da lógica.
-To address these issues, we added a new way to organize code by logical concerns: the [Composition API](composition-api-introduction.html).
+Para resolver esses problemas, adicionamos uma nova maneira de organizar o código por questões lógicas: A [API de Composição](composition-api-introduction.html).
diff --git a/src/guide/mobile.md b/src/guide/mobile.md
index 8ed7e3e34c..fdc60ae7b8 100644
--- a/src/guide/mobile.md
+++ b/src/guide/mobile.md
@@ -1,23 +1,23 @@
-# Mobile
+# Desenvolvimento Mobile
-## Introduction
+## Introdução
-While Vue.js does not natively support mobile app development, there are a number of solutions for creating native iOS and Android apps with Vue.js.
+Embora Vue.js não suporte o desenvolvimento de aplicativos mobile nativamente, há uma série de soluções para a criação de aplicativos iOS e Android nativos com Vue.js.
-## Hybrid-App Development
+## Desenvolvimento de Aplicativos Híbridos
### Capacitor
-[Capacitor](https://capacitorjs.com/) is a project from the [Ionic Team](https://ionic.io/) that allows developers to build native iOS, Android, and PWA apps with a single codebase by providing an API that can be run across multiple platforms.
+[Capacitor](https://capacitorjs.com/) é um projeto do [time de desenvolvimento Ionic](https://ionic.io/) que permite que desenvolvedores construam aplicativos iOS, Android e PWA nativos com um único código base, fornecendo uma API que pode ser executada em múltiplas plataformas.
-**Resources**
+**Recursos**
-- [Capacitor + Vue.js Guide](https://capacitorjs.com/solution/vue)
+- [Guia para Capacitor + Vue.js](https://capacitorjs.com/solution/vue)
### NativeScript
-[NativeScript](https://www.nativescript.org) powers cross-platform (truly native) mobile apps, using the web skills you already know. Combined they are a fantastic pair for developing immersive mobile experiences.
+[NativeScript](https://www.nativescript.org) possibilita aplicativos mobile multiplataforma (verdadeiramente nativos), utilizando as habilidades de desenvolvimento _web_ que você já conhece. Combinados, eles formam um par fantástico para desenvolver experiências móveis imersivas.
-**Resources**
+**Recursos**
-- [NativeScript + Vue.js Guide](https://nativescript-vue.org/)
+- [Guia para NativeScript + Vue.js](https://nativescript-vue.org/)
diff --git a/src/guide/optimizations.md b/src/guide/optimizations.md
index b5f6d62e65..29f02a156c 100644
--- a/src/guide/optimizations.md
+++ b/src/guide/optimizations.md
@@ -1,17 +1,17 @@
-# Rendering Mechanisms and Optimizations
+# Mecanismos de Renderização e Otimização
-> This page is not required reading in order to learn how to use Vue well, but it provides more information, should you be curious how rendering works under the hood.
+> Essa página não é uma leitura necessária para aprender como usar o Vue de forma correta, mas fornece mais informações, caso você fique curioso em como o trabalho de renderização funciona por debaixo do capô.
-## Virtual DOM
+## DOM Virtual
-Now that we know how watchers are updating the components, you might ask how those changes eventually make it to the DOM! Perhaps you’ve heard of the Virtual DOM before, many frameworks including Vue use this paradigm to make sure our interfaces reflect the changes we’re updating in JavaScript effectively
+Agora que nós sabemos como os observadores atualizam os componentes, você deve se perguntar como essas mudanças eventualmente alteram o DOM! Possivelmente você já ouviu falar sobre o DOM Virtual anteriormente, muitos *frameworks* inclusive o Vue usam esse paradigma para ter certeza que suas interfaces refletem as alterações que nós atualizamos no JavaScript efetivamente.
-
-
+
+
-We make a copy of the DOM in JavaScript called the Virtual DOM, we do this because touching the DOM with JavaScript is computationally expensive. While performing updates in JavaScript is cheap, finding the required DOM nodes and updating them with JavaScript is expensive. So we batch calls, and change the DOM all at once.
+Nós fazemos uma cópia do DOM no JavaScript chamada DOM Virtual, nós fazemos isso porque alterar o DOM com JavaScript é computacionalmente caro. Enquanto efetuar atualizações no JavaScript é barato, encontrando os nós necessários do DOM e os atualizando com JavaScript é caro. Então nós colocamos as chamadas em lote, e fazemos a mudança no DOM todas de uma única vez.
-The Virtual DOM is a lightweight JavaScript object, created by a render function. It takes three arguments: the element, an object with data, props, attrs and more, and an array. The array is where we pass in the children, which have all these arguments too, and then they can have children and so on, until we build a full tree of elements.
+O DOM Virtual é um leve objeto em JavaScript, criado pela função de renderização. Ele recebe três argumentos: o elemento, o objeto com a informação, propriedades, atributos e mais, e uma Array. A Array é onde nós passamos o filho, no qual tem todos esses argumentos também, e então eles podem ter filhos e assim por diante, até que nós criamos uma árvore cheia de elementos.
-If we need to update the list items, we do so in JavaScript, using the reactivity we mentioned earlier. We then make all the changes to the JavaScript copy, the virtual DOM, and perform a diff between this and the actual DOM. Only then do we make our updates to just what has changed. The Virtual DOM allows us to make performant updates to our UIs!
+Se nós precisarmos atualizar a lista de itens, nós também fazemos no JavaScript, utilizando a reatividade que mencionamos anteriormente. Nós fazemos todas as alterações na cópia do JavaScript, o DOM Virtual, e executamos a diferença entre esse e o DOM atual. Apenas então, fazemos nossas atualizações apenas no que foi alterado. O DOM Virtual nos permite fazer atualizações performáticas em nossas interfaces de usuário (UIs)!.
diff --git a/src/guide/plugins.md b/src/guide/plugins.md
index aa3b44f847..6736196af3 100644
--- a/src/guide/plugins.md
+++ b/src/guide/plugins.md
@@ -1,39 +1,39 @@
# Plugins
-Plugins are self-contained code that usually add global-level functionality to Vue. It is either an `object` that exposes an `install()` method, or a `function`.
+_Plugins_ são códigos autocontidos que geralmente adicionam funcionalidade de nível global ao Vue. É um `object` que expõe um método `install()` ou uma `function`.
-There is no strictly defined scope for a plugin, but common scenarios where plugins are useful include:
+Não há escopo estritamente definido para um _plugin_, mas os cenários comuns em que os _plugins_ são úteis incluem:
-1. Add some global methods or properties, e.g. [vue-custom-element](https://github.com/karol-f/vue-custom-element).
+1. Adicionar alguns métodos e propriedades globais (Ex.: [vue-custom-element](https://github.com/karol-f/vue-custom-element)).
-2. Add one or more global assets: directives/transitions etc. (e.g. [vue-touch](https://github.com/vuejs/vue-touch)).
+2. Adicionar um ou mais recursos globais: diretivas/transições etc. (Ex.: [vue-touch](https://github.com/vuejs/vue-touch)).
-3. Add some component options by global mixin (e.g. [vue-router](https://github.com/vuejs/vue-router)).
+3. Adicionar algumas opções de componente via _mixin_ global. (Ex.: [vue-router](https://github.com/vuejs/vue-router)).
-4. Add some global instance methods by attaching them to `config.globalProperties`.
+4. Adicionar alguns métodos de instância globais, anexando-os a `config.globalProperties`.
-5. A library that provides an API of its own, while at the same time injecting some combination of the above (e.g. [vue-router](https://github.com/vuejs/vue-router)).
+5. Uma biblioteca que fornece uma API própria, que ao mesmo tempo injeta alguma combinação dos anteriores. (Ex.: [vue-router](https://github.com/vuejs/vue-router)).
-## Writing a Plugin
+## Escrevendo um Plugin
-In order to better understand how to create your own Vue.js plugins, we will create a very simplified version of a plugin that displays `i18n` ready strings.
+Para entender melhor como criar seus próprios _plugins_ Vue.js, criaremos uma versão muito simplificada de um _plugin_ que exibe strings prontas para `i18n`.
-Whenever this plugin is added to an application, the `install` method will be called if it is an object. If it is a `function`, the function itself will be called. In both cases, it will receive two parameters - the `app` object resulting from Vue's `createApp`, and the options passed in by the user.
+Sempre que este _plugin_ for adicionado a uma aplicação, o método `install` será chamado se for um objeto. Se for uma `function`, a própria função será chamada. Em ambos os casos, ele receberá dois parâmetros - o objeto `app` resultante do `createApp` do Vue, e as opções passadas pelo usuário.
-Let's begin by setting up the plugin object. It is recommended to create it in a separate file and export it, as shown below to keep the logic contained and separate.
+Vamos começar configurando o objeto do _plugin_. Recomenda-se criá-lo em um arquivo separado e exportá-lo, conforme mostrado a seguir, para manter a lógica contida e separada.
```js
// plugins/i18n.js
export default {
install: (app, options) => {
- // Plugin code goes here
+ // O código do plugin vai aqui
}
}
```
-We want to make a function to translate keys available to the whole application, so we will expose it using `app.config.globalProperties`.
+Queremos fazer uma função para traduzir as chaves disponíveis para toda a aplicação, então vamos expô-la usando `app.config.globalProperties`.
-This function will receive a `key` string, which we will use to look up the translated string in the user-provided options.
+Esta função receberá uma _string_ `key`, que usaremos para pesquisar a _string_ traduzida nas opções fornecidas pelo usuário.
```js
// plugins/i18n.js
@@ -48,9 +48,9 @@ export default {
}
```
-We will assume that our users will pass in an object containing the translated keys in the `options` parameter when they use the plugin. Our `$translate` function will take a string such as `greetings.hello`, look inside the user provided configuration and return the translated value - in this case, `Bonjour!`
+Assumiremos que nossos usuários passarão um objeto contendo as chaves traduzidas no parâmetro `options` quando usarem o _plugin_. Nossa função `$translate` pegará uma _string_ como `greetings.hello`, olhará dentro da configuração fornecida pelo usuário e vai retornar o valor traduzido - neste caso, `Bonjour!`
-Ex:
+Ex.:
```js
greetings: {
@@ -58,7 +58,7 @@ greetings: {
}
```
-Plugins also allow us to use `inject` to provide a function or attribute to the plugin's users. For example, we can allow the application to have access to the `options` parameter to be able to use the translations object.
+Os _plugins_ também nos permitem usar `inject` para fornecer uma função ou atributo aos usuários do _plugin_. Por exemplo, podemos permitir que a aplicação tenha acesso ao parâmetro `options` para poder usar o objeto de traduções.
```js
// plugins/i18n.js
@@ -75,9 +75,9 @@ export default {
}
```
-Plugin users will now be able to `inject['i18n']` into their components and access the object.
+Os usuários do _plugin_ agora serão capazes de fazer `inject['i18n']` em seus componentes e acessar o objeto.
-Additionally, since we have access to the `app` object, all other capabilities like using `mixin` and `directive` are available to the plugin. To learn more about `createApp` and the application instance, check out the [Application API documentation](/api/application-api.html).
+Além disso, como temos acesso ao objeto `app`, todos os outros recursos como o uso de `mixin` e `directive` estão disponíveis para o _plugin_. Para aprender mais sobre `createApp` e a instância do aplicativo, verifique a [documentação da API da Aplicação](/api/application-api.html).
```js
// plugins/i18n.js
@@ -92,14 +92,14 @@ export default {
app.directive('my-directive', {
mounted (el, binding, vnode, oldVnode) {
- // some logic ...
+ // alguma lógica...
}
...
})
app.mixin({
created() {
- // some logic ...
+ // alguma lógica...
}
...
})
@@ -107,20 +107,20 @@ export default {
}
```
-## Using a Plugin
+## Usando um Plugin
-After a Vue app has been initialized with `createApp()`, you can add a plugin to your application by calling the `use()` method.
+Depois que um aplicativo Vue foi inicializado com `createApp()`, você pode adicionar um _plugin_ ao seu aplicativo chamando o método `use()`.
-We will use the `i18nPlugin` we created in the [Writing a Plugin](#writing-a-plugin) section for demo purposes.
+Usaremos o `i18nPlugin` que criamos na seção [Escrevendo um Plugin](#escrevendo-um-plugin) para fins de demonstração.
-The `use()` method takes two parameters. The first one is the plugin to be installed, in this case `i18nPlugin`.
+O método `use()` recebe dois parâmetros. O primeiro é o _plugin_ a ser instalado, neste caso `i18nPlugin`.
-It also automatically prevents you from using the same plugin more than once, so calling it multiple times on the same plugin will install the plugin only once.
+Ele também impede automaticamente que você use o mesmo _plugin_ mais de uma vez, portanto, chamá-lo várias vezes no mesmo _plugin_ instalará o _plugin_ apenas uma vez.
-The second parameter is optional, and depends on each particular plugin. In the case of the demo `i18nPlugin`, it is an object with the translated strings.
+O segundo parâmetro é opcional e depende de cada _plugin_ específico. No caso do demo `i18nPlugin`, é um objeto com as _strings_ traduzidas.
:::info
-If you are using third party plugins such as `Vuex` or `Vue Router`, always check the documentation to know what that particular plugin expects to receive as a second parameter.
+Se você estiver usando _plugins_ de terceiros, como `Vuex` ou `Vue Router`, sempre verifique a documentação para saber o que aquele _plugin_ específico espera receber como um segundo parâmetro.
:::
```js
@@ -139,4 +139,4 @@ app.use(i18nPlugin, i18nStrings)
app.mount('#app')
```
-Checkout [awesome-vue](https://github.com/vuejs/awesome-vue#components--libraries) for a huge collection of community-contributed plugins and libraries.
+Verifique [awesome-vue](https://github.com/vuejs/awesome-vue#components--libraries) para uma enorme coleção de _plugins_ e bibliotecas disponibilizados pela comunidade.
diff --git a/src/guide/reactivity-computed-watchers.md b/src/guide/reactivity-computed-watchers.md
index b1860b03ef..f915eca332 100644
--- a/src/guide/reactivity-computed-watchers.md
+++ b/src/guide/reactivity-computed-watchers.md
@@ -1,10 +1,10 @@
-# Computed and Watch
+# Dados Computados e Observadores
-> This section uses [single-file component](single-file-component.html) syntax for code examples
+> Esta seção usa a sintaxe de [componente de single-file](single-file-component.html) para exemplos de código
-## Computed values
+## Valores computados
-Sometimes we need state that depends on other state - in Vue this is handled with component [computed properties](computed.html#computed-properties). To directly create a computed value, we can use the `computed` function: it takes a getter function and returns an immutable reactive [ref](reactivity-fundamentals.html#creating-standalone-reactive-values-as-refs) object for the returned value from the getter.
+Às vezes precisamos de um estado que depende de outro estado - no Vue isso é tratado com [dados computados](computed.html#computed-properties) do componente. Para criar diretamente um valor computado, podemos usar a função `computed`: ela pega uma função _getter_ e retorna um objeto reativo imutável [ref](reactivity-fundamentals.html#criacao-de-valores-reativos-avulsos-como-refs) para o valor retornado do _getter_.
```js
const count = ref(1)
@@ -12,10 +12,10 @@ const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
-plusOne.value++ // error
+plusOne.value++ // erro
```
-Alternatively, it can take an object with `get` and `set` functions to create a writable ref object.
+Alternativamente, ele pode receber um objeto com as funções `get` e `set` para criar um objeto _ref_ modificável.
```js
const count = ref(1)
@@ -30,102 +30,102 @@ plusOne.value = 1
console.log(count.value) // 0
```
-### Computed Debugging
+### Depuração de Computados
-`computed` accepts a second argument with `onTrack` and `onTrigger` options:
+`computed` aceita um segundo argumento com as opções `onTrack` e `onTrigger`:
-- `onTrack` will be called when a reactive property or ref is tracked as a dependency.
-- `onTrigger` will be called when the watcher callback is triggered by the mutation of a dependency.
+- `onTrack` será chamado quando uma propriedade reativa ou _ref_ for rastreada como uma dependência.
+- `onTrigger` será chamado quando o _callback_ do observador for acionado pela mutação de uma dependência.
-Both callbacks will receive a debugger event which contains information on the dependency in question. It is recommended to place a `debugger` statement in these callbacks to interactively inspect the dependency:
+Ambos os _callbacks_ receberão um evento depurador que contém informações sobre a dependência em questão. Recomenda-se colocar uma instrução `debugger` nesses _callbacks_ para inspecionar interativamente a dependência:
```js
const plusOne = computed(() => count.value + 1, {
onTrack(e) {
- // triggered when count.value is tracked as a dependency
+ // acionado quando count.value é rastreado como uma dependência
debugger
},
onTrigger(e) {
- // triggered when count.value is mutated
+ // acionado quando count.value é modificado
debugger
}
})
-// access plusOne, should trigger onTrack
+// acessa plusOne, deve acionar onTrack
console.log(plusOne.value)
-// mutate count.value, should trigger onTrigger
+// muda count.value, deve acionar onTrigger
count.value++
```
-`onTrack` and `onTrigger` only work in development mode.
+`onTrack` e `onTrigger` só funcionam no modo de desenvolvimento.
## `watchEffect`
-To apply and _automatically re-apply_ a side effect based on reactive state, we can use the `watchEffect` function. It runs a function immediately while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.
+Para aplicar e _automaticamente reaplicar_ um efeito colateral baseado no estado reativo, podemos usar a função `watchEffect`. Ela executa uma função imediatamente enquanto rastreia de forma reativa suas dependências e a executa novamente sempre que as dependências são alteradas.
```js
const count = ref(0)
watchEffect(() => console.log(count.value))
-// -> logs 0
+// -> loga 0
setTimeout(() => {
count.value++
- // -> logs 1
+ // -> loga 1
}, 100)
```
-### Stopping the Watcher
+### Parando o Observador
-When `watchEffect` is called during a component's [setup()](composition-api-setup.html) function or [lifecycle hooks](composition-api-lifecycle-hooks.html), the watcher is linked to the component's lifecycle and will be automatically stopped when the component is unmounted.
+Quando `watchEffect` é chamado durante a função [setup()](composition-api-setup.html) de um componente ou [gatilhos do ciclo de vida](composition-api-lifecycle-hooks.html), o observador é vinculado ao ciclo de vida do componente e será interrompido automaticamente quando o componente for desmontado.
-In other cases, it returns a stop handle which can be called to explicitly stop the watcher:
+Em outros casos, ele retorna um manipulador de parada que pode ser chamado para parar explicitamente o observador:
```js
const stop = watchEffect(() => {
/* ... */
})
-// later
+// depois
stop()
```
-### Side Effect Invalidation
+### Invalidação de Efeito Colateral
-Sometimes the watched effect function will perform asynchronous side effects that need to be cleaned up when it is invalidated (i.e. state changed before the effects can be completed). The effect function receives an `onInvalidate` function that can be used to register an invalidation callback. This invalidation callback is called when:
+Às vezes, a função do efeito observado executará efeitos colaterais assíncronos que precisam ser limpos quando forem invalidados (ou seja, estado alterado antes que os efeitos possam ser concluídos). A função de efeito recebe uma função `onInvalidate` que pode ser usada para registrar um _callback_ de invalidação. Esse _callback_ de invalidação é chamado quando:
-- the effect is about to re-run
-- the watcher is stopped (i.e. when the component is unmounted if `watchEffect` is used inside `setup()` or lifecycle hooks)
+- o efeito está prestes a ser executado novamente
+- o observador é parado (ou seja, quando o componente é desmontado se `watchEffect` for usado dentro de `setup()` ou gatilhos de ciclo de vida)
```js
watchEffect(onInvalidate => {
const token = performAsyncOperation(id.value)
onInvalidate(() => {
- // id has changed or watcher is stopped.
- // invalidate previously pending async operation
+ // id foi alterado ou o observador está parado.
+ // invalida a operação assíncrona pendente anteriormente
token.cancel()
})
})
```
-We are registering the invalidation callback via a passed-in function instead of returning it from the callback because the return value is important for async error handling. It is very common for the effect function to be an async function when performing data fetching:
+Estamos registrando o _callback_ de invalidação por meio de uma função passada em vez de retorná-lo do _callback_ porque o valor retornado é importante para o tratamento de erros assíncronos. É muito comum que a função de efeito seja uma função assíncrona ao realizar a requisição de dados:
```js
const data = ref(null)
watchEffect(async onInvalidate => {
onInvalidate(() => {
/* ... */
- }) // we register cleanup function before Promise resolves
+ }) // registramos a função de limpeza antes que a Promise seja resolvida
data.value = await fetchData(props.id)
})
```
-An async function implicitly returns a Promise, but the cleanup function needs to be registered immediately before the Promise resolves. In addition, Vue relies on the returned Promise to automatically handle potential errors in the Promise chain.
+Uma função assíncrona retorna implicitamente uma Promise, mas a função de limpeza precisa ser registrada imediatamente antes que a Promise seja resolvida. Além disso, o Vue depende da Promise retornada para lidar automaticamente com possíveis erros na cadeia de Promises.
-### Effect Flush Timing
+### Momento de Limpeza do Efeito
-Vue's reactivity system buffers invalidated effects and flushes them asynchronously to avoid unnecessary duplicate invocation when there are many state mutations happening in the same "tick". Internally, a component's `update` function is also a watched effect. When a user effect is queued, it is by default invoked **before** all component `update` effects:
+O sistema de reatividade do Vue armazena em _buffer_ os efeitos invalidados e os libera de forma assíncrona para evitar invocação duplicada desnecessária quando há muitas mutações de estado acontecendo no mesmo "tick". Internamente, a função `update` de um componente também é um efeito observado. Quando um efeito de usuário é enfileirado, ele é invocado por padrão **antes** de todos os efeitos de `update` do componente:
```vue
@@ -149,17 +149,17 @@ export default {
```
-In this example:
+Neste exemplo:
-- The count will be logged synchronously on initial run.
-- When `count` is mutated, the callback will be called **before** the component has updated.
+- A contagem será registrada de forma síncrona na execução inicial.
+- Quando `count` for modificado, o callback será chamado **antes** de o componente ser atualizado.
-In cases where a watcher effect needs to be re-run **after** component updates (i.e. when working with [Template Refs](./composition-api-template-refs.md#watching-template-refs)), we can pass an additional `options` object with the `flush` option (default is `'pre'`):
+Nos casos em que um efeito de observador precisa ser executado novamente **após** atualizações de componentes (ou seja, ao trabalhar com [_Refs_ de _Template_](./composition-api-template-refs.md#observando-refs-de-template)), nós podemos passar um objeto `options` adicional com a opção `flush` (o padrão é `'pre'`):
```js
-// fire after component updates so you can access the updated DOM
-// Note: this will also defer the initial run of the effect until the
-// component's first render is finished.
+// dispara após atualizações de componentes para que você possa acessar o DOM atualizado
+// Nota: isso também adiará a execução inicial do efeito até
+// a primeira renderização do componente ser finalizada.
watchEffect(
() => {
/* ... */
@@ -170,23 +170,23 @@ watchEffect(
)
```
-The `flush` option also accepts `'sync'`, which forces the effect to always trigger synchronously. This is however inefficient and should be rarely needed.
+A opção `flush` também aceita `'sync'`, o que força o efeito a sempre disparar de forma síncrona. No entanto, isso é ineficiente e raramente deve ser necessário.
-In Vue >= 3.2.0, `watchPostEffect` and `watchSyncEffect` aliases can also be used to make the code intention more obvious.
+No Vue >= 3.2.0, os apelidos `watchPostEffect` e `watchSyncEffect` também podem ser usados para tornar a intenção do código mais óbvia.
-### Watcher Debugging
+### Depuração do Observador
-The `onTrack` and `onTrigger` options can be used to debug a watcher's behavior.
+As opções `onTrack` e `onTrigger` podem ser usadas para depurar o comportamento de um observador.
-- `onTrack` will be called when a reactive property or ref is tracked as a dependency.
-- `onTrigger` will be called when the watcher callback is triggered by the mutation of a dependency.
+- `onTrack` será chamado quando uma propriedade reativa ou _ref_ for rastreada como uma dependência.
+- `onTrigger` será chamado quando o _callback_ do observador for acionado pela mutação de uma dependência.
-Both callbacks will receive a debugger event which contains information on the dependency in question. It is recommended to place a `debugger` statement in these callbacks to interactively inspect the dependency:
+Ambos os _callbacks_ receberão um evento depurador que contém informações sobre a dependência em questão. Recomenda-se colocar uma instrução `debugger` nesses _callbacks_ para inspecionar interativamente a dependência:
```js
watchEffect(
() => {
- /* side effect */
+ /* efeito colateral */
},
{
onTrigger(e) {
@@ -196,24 +196,24 @@ watchEffect(
)
```
-`onTrack` and `onTrigger` only work in development mode.
+`onTrack` e `onTrigger` só funcionam no modo de desenvolvimento.
## `watch`
-The `watch` API is the exact equivalent of the component [watch](computed.html#watchers) property. `watch` requires watching a specific data source and applies side effects in a separate callback function. It also is lazy by default - i.e. the callback is only called when the watched source has changed.
+A API `watch` é o equivalente exato da propriedade [watch](computed.html#observadores) do componente. `watch` requer a observação de uma fonte de dados específica e aplica efeitos colaterais em um _callback_ separado. Também é preguiçoso por padrão - ou seja, o _callback_ só é chamado quando a fonte observada foi alterada.
-- Compared to [watchEffect](#watcheffect), `watch` allows us to:
+- Comparado com [watchEffect](#watcheffect), `watch` nos permite:
- - Perform the side effect lazily;
- - Be more specific about what state should trigger the watcher to re-run;
- - Access both the previous and current value of the watched state.
+ - Executar o efeito colateral preguiçosamente;
+ - Ser mais específico sobre qual estado deve acionar o observador para executar novamente;
+ - Acessar o valor anterior e atual do estado observado.
-### Watching a Single Source
+### Observando uma Única Fonte
-A watcher data source can either be a getter function that returns a value, or directly a `ref`:
+Uma fonte de dados do observador pode ser uma função _getter_ que retorna um valor ou diretamente um `ref`:
-```js
-// watching a getter
+``` js
+// observando um getter
const state = reactive({ count: 0 })
watch(
() => state.count,
@@ -222,16 +222,16 @@ watch(
}
)
-// directly watching a ref
+// observando diretamente um ref
const count = ref(0)
watch(count, (count, prevCount) => {
/* ... */
})
```
-### Watching Multiple Sources
+### Observando Várias Fontes
-A watcher can also watch multiple sources at the same time using an array:
+Um observador também pode observar várias fontes ao mesmo tempo usando um array:
```js
const firstName = ref('')
@@ -245,7 +245,7 @@ firstName.value = 'John' // logs: ["John", ""] ["", ""]
lastName.value = 'Smith' // logs: ["John", "Smith"] ["John", ""]
```
-However, if you are changing both watched sources simultaneously in the same function, the watcher will be executed only once:
+No entanto, se você estiver alterando as duas fontes observadas simultaneamente na mesma função, o observador será executado apenas uma vez:
```js{9-13}
setup() {
@@ -266,9 +266,9 @@ setup() {
}
```
-Note that multiple synchronous changes will only trigger the watcher once.
+Observe que várias alterações síncronas acionarão o observador apenas uma vez.
-It is possible to force the watcher to trigger after every change by using the setting `flush: 'sync'`, though that isn't usually recommended. Alternatively, [nextTick](/api/global-api.html#nexttick) can be used to wait for the watcher to run before making further changes. e.g.:
+É possível forçar o observador a disparar após cada mudança usando a configuração `flush: 'sync'`, embora isso geralmente não seja recomendado. Como alternativa, [nextTick](/api/global-api.html#nexttick) pode ser usado para aguardar a execução do observador antes de fazer outras alterações. por exemplo.:
```js
const changeValues = async () => {
@@ -278,9 +278,9 @@ const changeValues = async () => {
}
```
-### Watching Reactive Objects
+### Observando Objetos Reativos
-Using a watcher to compare values of an array or object that are reactive requires that it has a copy made of just the values.
+Usar um observador para comparar valores de um array ou objeto que são reativos requer que ele tenha uma cópia feita apenas dos valores.
```js
const numbers = reactive([1, 2, 3, 4])
@@ -295,7 +295,7 @@ watch(
numbers.push(5) // logs: [1,2,3,4,5] [1,2,3,4]
```
-Attempting to check for changes of properties in a deeply nested object or array will still require the `deep` option to be true:
+A tentativa de verificar alterações de propriedades em um objeto ou array profundamente aninhado ainda exigirá que a opção `deep` seja verdadeira:
```js
const state = reactive({
@@ -320,10 +320,10 @@ watch(
{ deep: true }
)
-state.attributes.name = 'Alex' // Logs: "deep" "Alex" "Alex"
+state.attributes.name = 'Alex' // Loga: "deep" "Alex" "Alex"
```
-However, watching a reactive object or array will always return a reference to the current value of that object for both the current and previous value of the state. To fully watch deeply nested objects and arrays, a deep copy of values may be required. This can be achieved with a utility such as [lodash.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)
+No entanto, observar um objeto ou array reativo sempre retornará uma referência ao valor atual desse objeto para ambos o valor atual e anterior do estado. Para observar completamente objetos e arrays profundamente aninhados, pode ser necessária uma cópia profunda dos valores. Isso pode ser feito com um utilitário como [lodash.cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep)
```js
import _ from 'lodash'
@@ -342,9 +342,9 @@ watch(
}
)
-state.attributes.name = 'Alex' // Logs: "Alex" ""
+state.attributes.name = 'Alex' // Loga: "Alex" ""
```
-### Shared Behavior with `watchEffect`
+### Comportamento Compartilhado com `watchEffect`
-`watch` shares behavior with [`watchEffect`](#watcheffect) in terms of [manual stoppage](#stopping-the-watcher), [side effect invalidation](#side-effect-invalidation) (with `onInvalidate` passed to the callback as the 3rd argument instead), [flush timing](#effect-flush-timing) and [debugging](#watcher-debugging).
+`watch` compartilha comportamento com [`watchEffect`](#watcheffect) em termos de [parada manual](#parando-o-observador), [invalidação de efeito colateral](#invalidacao-de-efeito-colateral) (com `onInvalidate` passado ao _callback_ como o terceiro argumento), [momento de limpeza](#momento-de-limpeza-do-efeito) e [depuração](#depuracao-do-observador).
diff --git a/src/guide/reactivity-fundamentals.md b/src/guide/reactivity-fundamentals.md
index bbaef88a95..6f8eb7f5e8 100644
--- a/src/guide/reactivity-fundamentals.md
+++ b/src/guide/reactivity-fundamentals.md
@@ -1,31 +1,31 @@
-# Reactivity Fundamentals
+# Fundamentos da Reatividade
-> This section uses [single-file component](single-file-component.html) syntax for code examples
+> Esta seção usa a sintaxe de [componente single-file](single-file-component.html) para exemplos de código
-## Declaring Reactive State
+## Declarando Estado Reativo
-To create a reactive state from a JavaScript object, we can use a `reactive` method:
+Para criar um estado reativo a partir de um objeto JavaScript, podemos usar o método `reactive`:
```js
import { reactive } from 'vue'
-// reactive state
+// estado reativo
const state = reactive({
count: 0
})
```
-`reactive` is the equivalent of the `Vue.observable()` API in Vue 2.x, renamed to avoid confusion with RxJS observables. Here, the returned state is a reactive object. The reactive conversion is "deep" - it affects all nested properties of the passed object.
+`reactive` é equivalente à API `Vue.observable()` do Vue 2.x, renomeado para evitar confusões com os `Observables` do RxJS. Aqui, o estado retornado é um objeto reativo. A conversão reativa é "profunda" - ela afeta todas as propriedades aninhadas do objeto passado.
-The essential use case for reactive state in Vue is that we can use it during render. Thanks to dependency tracking, the view automatically updates when reactive state changes.
+O caso de uso essencial para o estado reativo no Vue é que podemos usá-lo durante a renderização. Graças ao rastreamento de dependência, a exibição é atualizada automaticamente quando o estado reativo muda.
-This is the very essence of Vue's reactivity system. When you return an object from `data()` in a component, it is internally made reactive by `reactive()`. The template is compiled into a [render function](render-function.html) that makes use of these reactive properties.
+Esta é a própria essência do sistema de reatividade do Vue. Quando você retorna um objeto de `data()` em um componente, ele é tornado reativo internamente pelo `reactive()`. O _template_ é compilado em uma [função de renderização](render-function.html) que faz uso dessas propriedades reativas.
-You can learn more about `reactive` in the [Basic Reactivity API's](../api/basic-reactivity.html) section
+Você pode aprender mais sobre `reactive` na seção [Básico da API de Reatividade](../api/basic-reactivity.html)
-## Creating Standalone Reactive Values as `refs`
+## Criação de Valores Reativos Avulsos como `refs`
-Imagine the case where we have a standalone primitive value (for example, a string) and we want to make it reactive. Of course, we could make an object with a single property equal to our string, and pass it to `reactive`. Vue has a method that will do the same for us - it's a `ref`:
+Imagine o caso em que temos um valor primitivo avulso (por exemplo, uma string) e queremos torná-la reativa. Claro, poderíamos fazer um objeto com uma única propriedade igual à nossa string e passá-la para `reactive`. Vue tem um método que fará o mesmo para nós - ele é o `ref`:
```js
import { ref } from 'vue'
@@ -33,7 +33,7 @@ import { ref } from 'vue'
const count = ref(0)
```
-`ref` will return a reactive and mutable object that serves as a reactive **ref**erence to the internal value it is holding - that's where the name comes from. This object contains the only one property named `value`:
+`ref` retornará um objeto reativo e mutável que serve como uma **ref**erência reativa para o valor interno que está mantendo - é daí que vem o seu nome. Este objeto contém uma única propriedade chamada `value`:
```js
import { ref } from 'vue'
@@ -45,16 +45,16 @@ count.value++
console.log(count.value) // 1
```
-### Ref Unwrapping
+### Ref Desempacotada
-When a ref is returned as a property on the render context (the object returned from [setup()](composition-api-setup.html)) and accessed in the template, it automatically shallow unwraps the inner value. Only the nested ref will require `.value` in the template:
+Quando um `ref` é retornado como uma propriedade no contexto de renderização (o objeto retornado de [setup()](composition-api-setup.html)) e acessado no _template_, ele automaticamente se desempacota rasamente para o valor interno. Apenas o ref aninhado exigirá `.value` no _template_:
```vue-html
{{ count }}
- Increment count
- Nested Increment count
+ Incrementar contador
+ Incrementar contador aninhado
@@ -75,8 +75,8 @@ When a ref is returned as a property on the render context (the object returned
```
-:::tip
-If you don't want to access the actual object instance, you can wrap it in a `reactive`:
+:::tip Dica
+Se você não quiser acessar a instância do objeto real, pode envolvê-lo em um `reactive`:
```js
nested: reactive({
@@ -85,9 +85,9 @@ nested: reactive({
```
:::
-### Access in Reactive Objects
+### Acesso em Objetos Reativos
-When a `ref` is accessed or mutated as a property of a reactive object, it automatically unwraps to the inner value so it behaves like a normal property:
+Quando um `ref` é acessado ou alterado como uma propriedade de um objeto reativo, ele se desempacota automaticamente para o valor interno para que se comporte como uma propriedade normal:
```js
const count = ref(0)
@@ -101,7 +101,7 @@ state.count = 1
console.log(count.value) // 1
```
-If a new ref is assigned to a property linked to an existing ref, it will replace the old ref:
+Se uma nova `ref` for atribuída à uma propriedade vinculada à uma `ref` existente, ela substituirá a antiga ref:
```js
const otherCount = ref(2)
@@ -111,60 +111,60 @@ console.log(state.count) // 2
console.log(count.value) // 1
```
-Ref unwrapping only happens when nested inside a reactive `Object`. There is no unwrapping performed when the ref is accessed from an `Array` or a native collection type like [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
+O desempacotamento de um `ref` só acontece quando aninhado dentro de um `Object` reativo. Não há desempacotamento executado quando o `ref` é acessado de um `Array` ou um tipo de coleção nativo como [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
```js
-const books = reactive([ref('Vue 3 Guide')])
-// need .value here
+const books = reactive([ref('Guia do Vue 3')])
+// precisa usar .value aqui
console.log(books[0].value)
const map = reactive(new Map([['count', ref(0)]]))
-// need .value here
+// precisa usar .value aqui
console.log(map.get('count').value)
```
-## Destructuring Reactive State
+## Desestruturar Estado Reativo
-When we want to use a few properties of the large reactive object, it could be tempting to use [ES6 destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to get properties we want:
+Quando queremos usar algumas propriedades do grande objeto reativo, pode ser tentador usar [desestruturação do ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) para obter as propriedades que desejamos:
```js
import { reactive } from 'vue'
const book = reactive({
- author: 'Vue Team',
+ author: 'Equipe Vue',
year: '2020',
- title: 'Vue 3 Guide',
- description: 'You are reading this book right now ;)',
- price: 'free'
+ title: 'Guia do Vue 3',
+ description: 'Você está lendo esta documentação agora ;)',
+ price: 'grátis'
})
let { author, title } = book
```
-Unfortunately, with such a destructuring the reactivity for both properties would be lost. For such a case, we need to convert our reactive object to a set of refs. These refs will retain the reactive connection to the source object:
+Infelizmente, com tal desestruturação, a reatividade para ambas as propriedades seria perdida. Para tal, precisamos converter nosso objeto reativo em um conjunto de refs. Esses refs manterão a conexão reativa com o objeto de origem:
```js
import { reactive, toRefs } from 'vue'
const book = reactive({
- author: 'Vue Team',
+ author: 'Equipe Vue',
year: '2020',
- title: 'Vue 3 Guide',
- description: 'You are reading this book right now ;)',
- price: 'free'
+ title: 'Guia do Vue 3',
+ description: 'Você está lendo esta documentação agora ;)',
+ price: 'grátis'
})
let { author, title } = toRefs(book)
-title.value = 'Vue 3 Detailed Guide' // we need to use .value as title is a ref now
-console.log(book.title) // 'Vue 3 Detailed Guide'
+title.value = 'Guia detalhado do Vue 3' // precisamos usar .value porque `title` é uma `ref` agora
+console.log(book.title) // 'Guia detalhado do Vue 3'
```
-You can learn more about `refs` in the [Refs API](../api/refs-api.html#ref) section
+Você pode aprender mais sobre `refs` na seção [API de Refs](../api/refs-api.html#ref)
-## Prevent Mutating Reactive Objects with `readonly`
+## Evite Mutar Objetos Reativos com `readonly`
-Sometimes we want to track changes of the reactive object (`ref` or `reactive`) but we also want prevent changing it from a certain place of the application. For example, when we have a [provided](component-provide-inject.html) reactive object, we want to prevent mutating it where it's injected. To do so, we can create a readonly proxy to the original object:
+Às vezes, queremos rastrear as alterações do objeto reativo (`ref` ou` reactive`), mas também queremos evitar alterá-lo de um determinado local do aplicativo. Por exemplo, quando temos um objeto reativo [provido](component-provide-inject.html), queremos evitar a sua mutação onde ele é injetado. Para fazer isso, podemos criar um _proxy_ somente leitura (readonly) para o objeto original:
```js
import { reactive, readonly } from 'vue'
@@ -173,9 +173,9 @@ const original = reactive({ count: 0 })
const copy = readonly(original)
-// mutating original will trigger watchers relying on the copy
+// a mutação do original fará com que os observadores confiem na cópia
original.count++
-// mutating the copy will fail and result in a warning
+// alterar a cópia irá falhar e resultar em um aviso
copy.count++ // warning: "Set operation on key 'count' failed: target is readonly."
```
diff --git a/src/guide/reactivity.md b/src/guide/reactivity.md
index ba6ce6c3ee..cd926b6990 100644
--- a/src/guide/reactivity.md
+++ b/src/guide/reactivity.md
@@ -1,21 +1,21 @@
-# Reactivity in Depth
+# Aprofundando-se na Reatividade
-Now it’s time to take a deep dive! One of Vue’s most distinct features is the unobtrusive reactivity system. Models are proxied JavaScript objects. When you modify them, the view updates. It makes state management simple and intuitive, but it’s also important to understand how it works to avoid some common gotchas. In this section, we are going to dig into some of the lower-level details of Vue’s reactivity system.
+Agora é o momento de mergulhar fundo! Uma das características mais distintas do Vue é o seu discreto sistema de reatividade. Os modelos de dados são _proxies_ de objetos JavaScript. Quando você os modifica, a _view_ é atualizada. Isso faz com que a administração de estado seja simples e intuitiva, mas também é importante entender como isso funciona para evitar algumas pegadinhas. Nesta seção, vamos nos aprofundar em alguns dos detalhes de baixo nível do sistema de reatividade do Vue.
-Watch a free video on Reactivity in Depth on Vue Mastery
+Assista um vídeo gratuito sobre Aprofundando-se na Reatividade no Vue Mastery
-## What is Reactivity?
+## O Que é Reatividade?
-This term comes up in programming quite a bit these days, but what do people mean when they say it? Reactivity is a programming paradigm that allows us to adjust to changes in a declarative manner. The canonical example that people usually show, because it’s a great one, is an Excel spreadsheet.
+Esse termo aparece na programação com uma certa frequência atualmente, mas o que realmente significa quando as pessoas o dizem? Reatividade é um paradigma da programação que permite nos ajustarmos à mudanças de uma maneira declarativa. O exemplo canônico geralmente mostrado, por ser ótimo, é uma planilha do Excel.
- Your browser does not support the video tag.
+ Seu navegador não possui suporte para a tag video.
-If you put the number 2 in the first cell, and the number 3 in the second and asked for the SUM, the spreadsheet would give it to you. No surprises there. But if you update that first number, the SUM automagically updates too.
+Se você colocar o número 2 na primeira célula, e o número 3 na segunda e então utilizar o SUM, a planilha te dará o resultado. Até aqui nada demais. Mas se você atualizar o primeiro número, o SUM é automagicamente atualizado.
-JavaScript doesn’t usually work like this. If we were to write something comparable in JavaScript:
+O JavaScript, geralmente, não funciona assim. Se escrevêssemos algo semelhante em Javascript:
```js
let val1 = 2
@@ -26,26 +26,26 @@ console.log(sum) // 5
val1 = 3
-console.log(sum) // Still 5
+console.log(sum) // Ainda 5
```
-If we update the first value, the sum is not adjusted.
+Ao atualizarmos o primeiro valor, a soma não é ajustada.
-So how would we do this in JavaScript?
+Então, como faríamos isso em JavaScript?
-As a high-level overview, there are a few things we need to be able to do:
+Como uma visão geral de alto nível, existem algumas coisas que precisamos ser capazes de fazer:
-1. **Track when a value is read.** e.g. `val1 + val2` reads both `val1` and `val2`.
-2. **Detect when a value changes.** e.g. When we assign `val1 = 3`.
-3. **Re-run the code that read the value originally.** e.g. Run `sum = val1 + val2` again to update the value of `sum`.
+1. **Rastrear quando um valor é lido.** ex: `val1 + val2` lê `val1` e `val2`.
+2. **Detectar quando um valor muda.** ex: Quando atribuímos `val1 = 3`.
+3. **Execute novamente o código que leu o valor originalmente.** ex: Execute `sum = val1 + val2` novamente para atualizar o valor de `sum`.
-We can't do this directly using the code from the previous example but we'll come back to this example later to see how to adapt it to be compatible with Vue's reactivity system.
+Não podemos fazer isso diretamente usando o código do exemplo anterior, mas voltaremos a este exemplo mais tarde para ver como adaptá-lo para ser compatível com o sistema de reatividade do Vue.
-First, let's dig a bit deeper into how Vue implements the core reactivity requirements outlined above.
+Primeiro, vamos nos aprofundar um pouco mais em como o Vue implementa os requisitos básicos de reatividade descritos acima.
-## How Vue Knows What Code Is Running
+## Como Vue Sabe o Código Executando
-To be able to run our sum whenever the values change, the first thing we need to do is wrap it in a function:
+Para poder executar nossa soma sempre que os valores mudarem, a primeira coisa que precisamos fazer é envolvê-la em uma função:
```js
const updateSum = () => {
@@ -53,13 +53,13 @@ const updateSum = () => {
}
```
-But how do we tell Vue about this function?
+Mas como informamos o Vue sobre essa função?
-Vue keeps track of which function is currently running by using an *effect*. An effect is a wrapper around the function that initiates tracking just before the function is called. Vue knows which effect is running at any given point and can run it again when required.
+O Vue mantém o controle de qual função está sendo executada usando um *efeito*. Um efeito é um _wrapper_ em torno da função que inicia o rastreamento logo antes de a função ser chamada. O Vue sabe qual efeito está sendo executado em um determinado ponto e pode executá-lo novamente quando necessário.
-To understand that better, let's try to implement something similar ourselves, without Vue, to see how it might work.
+Para entender melhor, vamos tentar implementar algo semelhante nós mesmos, sem o Vue, para ver como pode funcionar.
-What we need is something that can wrap our sum, like this:
+O que precisamos é de algo que possa envolver nossa soma, assim:
```js
createEffect(() => {
@@ -67,46 +67,46 @@ createEffect(() => {
})
```
-We need `createEffect` to keep track of when the sum is running. We might implement it something like this:
+Precisamos de `createEffect` para acompanhar quando a soma está sendo executada. Podemos implementar algo assim:
```js
-// Maintain a stack of running effects
+// Mantém uma pilha de efeitos em execução
const runningEffects = []
const createEffect = fn => {
- // Wrap the passed fn in an effect function
+ // Envolve o fn passado em uma função de efeito
const effect = () => {
runningEffects.push(effect)
fn()
runningEffects.pop()
}
- // Automatically run the effect immediately
+ // Executa automaticamente o efeito imediatamente
effect()
}
```
-When our effect is called it pushes itself onto the `runningEffects` array, before calling `fn`. Anything that needs to know which effect is currently running can check that array.
+Quando nosso efeito é chamado, ele se adiciona ao array `runningEffects`, antes de chamar `fn`. Qualquer coisa que precise saber qual efeito está sendo executado no momento pode verificar esse array.
-Effects act as the starting point for many key features. For example, both component rendering and computed properties use effects internally. Any time something magically responds to data changes you can be pretty sure it has been wrapped in an effect.
+Os efeitos atuam como ponto de partida para muitos recursos importantes. Por exemplo, tanto a renderização do componente quanto os dados computados usam efeitos internamente. Sempre que algo responde magicamente a alterações de dados, você pode ter certeza de que foi envolvido em um efeito.
-While Vue's public API doesn't include any way to create an effect directly, it does expose a function called `watchEffect` that behaves a lot like the `createEffect` function from our example. We'll discuss that in more detail [later in the guide](/guide/reactivity-computed-watchers.html#watcheffect).
+Embora a API pública do Vue não inclua nenhuma maneira de criar um efeito diretamente, ela expõe uma função chamada `watchEffect` que se comporta muito como a função `createEffect` do nosso exemplo. Discutiremos isso com mais detalhes [mais adiante no guia](/guide/reactivity-computed-watchers.html#watcheffect).
-But knowing what code is running is just one part of the puzzle. How does Vue know what values the effect uses and how does it know when they change?
+Mas saber qual código está sendo executado é apenas uma parte do quebra-cabeça. Como o Vue sabe quais valores o efeito usa e como ele sabe quando eles mudam?
-## How Vue Tracks These Changes
+## Como o Vue Rastreia Essas Mudanças
-We can't track reassignments of local variables like those in our earlier examples, there's just no mechanism for doing that in JavaScript. What we can track are changes to object properties.
+Não podemos rastrear reatribuições de variáveis locais como aquelas em nossos exemplos anteriores, simplesmente não há mecanismo para fazer isso em JavaScript. O que podemos rastrear são as mudanças nas propriedades do objeto.
-When we return a plain JavaScript object from a component's `data` function, Vue will wrap that object in a [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) with handlers for `get` and `set`. Proxies were introduced in ES6 and allow Vue 3 to avoid some of the reactivity caveats that existed in earlier versions of Vue.
+Quando retornamos um objeto JavaScript simples da função de `data` de um componente, O Vue envolverá esse objeto em um [Proxy](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Proxy) com manipuladores para `get` e `set`. Os proxies foram introduzidos no ES6 e permitem que o Vue 3 evite algumas das limitações de reatividade que existiam nas versões anteriores do Vue.
-
+
-That was rather quick and requires some knowledge of [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) to understand! So let’s dive in a bit. There’s a lot of literature on Proxies, but what you really need to know is that a **Proxy is an object that encases another object and allows you to intercept any interactions with that object.**
+A explicação anterior foi breve e requer algum conhecimento de [Proxies](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Proxy) para ser entendida! Então vamos nos aprofundar um pouco. Há muita literatura sobre Proxies, mas o que você realmente precisa saber é que um **Proxy é um objeto que encapsula um outro objeto ou função e permite que você o intercepte.**
-We use it like this: `new Proxy(target, handler)`
+Nós o utilizamos assim: `new Proxy(target, handler)`
```js
const dinner = {
@@ -115,7 +115,7 @@ const dinner = {
const handler = {
get(target, property) {
- console.log('intercepted!')
+ console.log('interceptado!')
return target[property]
}
}
@@ -123,15 +123,15 @@ const handler = {
const proxy = new Proxy(dinner, handler)
console.log(proxy.meal)
-// intercepted!
+// interceptado!
// tacos
```
-Here we've intercepted attempts to read properties of the target object. A handler function like this is also known as a *trap*. There are many different types of trap available, each handling a different type of interaction.
+Aqui, interceptamos tentativas de ler propriedades do objeto-alvo. Uma função manipuladora como essa também é conhecida como *armadilha* (*trap*). Existem muitos tipos diferentes de armadilhas disponíveis, cada uma lidando com um tipo diferente de interação.
-Beyond a console log, we could do anything here we wish. We could even _not_ return the real value if we wanted to. This is what makes Proxies so powerful for creating APIs.
+Indo além de um `console.log`, nós poderíamos fazer aqui qualquer coisa que desejássemos. Poderíamos até mesmo _não_ retornar o valor real se quiséssemos. Isso é o que torna os Proxies tão poderosos para a criação de APIs.
-One challenge with using a Proxy is the `this` binding. We'd like any methods to be bound to the Proxy, rather than the target object, so that we can intercept them too. Thankfully, ES6 introduced another new feature, called `Reflect`, that allows us to make this problem disappear with minimal effort:
+Um desafio de usar um proxy é a vinculação de `this`. Gostaríamos que qualquer método fosse vinculado ao Proxy, em vez do objeto-alvo, para que também possamos interceptá-los. Felizmente, o ES6 introduziu outro novo recurso, chamado `Reflect`, que nos permite fazer esse problema desaparecer com o mínimo de esforço:
```js{7}
const dinner = {
@@ -147,10 +147,11 @@ const handler = {
const proxy = new Proxy(dinner, handler)
console.log(proxy.meal)
+// interceptado!
// tacos
```
-The first step towards implementing reactivity with a Proxy is to track when a property is read. We do this in the handler, in a function called `track`, where we pass in the `target` and `property`:
+A primeira etapa para implementar reatividade com um proxy é controlar quando uma propriedade é lida. Fazemos isso no manipulador, em uma função chamada `track`, onde passamos `target` e `property`:
```js{7}
const dinner = {
@@ -167,12 +168,13 @@ const handler = {
const proxy = new Proxy(dinner, handler)
console.log(proxy.meal)
+// interceptado!
// tacos
```
-The implementation of `track` isn't shown here. It will check which *effect* is currently running and record that alongside the `target` and `property`. This is how Vue knows that the property is a dependency of the effect.
+A implementação de `track` não é mostrada aqui. Ele verificará qual *efeito* está sendo executado e registrará junto de `target` e `property`. É assim que Vue sabe que a propriedade é uma dependência do efeito.
-Finally, we need to re-run the effect when the property value changes. For this we're going to need a `set` handler on our proxy:
+Finalmente, precisamos executar novamente o efeito quando o valor da propriedade mudar. Para isso, vamos precisar de um manipulador `set` em nosso *proxy*:
```js
const dinner = {
@@ -193,18 +195,19 @@ const handler = {
const proxy = new Proxy(dinner, handler)
console.log(proxy.meal)
+// interceptado!
// tacos
```
-Remember this list from earlier? Now we have some answers to how Vue implements these key steps:
+Lembra desta lista de anteriormente? Agora temos algumas respostas sobre como o Vue implementa essas etapas principais:
-1. **Track when a value is read**: the `track` function in the proxy's `get` handler records the property and the current effect.
-2. **Detect when that value changes**: the `set` handler is called on the proxy.
-3. **Re-run the code that read the value originally:** the `trigger` function looks up which effects depend on the property and runs them.
+1. **Rastrear quando um valor for lido**: a função `track` no manipulador `get` do *proxy* registra a propriedade e o efeito atual.
+2. **Detectar quando esse valor mudar**: o manipulador `set` é chamado no *proxy*.
+3. **Execute novamente o código que leu o valor originalmente:** a função `trigger` procura quais efeitos dependem da propriedade e os executa.
-The proxied object is invisible to the user, but under the hood it enables Vue to perform dependency-tracking and change-notification when properties are accessed or modified. One caveat is that console logging will format proxied objects differently, so you may want to install [vue-devtools](https://github.com/vuejs/vue-devtools) for a more inspection-friendly interface.
+O objeto com o _proxy_ aplicado é invisível para o usuário, mas por baixo dos panos ele possibilita que o Vue faça o rastreamento-de-dependência (_dependency-tracking_) e a notificação-de-mudança (_change-notification_) quando propriedades são acessadas ou modificadas. Um problema é que o _console_ de navegadores formatam diferentemente quando objetos de dados convertidos são registrados no _log_, então pode ser que você queria instalar o [vue-devtools](https://github.com/vuejs/vue-devtools) para uma interface mais amigável à inspeção.
-If we were to rewrite our original example using a component we might do it something like this:
+Se tivéssemos de reescrever nosso exemplo original usando um componente, poderíamos fazer algo assim:
```js
const vm = createApp({
@@ -228,11 +231,11 @@ vm.val1 = 3
console.log(vm.sum) // 6
```
-The object returned by `data` will be wrapped in a reactive proxy and stored as `this.$data`. The properties `this.val1` and `this.val2` are aliases for `this.$data.val1` and `this.$data.val2` respectively, so they go through the same proxy.
+O objeto retornado por `data` será encapsulado em um proxy reativo e armazenado como `this.$data`. As propriedades `this.val1` e `this.val2` são apelidos para `this.$data.val1` e `this.$data.val2` respectivamente, então elas passam pelo mesmo proxy.
-Vue will wrap the function for `sum` in an effect. When we try to access `this.sum`, it will run that effect to calculate the value. The reactive proxy around `$data` will track that the properties `val1` and `val2` were read while that effect is running.
+Vue envolverá a função para `sum` em um efeito. Quando tentamos acessar `this.sum`, ele executará esse efeito para calcular o valor. O proxy reativo em torno de `$data` rastreará se as propriedades `val1` e `val2` foram lidas enquanto o efeito está sendo executado.
-As of Vue 3, our reactivity is now available in a [separate package](https://github.com/vuejs/vue-next/tree/master/packages/reactivity). The function that wraps `$data` in a proxy is called [`reactive`](/api/basic-reactivity.html#reactive). We can call this directly ourselves, allowing us to wrap an object in a reactive proxy without needing to use a component:
+A partir do Vue 3, nossa reatividade agora está disponível em um [pacote separado](https://github.com/vuejs/vue-next/tree/master/packages/reactivity). A função que envolve `$data` em um proxy é chamada de [`reactive`](/api/basic-reactivity.html#reactive). Podemos chamar isso diretamente nós mesmos, permitindo-nos envolver um objeto em um proxy reativo sem precisar usar um componente:
```js
const proxy = reactive({
@@ -241,13 +244,13 @@ const proxy = reactive({
})
```
-We'll explore the functionality exposed by the reactivity package over the course of the next few pages of this guide. That includes functions like `reactive` and `watchEffect` that we've already met, as well as ways to use other reactivity features, such as `computed` and `watch`, without needing to create a component.
+Exploraremos a funcionalidade exposta pelo pacote de reatividade ao longo das próximas páginas deste guia. Isso inclui funções como `reactive` e `watchEffect` que já conhecemos, bem como formas de usar outros recursos de reatividade, como `computed` e `watch`, sem a necessidade de criar um componente.
-### Proxied Objects
+### Objetos com Proxy Aplicado
-Vue internally tracks all objects that have been made reactive, so it always returns the same proxy for the same object.
+O Vue rastreia internamente todos os objetos que foram transformados em reativos, então ele sempre retorna o mesmo proxy de um mesmo objeto.
-When a nested object is accessed from a reactive proxy, that object is _also_ converted into a proxy before being returned:
+Quando um objeto aninhado é acessado através de um proxy reativo, esse objeto é _também_ convertido em um proxy antes de ser retornado:
```js{6-7}
const handler = {
@@ -255,7 +258,7 @@ const handler = {
track(target, property)
const value = Reflect.get(...arguments)
if (isObject(value)) {
- // Wrap the nested object in its own reactive proxy
+ // Envolve o objeto aninhado em seu próprio proxy reativo
return reactive(value)
} else {
return value
@@ -265,9 +268,9 @@ const handler = {
}
```
-### Proxy vs. original identity
+### Proxy vs. Identidade Original
-The use of Proxy does introduce a new caveat to be aware of: the proxied object is not equal to the original object in terms of identity comparison (`===`). For example:
+O uso do Proxy de fato introduz um novo empecilho a ser considerado: o objeto com o *proxy* aplicado não é igual ao objeto original em termos de comparação de identidade (`===`). Por exemplo:
```js
const obj = {}
@@ -276,19 +279,19 @@ const wrapped = new Proxy(obj, handlers)
console.log(obj === wrapped) // false
```
-Other operations that rely on strict equality comparisons can also be impacted, such as `.includes()` or `.indexOf()`.
+Outras operações que dependem de comparações de igualdade estritas também podem ser afetadas, como `.includes()` ou `.indexOf()`.
-The best practice here is to never hold a reference to the original raw object and only work with the reactive version:
+A prática recomendada aqui é nunca manter uma referência ao objeto bruto original e trabalhar apenas com a versão reativa:
```js
const obj = reactive({
count: 0
-}) // no reference to original
+}) // nenhuma referência ao original
```
-This ensures that both equality comparisons and reactivity behave as expected.
+Isso garante que as comparações de igualdade e reatividade se comportem conforme o esperado.
-Note that Vue does not wrap primitive values such as numbers or strings in a Proxy, so you can still use `===` directly with those values:
+Observe que o Vue não envolve valores primitivos, como números ou strings em um *proxy*, então você ainda pode usar `===` diretamente com esses valores:
```js
const obj = reactive({
@@ -298,14 +301,18 @@ const obj = reactive({
console.log(obj.count === 0) // true
```
-## How Rendering Reacts to Changes
+## Observadores
-The template for a component is compiled down into a [`render`](/guide/render-function.html) function. The `render` function creates the [VNodes](/guide/render-function.html#the-virtual-dom-tree) that describe how the component should be rendered. It is wrapped in an effect, allowing Vue to track the properties that are 'touched' while it is running.
+Toda instância de componente tem uma instância de observador correspondente, que registra quaisquer propriedades "tocadas" durante a renderização do componente como dependências. Depois, quando um setter de uma dependência é disparado, ele notifica o observador, que por sua vez faz o componente re-renderizar.
-A `render` function is conceptually very similar to a `computed` property. Vue doesn't track exactly how dependencies are used, it only knows that they were used at some point while the function was running. If any of those properties subsequently changes, it will trigger the effect to run again, re-running the `render` function to generate new VNodes. These are then used to make the necessary changes to the DOM.
+## Como a Renderização Reage às Mudanças
+
+O _template_ para um componente é compilado em uma função [`render`](/guide/render-function.html). A função `render` cria os [VNodes](/guide/render-function.html#a-arvore-virtual-dom) que descrevem como o componente deve ser renderizado. Ele é envolvido em um efeito, permitindo que o Vue rastreie as propriedades que são 'tocadas' enquanto ele está em execução.
+
+Uma função `render` é conceitualmente muito semelhante a uma propriedade `computed`. O Vue não rastreia exatamente como as dependências são usadas, ele apenas sabe que elas foram usadas em algum momento enquanto a função estava em execução. Se qualquer uma dessas propriedades for alterada posteriormente, o efeito será acionado novamente, executando novamente a função `render` para gerar novos VNodes. Estes são então usados para fazer as alterações necessárias no DOM.
-
+
-> If you are using Vue 2.x and below, you may be interested in some of the change detection caveats that exist for those versions, [explored in more detail here](change-detection.md).
+> Se você está utilizando Vue v2.x ou mais antigo, pode estar interessado em alguns empecilhos da detecção de mudanças que existem nessas versões, [explorados em mais detalhes aqui](change-detection.md).
diff --git a/src/guide/render-function.md b/src/guide/render-function.md
index 902f229421..824c48f151 100644
--- a/src/guide/render-function.md
+++ b/src/guide/render-function.md
@@ -1,24 +1,24 @@
-# Render Functions
+# Funções de Renderização
-Vue recommends using templates to build applications in the vast majority of cases. However, there are situations where we need the full programmatic power of JavaScript. That's where we can use the **render function**.
+Vue recomenda o uso de _templates_ para construir aplicações na grande maioria dos casos. No entanto, existem situações onde precisamos de todo o poder programático do JavaScript. É aí onde podemos utilizar a **função de renderização**.
-Let's dive into an example where a `render()` function would be practical. Say we want to generate anchored headings:
+Vamos mergulhar em um exemplo onde uma função `render()` seria prática. Digamos que queremos gerar um título ancorados:
```html
```
-Anchored headings are used very frequently, we should create a component:
+Títulos ancorados são usados frequentemente, deveríamos criar um componente:
```vue-html
-Hello world!
+Olá mundo!
```
-The component must generate a heading based on the `level` prop, and we quickly arrive at this:
+O componente deve gerar um título baseado na propriedade `level`, e nós rapidamente chegaríamos nisso:
```js
const { createApp } = Vue
@@ -55,9 +55,9 @@ app.component('anchored-heading', {
})
```
-This template doesn't feel great. It's not only verbose, but we're duplicating ` ` for every heading level. And when we add the anchor element, we have to again duplicate it in every `v-if/v-else-if` branch.
+Este _template_ não parece bom. Não apenas é verboso, como também estamos duplicando o ` ` para cada nível de título. E quando adicionarmos o elemento de âncora, teríamos que duplicá-lo em cada ramo `v-if/v-else-if`.
-While templates work great for most components, it's clear that this isn't one of them. So let's try rewriting it with a `render()` function:
+Enquanto que _templates_ funcionam muito bem para a maioria dos componentes, fica claro que este não é um deles. Então, vamos tentar reescrevê-lo com uma função `render()`:
```js
const { createApp, h } = Vue
@@ -67,9 +67,9 @@ const app = createApp({})
app.component('anchored-heading', {
render() {
return h(
- 'h' + this.level, // tag name
- {}, // props/attributes
- this.$slots.default() // array of children
+ 'h' + this.level, // nome da tag
+ {}, // propriedades/atributos
+ this.$slots.default() // array de filhos
)
},
props: {
@@ -81,35 +81,35 @@ app.component('anchored-heading', {
})
```
-The `render()` function implementation is much simpler, but also requires greater familiarity with component instance properties. In this case, you have to know that when you pass children without a `v-slot` directive into a component, like the `Hello world!` inside of `anchored-heading`, those children are stored on the component instance at `$slots.default()`. If you haven't already, **it's recommended to read through the [instance properties API](../api/instance-properties.html) before diving into render functions.**
+A implementação da função `render()` é muito mais simples, mas também requer mais familiaridade com as propriedades das instâncias dos componentes. Nesse caso, você deve saber que quando você passar filhos sem uma diretiva `v-slot` para um componente, como o `Olá mundo!` dentro do `anchored-heading`, esses filhos serão armazenados na instância do componente em `$slots.default()`. Se você já não tiver feito ainda, **é recomendado ler a [API de propriedades de instância](../api/instance-properties.html) antes de mergulhar nas funções de renderização.**
-## The DOM tree
+## A Árvore DOM
-Before we dive into render functions, it’s important to know a little about how browsers work. Take this HTML for example:
+Antes de mergulharmos nas funções de renderização, é importante conhecer um pouco sobre como os navegadores funcionam. Veja esse HTML como exemplo:
```html
-
My title
- Some text content
-
+ Meu título
+ Algum conteúdo em texto
+
```
-When a browser reads this code, it builds a [tree of "DOM nodes"](https://javascript.info/dom-nodes) to help it keep track of everything.
+Quando um navegador lê este código, ele compila uma [árvore de "nós DOM"](https://javascript.info/dom-nodes) para ajudá-lo a acompanhar tudo.
-The tree of DOM nodes for the HTML above looks like this:
+A árvore de nós DOM para o HTML acima se parece com isso:
-
+
-Every element is a node. Every piece of text is a node. Even comments are nodes! Each node can have children (i.e. each node can contain other nodes).
+Cada elemento é um nó. Cada trecho de texto é um nó. Até mesmo comentários são nós! Cada nó pode possuír filhos (i.e. cada nó pode conter outros nós).
-Updating all these nodes efficiently can be difficult, but thankfully, we never have to do it manually. Instead, we tell Vue what HTML we want on the page, in a template:
+Atualizar todos esses nós eficientemente pode ser difícil, mas felizmente, nós nunca precisamos fazê-lo manualmente. Ao invés disso, nós dizemos ao Vue qual HTML nós queremos na página, em um _template_:
```html
{{ blogTitle }}
```
-Or in a render function:
+Ou em uma função de renderização:
```js
render() {
@@ -117,48 +117,48 @@ render() {
}
```
-And in both cases, Vue automatically keeps the page updated, even when `blogTitle` changes.
+E em ambos os casos, o Vue automaticamente mantém a página atualizada, até mesmo quando o `blogTitle` muda.
-## The Virtual DOM tree
+## A Árvore Virtual DOM
-Vue keeps the page updated by building a **virtual DOM** to keep track of the changes it needs to make to the real DOM. Taking a closer look at this line:
+Vue mantém a página atualizada compilando um **DOM virtual** para acompanhar as mudanças que necessita para fazer o DOM real. Olhando a seguinte linha mais de perto:
```js
return h('h1', {}, this.blogTitle)
```
-What is the `h()` function returning? It's not _exactly_ a real DOM element. It returns a plain object which contains information describing to Vue what kind of node it should render on the page, including descriptions of any child nodes. We call this node description a "virtual node", usually abbreviated to **VNode**. "Virtual DOM" is what we call the entire tree of VNodes, built by a tree of Vue components.
+O que a função `h()` retorna? Não é _exatamente_ um elemento DOM real. Ela retorna um objeto que contém informações que descrevem para o Vue que tipo de nó deve ser renderizado na página, incluíndo descrições de qualquer nó filho. Chamamos essa descrição do nó de "nó virtual", geralmente abreviado para **_VNode_**. "Virtual DOM" é como chamamos toda a árvore de _VNodes_, constituída de uma árvore de componentes Vue.
-## `h()` Arguments
+## Argumentos do `h()`
-The `h()` function is a utility to create VNodes. It could perhaps more accurately be named `createVNode()`, but it's called `h()` due to frequent use and for brevity. It accepts three arguments:
+A função `h()`é um utilitário para criar _VNodes_. Poderia, talvez, ser nomeado com mais precisão como `createVNode()`, mas é chamada `h()` devido ao uso frequente e por brevidade. Ela aceita três argumentos:
```js
// @returns {VNode}
h(
// {String | Object | Function} tag
- // An HTML tag name, a component, an async component, or a
- // functional component.
+ // O nome de uma tag HTML, um componente, um componente assíncrono ou um
+ // componente funcional.
//
- // Required.
+ // Obrigatório.
'div',
// {Object} props
- // An object corresponding to the attributes, props and events
- // we would use in a template.
+ // Um objeto correspondente aos atributos, propriedades e eventos
+ // que utilizaríamos em um template.
//
- // Optional.
+ // Opcional.
{},
// {String | Array | Object} children
- // Children VNodes, built using `h()`,
- // or using strings to get 'text VNodes' or
- // an object with slots.
+ // VNodes filhos, construídos usando `h()`,
+ // ou usando strings para obter 'VNodes de texto' ou
+ // um objeto com slots.
//
- // Optional.
+ // Opcional.
[
- 'Some text comes first.',
- h('h1', 'A headline'),
+ 'Algum texto vem primeiro.',
+ h('h1', 'Um título'),
h(MyComponent, {
someProp: 'foobar'
})
@@ -166,18 +166,18 @@ h(
)
```
-If there are no props then the children can usually be passed as the second argument. In cases where that would be ambiguous, `null` can be passed as the second argument to keep the children as the third argument.
+Se não houver props, os filhos geralmente podem ser passados como segundo argumento. Nos casos em que isso for ambíguo, `null` pode ser passado como o segundo argumento para manter os filhos como terceiro argumento.
-## Complete Example
+## Exemplo Completo
-With this knowledge, we can now finish the component we started:
+Com este conhecimento, podemos agora finalizar o componente que começamos:
```js
const { createApp, h } = Vue
const app = createApp({})
-/** Recursively get text from children nodes */
+/** Recupera o texto dos nós filhos recursivamente */
function getChildrenTextContent(children) {
return children
.map(node => {
@@ -192,11 +192,11 @@ function getChildrenTextContent(children) {
app.component('anchored-heading', {
render() {
- // create kebab-case id from the text contents of the children
+ // cria um id em kebab-case a partir do texto dos filhos
const headingId = getChildrenTextContent(this.$slots.default())
.toLowerCase()
- .replace(/\W+/g, '-') // replace non-word characters with dash
- .replace(/(^-|-$)/g, '') // remove leading and trailing dashes
+ .replace(/\W+/g, '-') // substitui caracteres não-texto por traços
+ .replace(/(^-|-$)/g, '') // remove os traços iniciais e finais
return h('h' + this.level, [
h(
@@ -218,23 +218,23 @@ app.component('anchored-heading', {
})
```
-## Constraints
+## Restrições
-### VNodes Must Be Unique
+### VNodes Devem Ser Únicos
-All VNodes in the component tree must be unique. That means the following render function is invalid:
+Todos os _VNodes_ na árvore de componentes devem ser únicos. Isso significa que a função de renderização a seguir é inválida:
```js
render() {
const myParagraphVNode = h('p', 'hi')
return h('div', [
- // Yikes - duplicate VNodes!
+ // Eita - VNodes duplicados!
myParagraphVNode, myParagraphVNode
])
}
```
-If you really want to duplicate the same element/component many times, you can do so with a factory function. For example, the following render function is a perfectly valid way of rendering 20 identical paragraphs:
+Se você realmente quiser duplicar o mesmo elemento/componente várias vezes, você pode fazê-lo com uma função fábrica (_factory function_). Por exemplo, a função de renderização a seguir é uma forma perfeitamente válida de renderizar 20 parágrafos idênticos:
```js
render() {
@@ -246,9 +246,9 @@ render() {
}
```
-## Creating Component VNodes
+## Criando VNodes de Componentes
-To create a VNode for a component, the first argument passed to `h` should be the component itself:
+Para criar um VNode para um componente, o primeiro argumento passado para `h` deve ser o próprio componente:
```js
render() {
@@ -256,7 +256,7 @@ render() {
}
```
-If we need to resolve a component by name then we can call `resolveComponent`:
+Se precisarmos resolver um componente pelo nome, podemos chamar `resolveComponent`:
```js
const { h, resolveComponent } = Vue
@@ -269,12 +269,12 @@ render() {
}
```
-`resolveComponent` is the same function that templates use internally to resolve components by name.
+`resolveComponent` é a mesma função que os _templates_ usam internamente para resolver componentes por nome.
-A `render` function will normally only need to use `resolveComponent` for components that are [registered globally](/guide/component-registration.html#global-registration). [Local component registration](/guide/component-registration.html#local-registration) can usually be skipped altogether. Consider the following example:
+Uma função `render` normalmente só precisa usar `resolveComponent` para componentes que são [registrados globalmente](/guide/component-registration.html#registro-global). Assim o [registro local de componentes](/guide/component-registration.html#registro-local) geralmente pode ser ignorado por completo. Considere o seguinte exemplo:
```js
-// We can simplify this
+// Podemos simplificar isso
components: {
ButtonCounter
},
@@ -283,7 +283,7 @@ render() {
}
```
-Rather than registering a component by name and then looking it up we can use it directly instead:
+Em vez de registrar um componente pelo nome e depois procurá-lo, podemos usá-lo diretamente:
```js
render() {
@@ -291,20 +291,20 @@ render() {
}
```
-## Replacing Template Features with Plain JavaScript
+## Substituíndo Recursos de _Templates_ com JavaScript Simples
-### `v-if` and `v-for`
+### `v-if` e `v-for`
-Wherever something can be easily accomplished in plain JavaScript, Vue render functions do not provide a proprietary alternative. For example, in a template using `v-if` and `v-for`:
+Sempre que algo for facilmente realizado usando JavaScript simples, as funções de renderização do Vue não são uma alternativa apropriada. Por exemplo, em um _template_ usando `v-if` e `v-for`:
```html
-No items found.
+Não foram encontrados itens.
```
-This could be rewritten with JavaScript's `if`/`else` and `map()` in a render function:
+Pode ser rescrito usando `if`/`else` e `map()` com JavaScript em uma função de renderização:
```js
props: ['items'],
@@ -314,16 +314,16 @@ render() {
return h('li', item.name)
}))
} else {
- return h('p', 'No items found.')
+ return h('p', 'Não foram encontrados itens.')
}
}
```
-In a template it can be useful to use a `` tag to hold a `v-if` or `v-for` directive. When migrating to a `render` function, the `` tag is no longer required and can be discarded.
+Em um _template_ pode ser útil usar uma tag `` para conter uma diretiva `v-if` ou `v-for`. Ao migrar para uma função `render`, a tag `` não é mais necessária e pode ser descartada.
### `v-model`
-The `v-model` directive is expanded to `modelValue` and `onUpdate:modelValue` props during template compilation—we will have to provide these props ourselves:
+A diretiva `v-model` é expandida para as propriedades `modelValue`e `onUpdate:modelValue` durante a compilação do _template_ - nós mesmos teremos que prover essas propriedades:
```js
props: ['modelValue'],
@@ -338,7 +338,7 @@ render() {
### `v-on`
-We have to provide a proper prop name for the event handler, e.g., to handle `click` events, the prop name would be `onClick`.
+Temos que prover um nome de propriedade adequado para o manipulador do evento, e.g., para manipular um evento de `click`, o nome da propriedade deve ser `onClick`.
```js
render() {
@@ -348,11 +348,11 @@ render() {
}
```
-#### Event Modifiers
+#### Modificadores de Eventos
-For the `.passive`, `.capture`, and `.once` event modifiers, they can be concatenated after the event name using camelCase.
+Os modificadores de evento `.passive`, `.capture` e `.once`, podem ser concatenados após o nome do evento usando _camelCase_.
-For example:
+Por exemplo:
```js
render() {
@@ -364,32 +364,32 @@ render() {
}
```
-For all other event and key modifiers, no special API is necessary, because we can use event methods in the handler:
+Para todos os outros modificadores de evento, não é necessária nenhuma API especial, pois podemos usar métodos de evento no manipulador:
-| Modifier(s) | Equivalent in Handler |
-| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
-| `.stop` | `event.stopPropagation()` |
-| `.prevent` | `event.preventDefault()` |
-| `.self` | `if (event.target !== event.currentTarget) return` |
-| Keys: e.g. `.enter` | `if (event.key !== 'Enter') return` Change `'Enter'` to the appropriate [key](http://keycode.info/) |
-| Modifier Keys: `.ctrl`, `.alt`, `.shift`, `.meta` | `if (!event.ctrlKey) return` Likewise for `altKey`, `shiftKey`, and `metaKey` |
+| Modificador(es) | Equivalente no manipulador |
+| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
+| `.stop` | `event.stopPropagation()` |
+| `.prevent` | `event.preventDefault()` |
+| `.self` | `if (event.target !== event.currentTarget) return` |
+| Teclas: ex: `.enter` | `if (event.key !== 'Enter') return` Mude `'Enter'` para a [tecla](http://keycode.info/) apropriada |
+| Modificadores de teclas: `.ctrl`, `.alt`, `.shift`, `.meta` | `if (!event.ctrlKey) return` Da mesma forma para `altKey`,` shiftKey` e `metaKey` |
-Here's an example with all of these modifiers used together:
+Aqui temos um exemplo de todos esses modificadores sendo usados juntos:
```js
render() {
return h('input', {
onKeyUp: event => {
- // Abort if the element emitting the event is not
- // the element the event is bound to
+ // Aborta se o elemento emitindo o evento não é
+ // o elemento em qual o evento está ligado
if (event.target !== event.currentTarget) return
- // Abort if the key that went up is not the enter
- // key and the shift key was not held down at the
- // same time
+ // Aborta se a tecla que foi pressionada não é a tecla enter
+ // e a tecla shift não está sendo segurada
+ // ao mesmo tempo
if (!event.shiftKey || event.key !== 'Enter') return
- // Stop event propagation
+ // Para a propagação de eventos
event.stopPropagation()
- // Prevent the default keyup handler for this element
+ // Previne o manipulador padrão de teclas para este elemento
event.preventDefault()
// ...
}
@@ -399,7 +399,7 @@ render() {
### Slots
-We can access slot contents as arrays of VNodes from [`this.$slots`](../api/instance-properties.html#slots):
+Podemos acessar os conteúdos de slots como arrays de _VNodes_ através de [`this.$slots`](../api/instance-properties.html#slots):
```js
render() {
@@ -418,7 +418,7 @@ render() {
}
```
-For component VNodes, we need to pass the children to `h` as an object rather than an array. Each property is used to populate the slot of the same name:
+Para VNodes de componente, precisamos passar os filhos para `h` como um objeto em vez de um array. Cada propriedade é usada para preencher o slot de mesmo nome:
```js
render() {
@@ -427,8 +427,8 @@ render() {
h(
resolveComponent('child'),
null,
- // pass `slots` as the children object
- // in the form of { name: props => VNode | Array }
+ // passa `slots` como objetos filhos
+ // na forma de { name: props => VNode | Array }
{
default: (props) => h('span', props.text)
}
@@ -437,12 +437,12 @@ render() {
}
```
-The slots are passed as functions, allowing the child component to control the creation of each slot's contents. Any reactive data should be accessed within the slot function to ensure that it's registered as a dependency of the child component and not the parent. Conversely, calls to `resolveComponent` should be made outside the slot function, otherwise they'll resolve relative to the wrong component:
+Os slots são passados como funções, permitindo que o componente filho controle a criação do conteúdo de cada slot. Quaisquer dados reativos devem ser acessados dentro da função do slot para garantir que sejam registrados como uma dependência do componente filho e não do pai. Por outro lado, chamadas ao `resolveComponent` devem ser feitas fora da função do slot, caso contrário, elas serão resolvidas em relação ao componente errado:
```js
// ` {{ text }} `
render() {
- // Calls to resolveComponent should be outside the slot function
+ // Chamadas para resolveComponent devem estar fora da função slot
const Button = resolveComponent('MyButton')
const Icon = resolveComponent('MyIcon')
@@ -450,10 +450,10 @@ render() {
Button,
null,
{
- // Use an arrow function to preserve the `this` value
+ // Use uma arrow function para preservar o valor de `this`
default: (props) => {
- // Reactive properties should be read inside the slot function
- // so that they become dependencies of the child's rendering
+ // Propriedades reativas devem ser lidas dentro da função slot
+ // para que se tornem dependências da renderização do filho
return [
h(Icon, { name: this.icon }),
this.text
@@ -464,7 +464,7 @@ render() {
}
```
-If a component receives slots from its parent, they can be passed on directly to a child component:
+Se um componente recebe slots de seu pai, eles podem ser passados diretamente para um componente filho:
```js
render() {
@@ -472,7 +472,7 @@ render() {
}
```
-They can also be passed individually or wrapped as appropriate:
+Eles também podem ser passados individualmente ou envolvidos conforme apropriado:
```js
render() {
@@ -480,24 +480,24 @@ render() {
Panel,
null,
{
- // If we want to pass on a slot function we can
+ // Se quisermos passar uma função de slot podemos
header: this.$slots.header,
- // If we need to manipulate the slot in some way
- // then we need to wrap it in a new function
+ // Se precisarmos manipular o slot de alguma forma
+ // então precisamos envolvê-lo em uma nova função
default: (props) => {
const children = this.$slots.default ? this.$slots.default(props) : []
- return children.concat(h('div', 'Extra child'))
+ return children.concat(h('div', 'Filho extra'))
}
}
)
}
```
-### `` and `is`
+### `` e `is`
-Behind the scenes, templates use `resolveDynamicComponent` to implement the `is` attribute. We can use the same function if we need all the flexibility provided by `is` in our `render` function:
+Nos bastidores, os _templates_ usam `resolveDynamicComponent` para implementar o atributo `is`. Podemos usar a mesma função se precisarmos de toda a flexibilidade fornecida por `is` em nossa função `render`:
```js
const { h, resolveDynamicComponent } = Vue
@@ -511,13 +511,13 @@ render() {
}
```
-Just like `is`, `resolveDynamicComponent` supports passing a component name, an HTML element name, or a component options object.
+Assim como `is`, `resolveDynamicComponent` suporta a passagem de um nome de componente, um nome de elemento HTML ou um objeto de opções de componente.
-However, that level of flexibility is usually not required. It's often possible to replace `resolveDynamicComponent` with a more direct alternative.
+No entanto, esse nível de flexibilidade geralmente não é necessário. Muitas vezes é possível substituir `resolveDynamicComponent` por uma alternativa mais direta.
-For example, if we only need to support component names then `resolveComponent` can be used instead.
+Por exemplo, se precisarmos apenas oferecer suporte a nomes de componentes, então `resolveComponent` pode ser usado.
-If the VNode is always an HTML element then we can pass its name directly to `h`:
+Se o VNode for sempre um elemento HTML, podemos passar seu nome diretamente para `h`:
```js
// ` `
@@ -526,13 +526,13 @@ render() {
}
```
-Similarly, if the value passed to `is` is a component options object then there's no need to resolve anything, it can be passed directly as the first argument of `h`.
+Da mesma forma, se o valor passado para `is` for um objeto de opções de componente, então não há necessidade de resolver nada, ele pode ser passado diretamente como o primeiro argumento de `h`.
-Much like a `` tag, a `` tag is only required in templates as a syntactical placeholder and should be discarded when migrating to a `render` function.
+Assim como uma tag ``, uma tag `` só é necessária em _templates_ como um espaço reservado sintático e deve ser descartada ao migrar para uma função `render`.
-### Custom Directives
+### Diretivas Personalizadas
-Custom directives can be applied to a VNode using [`withDirectives`](/api/global-api.html#withdirectives):
+Diretivas personalizadas podem ser aplicadas a um VNode usando [`withDirectives`](/api/global-api.html#withdirectives):
```js
const { h, resolveDirective, withDirectives } = Vue
@@ -549,13 +549,13 @@ render () {
}
```
-[`resolveDirective`](/api/global-api.html#resolvedirective) is the same function that templates use internally to resolve directives by name. That is only necessary if you don't already have direct access to the directive's definition object.
+[`resolveDirective`](/api/global-api.html#resolvedirective) é a mesma função que os _templates_ usam internamente para resolver diretivas por nome. Isso só é necessário se você ainda não tiver acesso direto ao objeto de definição da diretiva.
-### Built-in Components
+### Componentes Integrados
-[Built-in components](/api/built-in-components.html) such as ``, ``, ``, and `` are not registered globally by default. This allows bundlers to perform tree-shaking, so that the components are only included in the build if they are used. However, that also means we can't access them using `resolveComponent` or `resolveDynamicComponent`.
+[Componentes integrados](/api/built-in-components.html), como ``, ``, `` e `` por padrão não são registrados globalmente. Isso permite que empacotadores executem o _tree-shaking_ para que os componentes sejam incluídos na compilação apenas se forem usados. No entanto, isso também significa que não podemos acessá-los usando `resolveComponent` ou `resolveDynamicComponent`.
-Templates have special handling for those components, automatically importing them when they are used. When we're writing our own `render` functions, we need to import them ourselves:
+_Templates_ possuem tratamento especial para esses componentes, importando-os automaticamente quando utilizados. Quando estamos escrevendo nossas próprias funções `render`, precisamos importá-las nós mesmos:
```js
const { h, KeepAlive, Teleport, Transition, TransitionGroup } = Vue
@@ -567,36 +567,36 @@ render () {
}
```
-## Return Values for Render Functions
+## Valores de Retorno para Funções de Renderização
-In all of the examples we've seen so far, the `render` function has returned a single root VNode. However, there are alternatives.
+Em todos os exemplos que vimos até agora, a função `render` retornou um único VNode raiz. No entanto, existem alternativas.
-Returning a string will create a text VNode, without any wrapping element:
+Retornar uma string criará um VNode de texto, sem nenhum elemento de encapsulamento:
```js
render() {
- return 'Hello world!'
+ return 'Olá mundo!'
}
```
-We can also return an array of children, without wrapping them in a root node. This creates a fragment:
+Também podemos retornar um array de filhos, sem envolvê-los em um nó raiz. Isso cria um fragmento:
```js
-// Equivalent to a template of `Hello world!`
+// Equivalente a um template de `Olá mundo!`
render() {
return [
- 'Hello',
+ 'Olá',
h('br'),
- 'world!'
+ 'mundo!'
]
}
```
-If a component needs to render nothing, perhaps because data is still loading, it can just return `null`. This will be rendered as a comment node in the DOM.
+Se um componente não precisar renderizar nada, talvez porque os dados ainda estão sendo carregados, ele pode simplesmente retornar `null`. Isso será renderizado como um nó de comentário no DOM.
## JSX
-If we're writing a lot of `render` functions, it might feel painful to write something like this:
+Se estivermos escrevendo muitas funções `render`, pode ficar doloroso escrever algo assim:
```js
h(
@@ -605,18 +605,18 @@ h(
level: 1
},
{
- default: () => [h('span', 'Hello'), ' world!']
+ default: () => [h('span', 'Olá'), ' mundo!']
}
)
```
-Especially when the template version is so concise in comparison:
+Especialmente quando a versão usando _template_ é mais concisa em comparação:
```vue-html
- Hello world!
+ Olá mundo!
```
-That's why there's a [Babel plugin](https://github.com/vuejs/jsx-next) to use JSX with Vue, getting us back to a syntax that's closer to templates:
+É por isso que existe um [_plugin_ Babel](https://github.com/vuejs/jsx-next) para usar JSX com Vue, nos colocando em uma sintaxe que é mais próxima dos _templates_:
```jsx
import AnchoredHeading from './AnchoredHeading.vue'
@@ -625,7 +625,7 @@ const app = createApp({
render() {
return (
- Hello world!
+ Olá mundo!
)
}
@@ -634,13 +634,13 @@ const app = createApp({
app.mount('#demo')
```
-For more on how JSX maps to JavaScript, see the [usage docs](https://github.com/vuejs/jsx-next#installation).
+Para saber mais sobre como JSX mapeia para o JavaScript, veja a [documentação de uso](https://github.com/vuejs/jsx-next#installation).
-## Functional Components
+## Componentes Funcionais
-Functional components are an alternative form of component that don't have any state of their own. They are rendered without creating a component instance, bypassing the usual component lifecycle.
+Componentes funcionais são uma forma alternativa de componente que não possui nenhum estado próprio. Eles são renderizados sem criar uma instância de componente, ignorando o ciclo de vida normal do componente.
-To create a functional component we use a plain function, rather than an options object. The function is effectively the `render` function for the component. As there is no `this` reference for a functional component, Vue will pass in the `props` as the first argument:
+Para criar um componente funcional, usamos uma função simples, em vez de um objeto de opções. A função é efetivamente a função `render` para o componente. Como não há referência de `this` para um componente funcional, o Vue passará o `props` como primeiro argumento:
```js
const FunctionalComponent = (props, context) => {
@@ -648,21 +648,21 @@ const FunctionalComponent = (props, context) => {
}
```
-The second argument, `context`, contains three properties: `attrs`, `emit`, and `slots`. These are equivalent to the instance properties [`$attrs`](/api/instance-properties.html#attrs), [`$emit`](/api/instance-methods.html#emit), and [`$slots`](/api/instance-properties.html#slots) respectively.
+O segundo argumento, `context`, contém três propriedades: `attrs`, `emit` e `slots`. Elas são equivalentes às propriedades de instância [`$attrs`](/api/instance-properties.html#attrs), [`$emit`](/api/instance-methods.html#emit) e [`$slots`](/api/instance-properties.html#slots) respectivamente.
-Most of the usual configuration options for components are not available for functional components. However, it is possible to define [`props`](/api/options-data.html#props) and [`emits`](/api/options-data.html#emits) by adding them as properties:
+A maioria das opções de configuração usuais para componentes não está disponível para componentes funcionais. No entanto, é possível definir [`props`](/api/options-data.html#props) e [`emits`](/api/options-data.html#emits) adicionando-os como propriedades:
```js
FunctionalComponent.props = ['value']
FunctionalComponent.emits = ['click']
```
-If the `props` option is not specified, then the `props` object passed to the function will contain all attributes, the same as `attrs`. The prop names will not be normalized to camelCase unless the `props` option is specified.
+Se a opção `props` não for especificada, então o objeto `props` passado para a função conterá todos os atributos, o mesmo que `attrs`. Os nomes das props não serão normalizados para camelCase a menos que a opção `props` seja especificada.
-Functional components can be registered and consumed just like normal components. If you pass a function as the first argument to `h`, it will be treated as a functional component.
+Componentes funcionais podem ser registrados e consumidos como componentes normais. Se você passar uma função como primeiro argumento para `h`, ela será tratada como um componente funcional.
-## Template Compilation
+## Compilação de _Template_
-You may be interested to know that Vue's templates actually compile to render functions. This is an implementation detail you usually don't need to know about, but if you'd like to see how specific template features are compiled, you may find it interesting. Below is a little demo using `Vue.compile` to live-compile a template string:
+Pode ser que você esteja interessando em saber que o Vue, na verdade, compila os _templates_ em funções de renderização. Isso é um detalhe de implementação que, geralmente, você não precisa saber, porém, se você quiser ver como recursos específicos de _templates_ são compilados, você pode achar interessante. Abaixo temos uma pequena demonstração de uso de `Vue.compile` para compilar em tempo real uma string de _template_:
diff --git a/src/guide/routing.md b/src/guide/routing.md
index 0bca2d5ba4..21759b61ba 100644
--- a/src/guide/routing.md
+++ b/src/guide/routing.md
@@ -1,12 +1,12 @@
-# Routing
+# Roteamento
-## Official Router
+## Roteador oficial
-For most Single Page Applications, it's recommended to use the officially-supported [vue-router library](https://github.com/vuejs/vue-router-next). For more details, see vue-router's [documentation](https://next.router.vuejs.org/).
+Para a maioria das aplicações de página única _(Single Page Application)_, é recomendado utilizar a [biblioteca vue-router](https://github.com/vuejs/vue-router-next) oficial. Para mais detalhes, veja a [documentação](https://next.router.vuejs.org/) do _vue-router_.
-## Simple Routing from Scratch
+## Roteamento básico do zero
-If you only need very simple routing and do not wish to involve a full-featured router library, you can do so by dynamically rendering a page-level component like this:
+Se você só precisa de um roteamento simples e não tem interesse em utilizar uma biblioteca robusta de roteamento, você pode o fazer dinamicamente, renderizando um componente no nível da página _(page-level component)_, desse jeito:
```js
const { createApp, h } = Vue
@@ -39,8 +39,8 @@ const SimpleRouter = {
createApp(SimpleRouter).mount('#app')
```
-Combined with the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API), you can build a very basic but fully-functional client-side router. To see that in practice, check out [this example app](https://github.com/phanan/vue-3.0-simple-routing-example).
+Combinado com a [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API/Working_with_the_History_API), você poderá construir um roteador básico (porém poderoso) no lado do cliente (client-side router). Para ver isso na prática, acesse [esse app de exemplo](https://github.com/phanan/vue-3.0-simple-routing-example).
-## Integrating 3rd-Party Routers
+## Integrando com roteadores externos
-If there's a 3rd-party router you prefer to use, such as [Page.js](https://github.com/visionmedia/page.js) or [Director](https://github.com/flatiron/director), integration is [similarly straightforward](https://github.com/phanan/vue-3.0-simple-routing-example/compare/master...pagejs). Here's a [complete example](https://github.com/phanan/vue-3.0-simple-routing-example/tree/pagejs) using Page.js.
+Se você preferir utilizar um roteador de terceiros _(3rd-party router)_, como por exemplo [Page.js](https://github.com/visionmedia/page.js) ou [Director](https://github.com/flatiron/director), a integração é [igualmente simples](https://github.com/phanan/vue-3.0-simple-routing-example/compare/master...pagejs). Segue aqui [um exemplo completo](https://github.com/phanan/vue-3.0-simple-routing-example/tree/pagejs) utilizando `Page.js`.
diff --git a/src/guide/security.md b/src/guide/security.md
index 5f7813e00a..8a1316ac64 100644
--- a/src/guide/security.md
+++ b/src/guide/security.md
@@ -1,88 +1,88 @@
-# Security
+# Segurança
-## Reporting Vulnerabilities
+## Reportando Vulnerabilidades
-When a vulnerability is reported, it immediately becomes our top concern, with a full-time contributor dropping everything to work on it. To report a vulnerability, please email [security@vuejs.org](mailto:security@vuejs.org).
+Quando uma vulnerabilidade é reportada, ela imediatamente se torna nossa principal preocupação, com um contribuidor em tempo integral largando tudo para trabalhar nela. Para reportar uma vulnerabilidade, envie um e-mail para [security@vuejs.org](mailto:security@vuejs.org).
-While the discovery of new vulnerabilities is rare, we also recommend always using the latest versions of Vue and its official companion libraries to ensure your application remains as secure as possible.
+Embora a descoberta de novas vulnerabilidades seja rara, também recomendamos sempre usar as versões mais recentes do Vue e suas bibliotecas complementares oficiais para garantir que seu aplicativo permaneça o mais seguro possível.
-## Rule No.1: Never Use Non-trusted Templates
+## Regra nº 1: Nunca Use Templates Não Confiáveis
-The most fundamental security rule when using Vue is **never use non-trusted content as your component template**. Doing so is equivalent to allowing arbitrary JavaScript execution in your application - and worse, could lead to server breaches if the code is executed during server-side rendering. An example of such usage:
+A regra de segurança mais fundamental ao usar o Vue é **nunca use conteúdo não confiável como seu _template_ de componente**. Fazer isso é equivalente a permitir a execução arbitrária de JavaScript em seu aplicativo - e pior, pode levar a violações do servidor se o código for executado durante a renderização do lado do servidor. Um exemplo desse uso:
```js
Vue.createApp({
- template: `` + userProvidedString + `
` // NEVER DO THIS
+ template: `` + userProvidedString + `
` // NUNCA FAÇA ISSO
}).mount('#app')
```
-Vue templates are compiled into JavaScript, and expressions inside templates will be executed as part of the rendering process. Although the expressions are evaluated against a specific rendering context, due to the complexity of potential global execution environments, it is impractical for a framework like Vue to completely shield you from potential malicious code execution without incurring unrealistic performance overhead. The most straightforward way to avoid this category of problems altogether is to make sure the contents of your Vue templates are always trusted and entirely controlled by you.
+Os _templates_ Vue são compilados em JavaScript, e as expressões dentro dos _templates_ serão executadas como parte do processo de renderização. Embora as expressões sejam avaliadas em um contexto de renderização específico, devido à complexidade de ambientes de execução global em potencial, é impraticável para um _framework_ como o Vue protegê-lo completamente de uma possível execução de código malicioso sem incorrer em sobrecarga de desempenho irreal. A maneira mais direta de evitar essa categoria de problemas é garantir que o conteúdo de seus _templates_ Vue seja sempre confiável e totalmente controlado por você.
-## What Vue Does to Protect You
+## Ações do Vue Para Te Proteger
-### HTML content
+### conteúdo HTML
-Whether using templates or render functions, content is automatically escaped. That means in this template:
+Seja usando _templates_ ou funções de renderização, o conteúdo é tratado automaticamente. Isso significa que neste _template_:
```html
{{ userProvidedString }}
```
-if `userProvidedString` contained:
+se `userProvidedString` continha:
```js
-''
+''
```
-then it would be escaped to the following HTML:
+então seria tratado para o seguinte HTML:
```html
-<script>alert("hi")</script>
+<script>alert("oi")</script>
```
-thus preventing the script injection. This escaping is done using native browser APIs, like `textContent`, so a vulnerability can only exist if the browser itself is vulnerable.
+evitando assim a injeção de script. Esse tratamento é feito usando APIs nativas do navegador, como `textContent`, portanto, uma vulnerabilidade só pode existir se o próprio navegador for vulnerável.
-### Attribute bindings
+### Vínculos de atributo
-Similarly, dynamic attribute bindings are also automatically escaped. That means in this template:
+Da mesma forma, os vínculos dinâmicos de atributos também são tratados automaticamente. Isso significa que neste _template_:
```html
- hello
+ Olá
```
-if `userProvidedString` contained:
+se `userProvidedString` continha:
```js
-'" onclick="alert(\'hi\')'
+'" onclick="alert(\'oi\')'
```
-then it would be escaped to the following HTML:
+então seria tratado para o seguinte HTML:
```html
-" onclick="alert('hi')
+" onclick="alert('oi')
```
-thus preventing the close of the `title` attribute to inject new, arbitrary HTML. This escaping is done using native browser APIs, like `setAttribute`, so a vulnerability can only exist if the browser itself is vulnerable.
+evitando assim o fechamento do atributo `title` para injetar um novo HTML arbitrário. Esse tratamento é feito usando APIs nativas do navegador, como `setAttribute`, portanto, uma vulnerabilidade só pode existir se o próprio navegador for vulnerável.
-## Potential Dangers
+## Potenciais Perigos
-In any web application, allowing unsanitized, user-provided content to be executed as HTML, CSS, or JavaScript is potentially dangerous, so should be avoided wherever possible. There are times when some risk may be acceptable though.
+Em qualquer aplicativo Web, permitir que conteúdo não sanitizado fornecido pelo usuário seja executado como HTML, CSS ou JavaScript é potencialmente perigoso, portanto, deve ser evitado sempre que possível. Há momentos em que algum risco pode ser aceitável.
-For example, services like CodePen and JSFiddle allow user-provided content to be executed, but it's in a context where this is expected and sandboxed to some extent inside iframes. In the cases when an important feature inherently requires some level of vulnerability, it's up to your team to weigh the importance of the feature against the worst-case scenarios the vulnerability enables.
+Por exemplo, serviços como CodePen e JSFiddle permitem que o conteúdo fornecido pelo usuário seja executado, mas é em um contexto em que isso é esperado e protegido até certo ponto dentro de iframes. Nos casos em que um recurso importante requer inerentemente algum nível de vulnerabilidade, cabe à sua equipe avaliar a importância do recurso em relação aos piores cenários que a vulnerabilidade permite.
-### Injecting HTML
+### Injetando HTML
-As you learned earlier, Vue automatically escapes HTML content, preventing you from accidentally injecting executable HTML into your application. However, in cases where you know the HTML is safe, you can explicitly render HTML content:
+Como aprendeu anteriormente, o Vue trata automaticamente o conteúdo HTML, evitando que você injete acidentalmente HTML executável em seu aplicativo. No entanto, nos casos em que sabe que o HTML é seguro, você pode renderizar explicitamente o conteúdo HTML:
-- Using a template:
+- Usando um _template_:
```html
```
-- Using a render function:
+- Usando uma função de renderização:
```js
h('div', {
@@ -90,54 +90,54 @@ As you learned earlier, Vue automatically escapes HTML content, preventing you f
})
```
-- Using a render function with JSX:
+- Usando uma função de renderização com JSX:
```jsx
```
-:::tip
-Note that user-provided HTML can never be considered 100% safe unless it's in a sandboxed iframe or in a part of the app where only the user who wrote that HTML can ever be exposed to it. Additionally, allowing users to write their own Vue templates brings similar dangers.
+:::tip Nota
+Observe que o HTML fornecido pelo usuário nunca pode ser considerado 100% seguro, a menos que esteja em um iframe em área restrita ou em uma parte do aplicativo em que apenas o usuário que escreveu esse HTML possa ser exposto a ele. Além disso, permitir que os usuários escrevam seus próprios _templates_ Vue traz perigos semelhantes.
:::
-### Injecting URLs
+### Injetando URLs
-In a URL like this:
+Em uma URL como esta:
```html
- click me
+ clique em mim
```
-There's a potential security issue if the URL has not been "sanitized" to prevent JavaScript execution using `javascript:`. There are libraries such as [sanitize-url](https://www.npmjs.com/package/@braintree/sanitize-url) to help with this, but note:
+Há um possível problema de segurança se o URL não tiver sido "sanitizado" para impedir a execução de JavaScript usando `javascript:`. Existem bibliotecas como [sanitize-url](https://www.npmjs.com/package/@braintree/sanitize-url) para ajudar com isso, mas observe:
-:::tip
-If you're ever doing URL sanitization on the frontend, you already have a security issue. User-provided URLs should always be sanitized by your backend before even being saved to a database. Then the problem is avoided for _every_ client connecting to your API, including native mobile apps. Also note that even with sanitized URLs, Vue cannot help you guarantee that they lead to safe destinations.
+:::tip Nota
+Se você está fazendo limpeza de URL no frontend, já tem um problema de segurança. Os URLs fornecidos pelo usuário devem sempre ser sanitizados pelo seu back-end antes mesmo de serem salvos em um banco de dados. Assim, o problema é evitado para _todos_ os clientes que se conectam à sua API, incluindo aplicativos móveis nativos. Observe também que, mesmo com URLs sanitizadas, o Vue não pode ajudá-lo a garantir que elas levem a destinos seguros.
:::
-### Injecting Styles
+### Injetando Estilos
-Looking at this example:
+Olhando para este exemplo:
```html
- click me
+ clique em mim
```
-let's assume that `sanitizedUrl` has been sanitized, so that it's definitely a real URL and not JavaScript. With the `userProvidedStyles`, malicious users could still provide CSS to "click jack", e.g. styling the link into a transparent box over the "Log in" button. Then if `https://user-controlled-website.com/` is built to resemble the login page of your application, they might have just captured a user's real login information.
+vamos supor que `sanitizedUrl` tenha sido sanitizado, então é definitivamente uma URL real e não JavaScript. Com o `userProvidedStyles`, usuários mal-intencionados ainda podem fornecer CSS para "_click jack_", por exemplo. estilizando o link em uma caixa transparente sobre o botão "Log in". Então, se `https://user-control-website.com/` for construído para se parecer com a página de login do seu aplicativo, eles podem ter capturado as informações de login reais de um usuário.
-You may be able to imagine how allowing user-provided content for a `
```
-To keep your users fully safe from click jacking, we recommend only allowing full control over CSS inside a sandboxed iframe. Alternatively, when providing user control through a style binding, we recommend using its [object syntax](class-and-style.html#object-syntax-2) and only allowing users to provide values for specific properties it's safe for them to control, like this:
+Para manter seus usuários totalmente protegidos contra o _click jacking_, recomendamos permitir apenas o controle total sobre o CSS dentro de um iframe em área restrita. Como alternativa, ao fornecer controle ao usuário por meio de um estilo com vínculo, recomendamos usar sua [sintaxe de objeto](class-and-style.html#sintaxe-de-objeto-2) e permitir que os usuários forneçam apenas valores para propriedades específicas que sejam seguras para eles controlarem , assim:
```html
- click me
+ clique em mim
```
-### Injecting JavaScript
+### Injetando JavaScript
-We strongly discourage ever rendering a `
- Toggle
+ Alternar
+
-## Transitions on Initial Render
+## Transições na Renderização Inicial
-If you also want to apply a transition on the initial render of a node, you can add the `appear` attribute:
+Se você também deseja aplicar uma transição na renderização inicial de um nó, você pode adicionar o atributo `appear`:
```html
@@ -413,38 +414,38 @@ If you also want to apply a transition on the initial render of a node, you can
```
-## Transitioning Between Elements
+## Transição Entre Elementos
-We discuss [transitioning between components](#transitioning-between-components) later, but you can also transition between raw elements using `v-if`/`v-else`. One of the most common two-element transitions is between a list container and a message describing an empty list:
+Nós discutiremos [transição entre componentes](#transicao-entre-componentes) mais tarde, mas você também pode fazer a transição entre os elementos brutos usando `v-if`/`v-else`. Uma das transições de dois elementos mais comuns é entre um contêiner de lista e uma mensagem que descreve uma lista vazia:
```html
- Sorry, no items found.
+ Desculpe, nenhum item encontrado.
```
-It's actually possible to transition between any number of elements, either by using `v-if`/`v-else-if`/`v-else` or binding a single element to a dynamic property. For example:
+Na verdade, é possível fazer a transição entre qualquer número de elementos, seja usando `v-if`/`v-else-if`/`v-else` ou vinculando um único elemento a uma propriedade dinâmica. Por exemplo:
-
+
```html
- Edit
+ Editar
- Save
+ Salvar
- Cancel
+ Cancelar
```
-Which could also be written as:
+Que também pode ser escrito como:
```html
@@ -459,54 +460,54 @@ Which could also be written as:
computed: {
buttonMessage() {
switch (this.docState) {
- case 'saved': return 'Edit'
- case 'edited': return 'Save'
- case 'editing': return 'Cancel'
+ case 'saved': return 'Editar'
+ case 'edited': return 'Salvar'
+ case 'editing': return 'Cancelar'
}
}
}
```
-### Transition Modes
+### Modos de Transição
-There's still one problem though. Try clicking the button below:
+Ainda há um problema. Experimente clicar no botão abaixo:
-
+
-As it's transitioning between the "on" button and the "off" button, both buttons are rendered - one transitioning out while the other transitions in. This is the default behavior of `` - entering and leaving happens simultaneously.
+À medida que faz a transição entre o botão "on" e o botão "off", os dois botões são renderizados - um faz a transição para fora e o outro para dentro. Este é o comportamento padrão do `` - entrada e saída acontecem simultaneamente.
-Sometimes this works great, like when transitioning items are absolutely positioned on top of each other:
+Às vezes, isso funciona muito bem, como quando os itens em transição são absolutamente posicionados um sobre o outro:
-
+
-Sometimes this isn't an option, though, or we're dealing with more complex movement where in and out states need to be coordinated, so Vue offers an extremely useful utility called **transition modes**:
+Às vezes, isso não é uma opção, ou estamos lidando com um movimento mais complexo onde os estados de entrada e saída precisam ser coordenados, então o Vue oferece um utilitário extremamente útil chamado **modos de transição**:
-- `in-out`: New element transitions in first, then when complete, the current element transitions out.
-- `out-in`: Current element transitions out first, then when complete, the new element transitions in.
+- `in-out`: Primeiro o novo elemento transita entrando, quando concluído, o elemento atual transita pra fora.
+- `out-in`: Primeiro o elemento atual transita saindo, quando concluído, o novo elemento transita entrando.
-::: tip
-You'll find very quickly that `out-in` is the state you will want most of the time :)
+::: tip Dica
+Você descobrirá muito rapidamente que `out-in` é o estado que você desejará na maior parte do tempo :)
:::
-Now let's update the transition for our on/off buttons with `out-in`:
+Agora vamos atualizar a transição para nossos botões on/off com `out-in`:
```html
-
+
```
-
+
-With one attribute addition, we've fixed that original transition without having to add any special styling.
+Com a adição de um atributo, corrigimos a transição original sem precisar adicionar nenhum estilo especial.
-We can use this to coordinate more expressive movement, such as a folding card, as demonstrated below. It's actually two elements transitioning between each other, but since the beginning and end states are scaling the same: horizontally to 0, it appears like one fluid movement. This type of sleight-of-hand can be very useful for realistic UI microinteractions:
+Podemos usar isso para coordenar movimentos mais expressivos, como um cartão dobrável, conforme demonstrado a seguir. Na verdade, são dois elementos em transição entre si, mas como os estados inicial e final estão na mesma escala: horizontalmente para 0, parece um movimento fluido. Este tipo de prestidigitação pode ser muito útil para microinterações de IU realistas:
-
+
-## Transitioning Between Components
+## Transição Entre Componentes
-Transitioning between components is even simpler - we don't even need the `key` attribute. Instead, we wrap a [dynamic component](component-basics.html#dynamic-components):
+A transição entre componentes é ainda mais simples - nem precisamos do atributo `key`. Em vez disso, envolvemos um [componente dinâmico](component-basics.html#componentes-dinamicos):
```html
@@ -527,10 +528,10 @@ const Demo = {
},
components: {
'v-a': {
- template: '
Component A
'
+ template: '
Componente A
'
},
'v-b': {
- template: '
Component B
'
+ template: '
Componente B
'
}
}
}
@@ -550,4 +551,4 @@ Vue.createApp(Demo).mount('#demo')
}
```
-
+
diff --git a/src/guide/transitions-list.md b/src/guide/transitions-list.md
index fa146ed64f..1c189a8b94 100644
--- a/src/guide/transitions-list.md
+++ b/src/guide/transitions-list.md
@@ -1,25 +1,25 @@
-# List Transitions
+# Transições de Listas
-So far, we've managed transitions for:
+Até agora, gerenciamos transições para:
-- Individual nodes
-- Multiple nodes where only 1 is rendered at a time
+- Nós individuais
+- Multiplos nós onde apenas 1 é renderizado por vez
-So what about for when we have a whole list of items we want to render simultaneously, for example with `v-for`? In this case, we'll use the `
` component. Before we dive into an example though, there are a few things that are important to know about this component:
+E quando tivermos toda uma lista de itens que queremos renderizar simultâneamente, com `v-for` por exemplo? Neste caso, usaremos o componente ``. Antes de entramos em um exemplo, existem algumas coisas que são importantes saber sobre esse componente:
-- By default, it doesn't render a wrapper element, but you can specify an element to be rendered with the `tag` attribute.
-- [Transition modes](/guide/transitions-enterleave.html#transition-modes) are not available, because we are no longer alternating between mutually exclusive elements.
-- Elements inside are **always required** to have a unique `key` attribute.
-- CSS transition classes will be applied to inner elements and not to the group/container itself.
+- Por padrão, ele não renderiza um elemento *wrapper*, mas você pode especificar um elemento a ser renderizado com o atributo `tag`.
+- Os [modos de transição](/guide/transitions-enterleave.html#transition-modes) não estão disponíveis, porque não estamos mais alternando entre elementos mutuamente exclusivos.
+- Os elementos internos **sempre precisam** ter um atributo `key` único.
+- As classes de transições CSS serão aplicadas aos elementos internos e não ao grupo/contêiner em si.
-## List Entering/Leaving Transitions
+### Transições de Entrada/Saída em Listas
-Now let's dive into an example, transitioning entering and leaving using the same CSS classes we've used previously:
+Agora iremos exemplificar, fazendo transições de entrada e saída usando as mesmas classes CSS que usamos anteriormente:
```html
-
Add
-
Remove
+
Adicionar
+
Remover
{{ item }}
@@ -68,21 +68,21 @@ Vue.createApp(Demo).mount('#list-demo')
}
```
-
+
-There's one problem with this example. When you add or remove an item, the ones around it instantly snap into their new place instead of smoothly transitioning. We'll fix that later.
+Existe um problema com esse exemplo. Quando você adiciona ou remove um item, os que estão ao redor se encaixam instantaneamente em seu novo lugar, em vez de realizarem uma transição suave. Corrigiremos isso depois.
-## List Move Transitions
+## Transições de Movimento em Listas
-The `` component has another trick up its sleeve. It can not only animate entering and leaving, but also changes in position. The only new concept you need to know to use this feature is the addition of **the `v-move` class**, which is added when items are changing positions. Like the other classes, its prefix will match the value of a provided `name` attribute and you can also manually specify a class with the `move-class` attribute.
+O componente `` tem outro truque na manga. Ele não apenas anima entrada e saída, como também anima mudanças nas posições. O único conceito novo que você precisa saber para usar esse recurso é a adição da **classe `v-move`**, que é adicionada quando os items estão mudando de posição. Assim como as outras classes, esse prefixo irá corresponder ao valor do atributo `name` fornecido e você pode especificar manualmente uma classe com o atributo `move-class`.
-This class is mostly useful for specifying the transition timing and easing curve, as you'll see below:
+Essa classe é útil principalmente para especificar o tempo de transição e a curva de atenuação, como você pode ver abaixo:
```html
-
Shuffle
+
Misturar
{{ item }}
@@ -114,19 +114,19 @@ Vue.createApp(Demo).mount('#flip-list-demo')
}
```
-
+
-This might seem like magic, but under the hood, Vue is using an animation technique called [FLIP](https://aerotwist.com/blog/flip-your-animations/) to smoothly transition elements from their old position to their new position using transforms.
+Isso pode parecer mágica, mas por baixo dos panos, o Vue está usando uma técnica de animação chamada [FLIP](https://aerotwist.com/blog/flip-your-animations/) para transicionar suavemente os elementos de sua antiga posição para a nova posição usando transformações.
-We can combine this technique with our previous implementation to animate every possible change to our list!
+Podemos combinar essa técnica com nossa implementação anterior para animar qualquer mudança possível em nossa lista!
```html
-
Shuffle
-
Add
-
Remove
+
Misturar
+
Adicionar
+
Remover
{{ item }}
@@ -180,19 +180,19 @@ Vue.createApp(Demo).mount('#list-complete-demo')
}
```
-
+
-::: tip
-One important note is that these FLIP transitions do not work with elements set to `display: inline`. As an alternative, you can use `display: inline-block` or place elements in a flex context.
+::: tip Nota
+É importante notar que essas transições FLIP não funcionam com elementos configurados com `display: inline`. Alternativamente, você pode usar `display: inline-block` ou posicionar os elementos em um contexto _flex_.
:::
-These FLIP animations are also not limited to a single axis. Items in a multidimensional grid can be [transitioned too](https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-list-move-transitions):
+Essas animações FLIP não são limitadas à um único eixo. Itens em um _grid_ multidimensional podem ser [transicionados também](https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-list-move-transitions):
-TODO: example
+TODO: exemplo
-## Staggering List Transitions
+## Escalonando Transições de Listas
-By communicating with JavaScript transitions through data attributes, it's also possible to stagger transitions in a list:
+Comunicando-se com transições JavaScript por meio de atributos de dados, também é possível escalonar as transições em uma lista:
```html
@@ -267,15 +267,15 @@ const Demo = {
Vue.createApp(Demo).mount('#demo')
```
-
+
-## Reusable Transitions
+## Transições Reutilizáveis
-Transitions can be reused through Vue's component system. To create a reusable transition, all you have to do is place a `` or `` component at the root, then pass any children into the transition component.
+Transições podem ser reutilizadas através do sistema de componentes do Vue. Para criar uma transição reutilizável tudo o que você precisa fazer é colocar um componente `` ou `` na raiz, e então passar qualquer filho para o componente de transição.
-TODO: refactor to Vue 3
+TODO: refatorar para o Vue 3
-Here's an example using a template component:
+Veja um exemplo usando um componente com _template_:
```js
Vue.component('my-special-transition', {
@@ -300,7 +300,7 @@ Vue.component('my-special-transition', {
})
```
-And [functional components](render-function.html#functional-components) are especially well-suited to this task:
+[Componentes funcionais](render-function.html#functional-components) são especialmente adequados para esta tarefa:
```js
Vue.component('my-special-transition', {
@@ -325,9 +325,9 @@ Vue.component('my-special-transition', {
})
```
-## Dynamic Transitions
+## Transições Dinâmicas
-Yes, even transitions in Vue are data-driven! The most basic example of a dynamic transition binds the `name` attribute to a dynamic property.
+Sim, até mesmo as transições no Vue são baseadas em dados! O exemplo mais trivial de uma transição dinâmica vincula o atributo `name` à uma propriedade dinâmica.
```html
@@ -335,9 +335,9 @@ Yes, even transitions in Vue are data-driven! The most basic example of a dynami
```
-This can be useful when you've defined CSS transitions/animations using Vue's transition class conventions and want to switch between them.
+Isso pode ser útil quando você definiu transições/animações CSS usando as convenções de classes de transição do Vue e quer alternar entre elas.
-Really though, any transition attribute can be dynamically bound. And it's not only attributes. Since event hooks are methods, they have access to any data in the context. That means depending on the state of your component, your JavaScript transitions can behave differently.
+Na verdade, qualquer atributo de transição pode ser vinculado dinamicamente. E não somente atributos. Como gatilhos de eventos são métodos, eles possuem acesso à qualquer dado no contexto. Isso significa que, dependendo do estado do seu componente, as transições do JavaScript podem se comportar de maneira diferente.
```html
@@ -358,12 +358,12 @@ Really though, any transition attribute can be dynamically bound. And it's not o
@enter="enter"
@leave="leave"
>
- hello
+ olá
- Start animating
+ Iniciar animação
- Stop it!
+ Parar!
```
@@ -419,6 +419,6 @@ const app = Vue.createApp({
app.mount('#dynamic-fade-demo')
```
-TODO: example
+TODO: exemplo
-Finally, the ultimate way of creating dynamic transitions is through components that accept props to change the nature of the transition(s) to be used. It may sound cheesy, but the only limit really is your imagination.
+Finalmente, a melhor maneira de criar transições dinâmicas é por meio de componentes que aceitam propriedades para mudar a natureza das transições à serem usadas. Pode soar clichê, mas o único limite realmente é sua imaginação.
diff --git a/src/guide/transitions-overview.md b/src/guide/transitions-overview.md
index ee20b1c262..32e5734901 100644
--- a/src/guide/transitions-overview.md
+++ b/src/guide/transitions-overview.md
@@ -1,27 +1,27 @@
-# Overview
+# Visão Geral
-Vue offers some abstractions that can help work with transitions and animations, particularly in response to something changing. Some of these abstractions include:
+Vue oferece algumas abstrações que podem lhe ajudar a trabalhar com transições e animações, particularmente em resposta à mudança de algo. Algumas dessas abstrações incluem:
-- Hooks for components entering and leaving the DOM, in both CSS and JS, using the built-in `` component.
-- Transition Modes so that you can orchestrate ordering during a transition.
-- Hooks for when multiple elements are updating in position, with FLIP techniques applied under the hood to increase performance, using the `` component.
-- Transitioning different states in an application, with `watchers`.
+- Gatilhos para componentes entrando e saindo do DOM, em CSS e JS, usando o componente interno ``.
+- Modos de Transição para que você possa orquestrar a ordenação durante a transição.
+- Gatilhos para quando múltiplos elementos estão atualizando em posição, com técnicas FLIP aplicadas em seu interior para aumentar a performance, usando o componente ``.
+- Transição de diferentes estados em uma aplicação, com `watchers`.
-We will cover all of these and more in the next three sections in this Guide. However, aside from these useful API offerings, it's worth mentioning that the class and style declarations we covered earlier can be used to apply animations and transitions as well, for more simple use cases.
+Vamos cobrir todos esses e mais nas próximas seções deste guia. Contudo, além dessas ofertas úteis de API, é importante mencionar que as declarações de classe e estilo mencionadas antes podem também ser usadas para aplicar animações e transições, para casos de uso simplificados.
-In this next section, we'll go over some web animation and transitions basics, and link off to some resources for further exploration. If you're already familiar with web animation and how those principles might work with some of Vue's directives, feel free to skip this next section. For anyone else looking to learn a little more about web animation basics before diving in, read on.
+Na próxima seção, vamos passar por conceitos básicos de transições e animações web, assim como oferecer links para alguns destes recursos para exploração posterior. Se você já estiver familiarizado com animação web e como estes princípios podem funcionar com algumas das directivas do Vue, sinta-se livre para pular a próxima seção. Para quem estiver buscando aprender mais sobre os básicos de animação web, continue a leitura.
-## Class-based Animations & Transitions
+## Animações & Transições Baseadas em Classes
-Though the `` component can be wonderful for components entering and leaving, you can also activate an animation without mounting a component, by adding a conditional class.
+Ainda que o componente `` pode ser maravilhoso para componentes que entram e saem, você também pode ativar uma animação sem montar um componente, adicionando uma classe condicional.
```html
- Push this button to do something you shouldn't be doing:
+ Aperte este botão para fazer algo que você não deveria estar fazendo:
- Click me
- Oh no!
+ Clique-me
+ Ah não!
```
@@ -70,11 +70,16 @@ const Demo = {
Vue.createApp(Demo).mount('#demo')
```
-
+
+ Veja o exemplo
+ Criar a animação por meio de uma classe por Vue (@Vue )
+ no CodePen .
+
+
-## Transitions with Style Bindings
+## Transições com Ligações de Estilo
-Some transition effects can be applied by interpolating values, for instance by binding a style to an element while an interaction occurs. Take this example for instance:
+Alguns efeitos de transições podem ser aplicados pela interpolação de valores, por exemplo, ao ligar um estilo com um elemento enquanto ocorre uma interação. Veja o seguinte exemplo:
```html
@@ -83,7 +88,7 @@ Some transition effects can be applied by interpolating values, for instance by
:style="{ backgroundColor: `hsl(${x}, 80%, 50%)` }"
class="movearea"
>
-
Move your mouse across the screen...
+
Mexa o seu mouse pela tela...
x: {{x}}
@@ -112,29 +117,29 @@ const Demo = {
Vue.createApp(Demo).mount('#demo')
```
-
+
-In this example, we are creating animation through the use of interpolation, attached to the mouse movement. The CSS transition is applied to the element as well, to let the element know what kind of easing to use while it's updating.
+Neste exemplo, estamos criando uma animação por meio do uso de interpolação, adjunto ao movimento do mouse. A transição CSS é aplicada ao elemento também, permitindo que o elemento saiba que tipo de atenuação é usada ao se atualizar.
## Performance
-You may notice that the animations shown above are using things like `transforms`, and applying strange properties like `perspective`- why were they built that way instead of just using `margin` and `top` etc?
+Você pode perceber que as animações mostradas acima estão usando coisas como `transforms`, e aplicando propriedades estranhas como `perspective` - por que foram construídos assim em vez de simplesmente usar `margin` e `top`, etc?
-We can create extremely smooth animations on the web by being aware of performance. We want to hardware accelerate elements when we can, and use properties that don't trigger repaints. Let's go over some of how we can accomplish this.
+Podemos criar animações extremamente suaves para a web estando cientes da performance. Queremos que o hardware acelere elementos quando pudermos, e que use as propriedades que não disparem a repintura dos mesmos. Vamos ver como podemos fazer isso.
-### Transform and Opacity
+### Transformações e Opacidade
-We can check resources like [CSS-Triggers](https://csstriggers.com/) to see which properties will trigger repaints if we animate them. Here, if you look under `transform`, you will see:
+Podemos verificar recursos como [Gatilhos CSS](https://csstriggers.com) para vermos quais propriedades vão desencadear repinturas se nós a animarmos. Aqui, caso você olhe a parte de `transform`, você verá:
-> Changing transform does not trigger any geometry changes or painting, which is very good. This means that the operation can likely be carried out by the compositor thread with the help of the GPU.
+> As mudanças do `transform` não desencadeiam mudanças geométricas ou de pintura, o que é muito bom. Isso significa que a operação provavelmente será realizada pela _thread_ de composição com o auxílio da GPU.
-Opacity behaves similarly. Thus, they are ideal candidates for movement on the web.
+A opacidade se comporta de maneira similar. Assim, são candidatos ideais para movimentos na web.
-### Hardware Acceleration
+### Aceleração de Hardware
-Properties such as `perspective`, `backface-visibility`, and `transform: translateZ(x)` will allow the browser to know you need hardware acceleration.
+Propriedades como `perspective`, `backface-visibility`, e `transform: translateZ(x)` vão permitir ao browser saber quando se necessita de aceleração de hardware.
-If you wish to hardware-accelerate an element, you can apply any of these properties (not all are necessary, only one):
+Se você gostaria de acelerar o hardware de um elemento, você pode aplicar qualquer uma dessas propriedades (não necessariamente só uma):
```css
perspective: 1000px;
@@ -142,49 +147,49 @@ backface-visibility: hidden;
transform: translateZ(0);
```
-Many JS libraries like GreenSock will assume you want hardware acceleration and will apply them by default, so you do not need to set them manually.
+Muitas bibliotecas JS como GreenSock vão assumir que você quer aceleração de hardware e as vão aplicar por padrão, assim você não precisa configurá-las manualmente.
-## Timing
+## Tempo de Animação
-For simple UI transitions, meaning from just one state to another with no intermediary states, it's common to use timings between 0.1s and 0.4s, and most folks find that _0.25s_ tends to be a sweet spot. Can you use that timing for everything? No, not really. If you have something that needs to move a greater distance or has more steps or state changes, 0.25s is not going to work as well and you will have to be much more intentional, and the timing will need to be more unique. That doesn't mean you can't have nice defaults that you repeat within your application, though.
+Para transições de UI simples, de um estado para outro sem estados intermediários, é comum usar tempos entre 0.1s e 0.4s, e muitas pessoas acham que _0.25s_ tende a ser o ponto certo. Você pode usar este tempo para tudo? Não necessariamente. Se você tem algo que precisa se mover uma distância maior ou que tenha mais passos ou mudanças de estado, 0.25s não vai funcionar tão bem e você terá que ser muito mais intencional, e o tempo terá a necessidade de ser mais único. O que não significa que você não possa ter ótimos padrões que você repete dentro da sua aplicação.
-You may also find that entrances look better with slightly more time than an exit. The user typically is being guided during the entrance, and is a little less patient upon exit because they want to go on their way.
+Você também pode se dar conta de que entradas têm uma aparência melhor com um pouco mais de tempo que uma saída. O usuário tipicamente está sendo guiado durante uma entrada e é um pouco menos paciente na saída, por que querem seguir seu caminho.
-## Easing
+## Atenuação
Easing is an important way to convey depth in an animation. One of the most common mistakes newcomers to animation make is to use `ease-in` for entrances, and `ease-out` for exits. You'll actually need the opposite.
-If we were to apply these states to a transition, it would look something like this:
+Se tivéssemos que aplicar estes estados a uma transição, ela ficaria algo assim:
```css
.button {
background: #1b8f5a;
- /* applied to the initial state, so this transition will be applied to the return state */
+ /* aplicada ao estado inicial, assim esta transição será aplicada ao estado de retorno */
transition: background 0.25s ease-in;
}
.button:hover {
background: #3eaf7c;
- /* applied to the hover state, so this transition will be applied when a hover is triggered */
+ /* aplicada ao estado de hover, assim esta transição será aplicada quando um hover é acionado. */
transition: background 0.35s ease-out;
}
```
-
+
-Easing can also convey the quality of material being animated. Take this pen for example, which ball do you think is hard and which is soft?
+A atenuação pode inclusive transmitir a qualidade do material sendo animado. Olhe este pen, por exemplo, qual bola você acha que é rígida e qual é macia?
-
+
-You can get a lot of unique effects and make your animation very stylish by adjusting your easing. CSS allows you to modify this by adjusting the cubic-bezier function's parameters, [this playground](https://cubic-bezier.com/#.17,.67,.83,.67) by Lea Verou is very helpful for exploring this.
+Você pode obter muitos efeitos únicos e fazer sua animação bem estilosa ajustando sua atenuação. O CSS lhe permite modificar isso ajustando os parâmetros da função _cubic-bezier_, [este playground](https://cubic-bezier.com/#.17,.67,.83,.67) por Lea Verou é muito útil para explorar isso.
-Though you can achieve great effects for simple animation with the two handles the cubic-bezier ease offers, JavaScript allows multiple handles, and therefore, allows for much more variance.
+Apesar de que você possa alcançar grandes efeitos para animações simples com as duas alças que a acentuação por bezier-cúbico oferece, Javascript permite múltiplas alças, e portanto, permite muito mais variação.
-
+
-Take a bounce, for instance. In CSS we have to declare each keyframe, up and down. In JavaScript, we can express all of that movement within the ease, by declaring `bounce` in the [GreenSock API (GSAP)](https://greensock.com/) (other JS libraries have other types of easing defaults).
+Tomemos um efeito de salto, por exemplo. Em CSS temos que declarar cada keyframe, para cima e para baixo. Em JavaScript, podemos expressar todo o movimento dentro da acentuação declarando `bounce` na [API GreenSock (GSAP)](https://greensock.com/) (outras bibliotecas JS têm outros tipos de padrões de acentuação).
-Here is the code used for a bounce in CSS (example from animate.css):
+Aqui está o código usado para o salto em CSS (exemplo de animate.css):
```css
@keyframes bounceInDown {
@@ -224,15 +229,15 @@ Here is the code used for a bounce in CSS (example from animate.css):
}
```
-And here is the same bounce in JS using GreenSock:
+E aqui está o mesmo salto em JS usando GreenSock:
```js
gsap.from(element, { duration: 1, ease: 'bounce.out', y: -500 })
```
-We'll be using GreenSock in some of the examples in the sections following. They have a great [ease visualizer](https://greensock.com/ease-visualizer) that will help you build nicely crafted eases.
+Vamos usar o GreenSock para alguns dos exemplos nas seções seguintes. Eles têm um ótimo [visualizador de atenuação](https://greensock.com/ease-visualizer) que vai lhe permitir construir atenuações bem trabalhadas.
-## Further Reading
+## Leituras Adicionais
-- [Designing Interface Animation: Improving the User Experience Through Animation by Val Head](https://www.amazon.com/dp/B01J4NKSZA/)
+- [Designing Interface Animation: Improving the User Experience Through Animation by Val Head](https://www.amazon.com.br/dp/B01J4NKSZA)
- [Animation at Work by Rachel Nabors](https://abookapart.com/products/animation-at-work)
diff --git a/src/guide/transitions-state.md b/src/guide/transitions-state.md
index 7310b3819a..eeca547194 100644
--- a/src/guide/transitions-state.md
+++ b/src/guide/transitions-state.md
@@ -1,17 +1,17 @@
-# State Transitions
+# Transições de Estado
-Vue's transition system offers many simple ways to animate entering, leaving, and lists, but what about animating your data itself? For example:
+O sistema de transição do Vue oferece muitas maneiras simples de animar entradas, saídas e listas, mas que tal animar seus próprios dados? Por exemplo:
-- numbers and calculations
-- colors displayed
-- the positions of SVG nodes
-- the sizes and other properties of elements
+- números e cálculos
+- cores exibidas
+- as posições dos nós (*nodes*) SVG
+- os tamanhos e outras propriedades dos elementos
-All of these are either already stored as raw numbers or can be converted into numbers. Once we do that, we can animate these state changes using 3rd-party libraries to tween state, in combination with Vue's reactivity and component systems.
+Todos eles já estão armazenados como números brutos ou podem ser convertidos em números. Depois de fazer isso, podemos animar essas mudanças de estado usando bibliotecas de terceiros para interpolar o estado, em combinação com a reatividade e os sistemas de componentes do Vue.
-## Animating State with Watchers
+## Animando Estado com Observadores
-Watchers allow us to animate changes of any numerical property into another property. That may sound complicated in the abstract, so let's dive into an example using [GreenSock](https://greensock.com/):
+Os observadores nos permitem animar mudanças de qualquer propriedade numérica em outra propriedade. Isso pode parecer complicado no abstrato, então vamos mergulhar em um exemplo usando [GreenSock](https://greensock.com/):
```html
@@ -45,19 +45,19 @@ const Demo = {
Vue.createApp(Demo).mount('#animated-number-demo')
```
-
+
-When you update the number, the change is animated below the input.
+Quando você atualiza o número, a mudança é animada abaixo do `input`.
-## Dynamic State Transitions
+## Transições de Estado Dinâmicas
-As with Vue's transition components, the data backing state transitions can be updated in real time, which is especially useful for prototyping! Even using a simple SVG polygon, you can achieve many effects that would be difficult to conceive of until you've played with the variables a little.
+Tal como acontece com os componentes de transição do Vue, os dados nos quais as transições de estado se baseiam podem ser atualizados em tempo real, o que é especialmente útil para prototipagem! Mesmo usando um polígono SVG simples, você pode obter muitos efeitos que seriam difíceis de conceber até que você brincasse um pouco com as variáveis.
-
+
-## Organizing Transitions into Components
+## Organizando Transições em Componentes
-Managing many state transitions can quickly increase the complexity of a component instance. Fortunately, many animations can be extracted out into dedicated child components. Let's do this with the animated integer from our earlier example:
+Gerenciar muitas transições de estado pode aumentar rapidamente a complexidade de uma instância de componente. Felizmente, muitas animações podem ser extraídas em componentes filhos dedicados. Vamos fazer isso com o número inteiro animado de nosso exemplo anterior:
```html
@@ -128,18 +128,18 @@ app.component('animated-integer', {
app.mount('#app')
```
-
+
-Now we can compose multiple states with these child components. It's exciting- we can use any combination of transition strategies that have been covered on this page, along with those offered by Vue's [built-in transition system](transitions-enterleave.html). Together, there are very few limits to what can be accomplished.
+Agora podemos compor vários estados com esses componentes filhos. É empolgante - podemos usar qualquer combinação de estratégias de transição que foram abordadas nesta página, junto com as oferecidas pelo [sistema de transição integrado](transitions-enterleave.html) do Vue. Juntos, existem poucos limites para o que pode ser realizado.
-You can see how we could use this for data visualization, for physics effects, for character animations and interactions, the sky's the limit.
+Você pode ver como podemos usar isso para visualização de dados, efeitos de física, animações e interações de personagens, o céu é o limite!
-## Bringing Designs to Life
+## Trazendo Designs à Vida
-To animate, by one definition, means to bring to life. Unfortunately, when designers create icons, logos, and mascots, they're usually delivered as images or static SVGs. So although GitHub's octocat, Twitter's bird, and many other logos resemble living creatures, they don't really seem alive.
+Animar, por uma definição, significa trazer à vida. Infelizmente, quando os designers criam ícones, logotipos e mascotes, eles geralmente são entregues como imagens ou SVGs estáticos. Portanto, embora o polvo-gato do GitHub, o pássaro do Twitter e muitos outros logotipos se assemelhem à criaturas vivas, eles não parecem realmente vivos.
-Vue can help. Since SVGs are just data, we only need examples of what these creatures look like when excited, thinking, or alarmed. Then Vue can help transition between these states, making your welcome pages, loading indicators, and notifications more emotionally compelling.
+O Vue pode ajudar. Como os SVGs são apenas dados, precisamos apenas de exemplos de como essas criaturas se parecem quando empolgadas, pensando ou alarmadas. O Vue pode ajudar na transição entre esses estados, tornando suas páginas de boas-vindas, indicadores de carregamento e notificações mais emocionalmente atraentes.
-Sarah Drasner demonstrates this in the demo below, using a combination of timed and interactivity-driven state changes:
+Sarah Drasner demonstra isso abaixo, usando uma combinação de mudanças de estado cronometradas e orientadas à interatividade:
-
+
diff --git a/src/guide/typescript-support.md b/src/guide/typescript-support.md
index c8363a08ef..c8c62401a9 100644
--- a/src/guide/typescript-support.md
+++ b/src/guide/typescript-support.md
@@ -1,12 +1,12 @@
-# TypeScript Support
+# Suporte ao TypeScript
-> [Vue CLI](https://cli.vuejs.org) provides built-in TypeScript tooling support.
+> O [Vue CLI](https://cli.vuejs.org) fornece ferramentas integradas de suporte ao TypeScript.
-## Official Declaration in NPM Packages
+## Declaração Oficial em Pacotes NPM
-A static type system can help prevent many potential runtime errors as applications grow, which is why Vue 3 is written in TypeScript. This means you don't need any additional tooling to use TypeScript with Vue - it has first-class citizen support.
+Um sistema de tipagem estática pode ajudar à prevenir diversos potenciais erros de _runtime_ conforme as aplicações crescem, é por isso que o Vue 3 é escrito em TypeScript. Isso significa que você não precisa de nenhum ferramental adicional para usar TypeScript com Vue - temos um suporte de primeiro mundo.
-## Recommended Configuration
+## Configuração Recomendada
```js
// tsconfig.json
@@ -14,7 +14,7 @@ A static type system can help prevent many potential runtime errors as applicati
"compilerOptions": {
"target": "esnext",
"module": "esnext",
- // this enables stricter inference for data properties on `this`
+ // isso permite uma inferência mais estrita para propriedades de dados no `this`
"strict": true,
"jsx": "preserve",
"moduleResolution": "node"
@@ -22,13 +22,13 @@ A static type system can help prevent many potential runtime errors as applicati
}
```
-Note that you have to include `strict: true` (or at least `noImplicitThis: true` which is a part of `strict` flag) to leverage type checking of `this` in component methods otherwise it is always treated as `any` type.
+Observe que você precisa incluir `strict: true` (ou ao menos `noImplicitThis: true`, que é uma parte da _flag_ `strict`) para aumentar a checagem de tipos do `this` em métodos de componentes, caso contrário, será sempre tratado como tipo `any`.
-See [TypeScript compiler options docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html) for more details.
+Veja a [documentação das opções do compilador TypeScript](https://www.typescriptlang.org/docs/handbook/compiler-options.html) para mais detalhes.
-## Webpack Configuration
+## Configuração do Webpack
-If you are using a custom Webpack configuration `ts-loader` needs to be configured to parse `
```
-Or, if you want to combine TypeScript with a [JSX `render` function](/guide/render-function.html#jsx):
+Ou, se você deseja combinar TypeScript com uma [função `render` do JSX](/guide/render-function.html#jsx):
```html
```
-### Editor Support
+### Suporte do Editor
-For developing Vue applications with TypeScript, we strongly recommend using [Visual Studio Code](https://code.visualstudio.com/), which provides great out-of-the-box support for TypeScript. If you are using [single-file components](./single-file-component.html) (SFCs), get the awesome [Volar extension](https://github.com/johnsoncodehk/volar), which provides TypeScript inference inside SFCs and many other great features.
+Para o desenvolvimento de aplicações Vue com TypeScript, nós recomendamos fortemente o uso do [Visual Studio Code](https://code.visualstudio.com/), que fornece um excelente suporte para o TypeScript. Se você está usando [componentes Single File](./single-file-component.html) (SFCs), obtenha a incrível [extensão Volar](https://github.com/johnsoncodehk/volar), que provê a inferência do TypeScript dentro de SFCs e muitos outros ótimos recursos.
-[WebStorm](https://www.jetbrains.com/webstorm/) provides out of the box support for both TypeScript and Vue. Other JetBrains IDEs also support them, either out of the box or via [this free plugin](https://plugins.jetbrains.com/plugin/9442-vue-js).
+O [WebStorm](https://www.jetbrains.com/webstorm/) fornece um suporte pronto para uso de ambos, TypeScript e Vue. Outras IDEs da JetBrains também os suportam, seja prontamente ou via [este plugin gratuito](https://plugins.jetbrains.com/plugin/9442-vue-js).
-## Defining Vue Components
+## Definindo Componentes Vue
-To let TypeScript properly infer types inside Vue component options, you need to define components with `defineComponent` global method:
+Para permitir ao TypeScript inferir corretamente os tipos dentro das opções do componente Vue, você precisa definir os componentes com o método global `defineComponent`:
```ts
import { defineComponent } from 'vue'
const Component = defineComponent({
- // type inference enabled
+ // inferência de tipos habilitada
})
```
-If you're using [single-file components](/guide/single-file-component.html) then this would typically be written as:
+Se você estiver usando [componentes single-file](/guide/single-file-component.html), isso normalmente seria escrito assim:
```vue
```
-## Using with Options API
+## Usando com a API de Opções
-TypeScript should be able to infer most of the types without defining types explicitly. For example, if you have a component with a number `count` property, you will have an error if you try to call a string-specific method on it:
+O TypeScript deve ser capaz de inferir a maioria dos tipos sem defini-los explicitamente. Por exemplo, se você tem um componente com uma propriedade numérica `count`, você receberá um erro se tentar chamar um método específico de _string_ nela.
```ts
const Component = defineComponent({
@@ -126,12 +126,12 @@ const Component = defineComponent({
}
},
mounted() {
- const result = this.count.split('') // => Property 'split' does not exist on type 'number'
+ const result = this.count.split('') // => A propriedade 'split' não existe no tipo 'number'
}
})
```
-If you have a complex type or interface, you can cast it using [type assertion](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions):
+Se você tem um tipo complexo ou uma interface, pode convertê-lo(a) usando a [afirmação de tipo](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions):
```ts
interface Book {
@@ -144,8 +144,8 @@ const Component = defineComponent({
data() {
return {
book: {
- title: 'Vue 3 Guide',
- author: 'Vue Team',
+ title: 'Guia do Vue 3',
+ author: 'Time do Vue',
year: 2020
} as Book
}
@@ -153,30 +153,30 @@ const Component = defineComponent({
})
```
-### Augmenting Types for `globalProperties`
+### Ampliando Tipos para `globalProperties`
-Vue 3 provides a [`globalProperties` object](../api/application-config.html#globalproperties) that can be used to add a global property that can be accessed in any component instance. For example, a [plugin](./plugins.html#writing-a-plugin) might want to inject a shared global object or function.
+O Vue 3 fornece um [objeto `globalProperties`](../api/application-config.html#globalproperties) que pode ser usado para adicionar uma propriedade global que pode ser acessada em qualquer instância do componente. Por exemplo, um [plugin](./plugins.html#escrevendo-um-plugin) pode querer injetar um objeto ou função global compartilhado.
```ts
-// User Definition
+// Definição do Usuário
import axios from 'axios'
const app = Vue.createApp({})
app.config.globalProperties.$http = axios
-// Plugin for validating some data
+// Plugin para validar alguns dados
export default {
install(app, options) {
app.config.globalProperties.$validate = (data: object, rule: object) => {
- // check whether the object meets certain rules
+ // verifica se o objeto atende a certas regras
}
}
}
```
-In order to tell TypeScript about these new properties, we can use [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
+Para informar o TypeScript sobre essas novas propriedades, podemos usar [aumento de módulos](https://www.typescriptlang.org/pt/docs/handbook/declaration-merging.html#aumento-de-m%C3%B3dulos).
-In the above example, we could add the following type declaration:
+No exemplo acima, poderíamos adicionar a seguinte declaração de tipo:
```ts
import axios from 'axios'
@@ -189,19 +189,19 @@ declare module '@vue/runtime-core' {
}
```
-We can put this type declaration in the same file, or in a project-wide `*.d.ts` file (for example, in the `src/typings` folder that is automatically loaded by TypeScript). For library/plugin authors, this file should be specified in the `types` property in `package.json`.
+Podemos colocar esta declaração de tipo no mesmo arquivo, ou em um arquivo `*.d.ts` acessível por todo o projeto (por exemplo, na pasta `src/typings` que é carregada automaticamente pelo TypeScript). Para autores de biblioteca/plugin, este arquivo deve ser especificado na propriedade `types` em `package.json`.
-::: warning Make sure the declaration file is a TypeScript module
-In order to take advantage of module augmentation, you will need to ensure there is at least one top-level `import` or `export` in your file, even if it is just `export {}`.
+::: warning Verifique se o arquivo de declaração é um módulo TypeScript
+Para aproveitar o aumento do módulo, você precisará garantir que haja pelo menos um `import` ou `export` de nível superior em seu arquivo, mesmo que seja apenas `export {}`.
-[In TypeScript](https://www.typescriptlang.org/docs/handbook/modules.html), any file containing a top-level `import` or `export` is considered a 'module'. If type declaration is made outside of a module, it will overwrite the original types rather than augmenting them.
+[No TypeScript](https://www.typescriptlang.org/pt/docs/handbook/modules.html), qualquer arquivo que contenha um `import` ou `export` de nível superior é considerado um 'módulo'. Se a declaração de tipo for feita fora de um módulo, ela substituirá os tipos originais em vez de aumentá-los.
:::
-For more information about the `ComponentCustomProperties` type, see its [definition in `@vue/runtime-core`](https://github.com/vuejs/vue-next/blob/2587f36fe311359e2e34f40e8e47d2eebfab7f42/packages/runtime-core/src/componentOptions.ts#L64-L80) and [the TypeScript unit tests](https://github.com/vuejs/vue-next/blob/master/test-dts/componentTypeExtensions.test-d.tsx) to learn more.
+Para obter mais informações sobre o tipo `ComponentCustomProperties`, consulte sua [definição em `@vue/runtime-core`](https://github.com/vuejs/vue-next/blob/2587f36fe311359e2e34f40e8e47d2eebfab7f42/packages/runtime-core/src/componentOptions.ts#L64-L80) e [os testes de unidade do TypeScript](https://github.com/vuejs/vue-next/blob/master/test-dts/componentTypeExtensions.test-d.tsx) para saber mais .
-### Annotating Return Types
+### Anotando Tipos de Retorno
-Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of computed. For this reason, you may need to annotate the return type of computed properties.
+Por causa da natureza circular dos arquivos de declaração do Vue, o TypeScript pode ter dificuldades para inferir os tipos de dados computados. Por esse motivo, você precisa anotar o tipo do retorno de propriedades computadas.
```ts
import { defineComponent } from 'vue'
@@ -213,12 +213,12 @@ const Component = defineComponent({
}
},
computed: {
- // needs an annotation
+ // precisa de uma anotação
greeting(): string {
return this.message + '!'
},
- // in a computed with a setter, getter needs to be annotated
+ // em uma computada com um setter, o getter precisa ser anotado
greetingUppercased: {
get(): string {
return this.greeting.toUpperCase()
@@ -231,9 +231,9 @@ const Component = defineComponent({
})
```
-### Annotating Props
+### Anotando Propriedades
-Vue does a runtime validation on props with a `type` defined. To provide these types to TypeScript, we need to cast the constructor with `PropType`:
+O Vue faz uma validação em runtime em propriedades com um `type` definido. Para fornecer esses tipos para o TypeScript, precisamos converter o construtor com `PropType`:
```ts
import { defineComponent, PropType } from 'vue'
@@ -302,33 +302,33 @@ const Component = defineComponent({
})
```
-### Annotating Emits
+### Anotando Tipos de Eventos Emitidos
-We can annotate a payload for the emitted event. Also, all non-declared emitted events will throw a type error when called:
+Podemos anotar o tipo do *payload* de um evento emitido. Além disso, todos os eventos emitidos não declarados lançarão um erro de tipo quando chamados:
```ts
const Component = defineComponent({
emits: {
addBook(payload: { bookName: string }) {
- // perform runtime validation
+ // executa validação em tempo de execução
return payload.bookName.length > 0
}
},
methods: {
onSubmit() {
this.$emit('addBook', {
- bookName: 123 // Type error!
+ bookName: 123 // Erro de tipo!
})
- this.$emit('non-declared-event') // Type error!
+ this.$emit('non-declared-event') // Erro de tipo!
}
}
})
```
-## Using with Composition API
+## Usando com a API de Composição
-On `setup()` function, you don't need to pass a typing to `props` parameter as it will infer types from `props` component option.
+Na função `setup()`, você não precisa passar um tipo para o parâmetro `props`, pois os tipos serão inferidos da opção `props` do componente.
```ts
import { defineComponent } from 'vue'
@@ -342,15 +342,15 @@ const Component = defineComponent({
},
setup(props) {
- const result = props.message.split('') // correct, 'message' is typed as a string
- const filtered = props.message.filter(p => p.value) // an error will be thrown: Property 'filter' does not exist on type 'string'
+ const result = props.message.split('') // correto, 'message' é tipada como uma string
+ const filtered = props.message.filter(p => p.value) // um erro será disparado: Propriedade 'filter' não existe no tipo 'string'
}
})
```
-### Typing `refs`
+### Tipando `refs`
-Refs infer the type from the initial value:
+Refs inferem o tipo do valor inicial:
```ts
import { defineComponent, ref } from 'vue'
@@ -359,26 +359,26 @@ const Component = defineComponent({
setup() {
const year = ref(2020)
- const result = year.value.split('') // => Property 'split' does not exist on type 'number'
+ const result = year.value.split('') // => Propriedade 'split' não existe no tipo 'number'
}
})
```
-Sometimes we may need to specify complex types for a ref's inner value. We can do that by simply passing a generic argument when calling ref to override the default inference:
+Algumas vezes, podemos precisar especificar tipos complexos para o valor interno de uma ref. Podemos fazer isso simplesmente passando um argumento genérico ao chamar ref para sobrescrever a inferência padrão:
```ts
-const year = ref('2020') // year's type: Ref
+const year = ref('2020') // tipo do year: Ref
year.value = 2020 // ok!
```
-::: tip Note
-If the type of the generic is unknown, it's recommended to cast `ref` to `Ref`.
+::: tip Nota
+Se o tipo do genérico é desconhecido, é recomendado converter `ref` para `Ref`.
:::
-### Typing Template Refs
+### Tipando Refs de _Template_
-Sometimes you might need to annotate a template ref for a child component in order to call its public method. For example, we have a `MyModal` child component with a method that opens the modal:
+Às vezes você pode precisar anotar um ref de _template_ para um componente filho para poder chamar seu método público. Por exemplo, temos um componente filho `MyModal` com um método que abre o modal:
```ts
import { defineComponent, ref } from 'vue'
@@ -396,7 +396,7 @@ const MyModal = defineComponent({
})
```
-We want to call this method via a template ref from the parent component:
+Queremos chamar esse método por meio de um ref de _template_ do componente pai:
```ts
import { defineComponent, ref } from 'vue'
@@ -418,7 +418,7 @@ const app = defineComponent({
MyModal
},
template: `
- Open from parent
+ Abrir pelo pai
`,
setup() {
@@ -432,7 +432,7 @@ const app = defineComponent({
})
```
-While this will work, there is no type information about `MyModal` and its available methods. To fix this, you should use `InstanceType` when creating a ref:
+Embora isso funcione, não há informações de tipo sobre `MyModal` e seus métodos disponíveis. Para corrigir isso, você deve usar `InstanceType` ao criar uma ref:
```ts
setup() {
@@ -445,11 +445,11 @@ setup() {
}
```
-Please note that you would also need to use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) or any other way to check that `modal.value` is not undefined.
+Observe que você também precisaria usar [encadeamento opcional](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Optional_chaining) ou qualquer outra maneira de verificar que `modal.value` não é `undefined`.
-### Typing `reactive`
+### Tipando `reactive`
-When typing a `reactive` property, we can use interfaces:
+Ao tipar uma propriedade `reactive`, podemos usar interfaces:
```ts
import { defineComponent, reactive } from 'vue'
@@ -463,17 +463,17 @@ export default defineComponent({
name: 'HelloWorld',
setup() {
const book = reactive({ title: 'Vue 3 Guide' })
- // or
+ // ou
const book: Book = reactive({ title: 'Vue 3 Guide' })
- // or
+ // ou
const book = reactive({ title: 'Vue 3 Guide' }) as Book
}
})
```
-### Typing `computed`
+### Tipando `computed`
-Computed values will automatically infer the type from returned value
+Valores computados irão inferir automaticamente o tipo do valor retornado
```ts
import { defineComponent, ref, computed } from 'vue'
@@ -483,10 +483,10 @@ export default defineComponent({
setup() {
let count = ref(0)
- // read-only
+ // apenas leitura
const doubleCount = computed(() => count.value * 2)
- const result = doubleCount.value.split('') // => Property 'split' does not exist on type 'number'
+ const result = doubleCount.value.split('') // => Propriedade 'split' não existe no tipo 'number'
}
})
```
diff --git a/src/guide/web-components.md b/src/guide/web-components.md
index be4d3de86f..9e6c211812 100644
--- a/src/guide/web-components.md
+++ b/src/guide/web-components.md
@@ -1,28 +1,28 @@
-# Vue and Web Components
+# Vue e Componentes da Web
-[Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) is an umbrella term for a set of web native APIs that allows developers to create reusable custom elements.
+[Componentes da Web](https://developer.mozilla.org/pt-BR/docs/Web/Web_Components) é um termo genérico para um conjunto de APIs nativas da Web que permite aos desenvolvedores criar elementos customizados reutilizáveis.
-We consider Vue and Web Components to be primarily complementary technologies. Vue has excellent support for both consuming and creating custom elements. Whether you are integrating custom elements into an existing Vue application, or using Vue to build and distribute custom elements, you are in good company.
+Consideramos Vue e Componentes da Web como tecnologias primeiramente complementares. O Vue tem um excelente suporte para consumir e criar elementos customizados. Esteja você integrando elementos customizados em um aplicativo Vue existente ou usando o Vue para criar e distribuir elementos customizados, você está em boa companhia.
-## Using Custom Elements in Vue
+## Usando Elementos Customizados no Vue
-Vue [scores a perfect 100% in the Custom Elements Everywhere tests](https://custom-elements-everywhere.com/libraries/vue/results/results.html). Consuming custom elements inside a Vue application largely works the same as using native HTML elements, with a few things to keep in mind:
+Vue [pontuou um perfeito 100% nos testes do Custom Elements Everywhere](https://custom-elements-everywhere.com/libraries/vue/results/results.html). Consumir elementos customizados dentro de um aplicativo Vue funciona basicamente da mesma forma que usar elementos HTML nativos, com algumas coisas a serem lembradas:
-### Skipping Component Resolution
+### Ignorando a Resolução de Componente
-By default, Vue will attempt to resolve a non-native HTML tag as a registered Vue component before falling back to rendering it as a custom element. This will cause Vue to emit a "failed to resolve component" warning during development. To let Vue know that certain elements should be treated as custom elements and skip component resolution, we can specify the [`compilerOptions.isCustomElement` option](/api/application-config.html#compileroptions).
+Por padrão, o Vue tentará resolver uma tag HTML não nativa como um componente Vue registrado antes de voltar a renderizá-lo como um elemento customizado. Isso fará com que o Vue emita um aviso de "falha ao resolver o componente" durante o desenvolvimento. Para que o Vue saiba que certos elementos devem ser tratados como elementos customizados e pular a resolução de componente, podemos especificar a [opção `compilerOptions.isCustomElement`](/api/application-config.html#compileroptions).
-If you are using Vue with a build setup, the option should be passed via build configs since it is a compile-time option.
+Se você estiver usando o Vue com um ambiente de compilação, a opção deve ser passada por meio das configurações de compilação, pois é uma opção de tempo de compilação.
-#### Example In-Browser Config
+#### Exemplo de Configuração no Navegador
```js
-// Only works if using in-browser compilation.
-// If using build tools, see config examples below.
+// Só funciona se estiver usando compilação no navegador.
+// Para ferramentas de compilação, veja os exemplos de configuração abaixo.
app.config.compilerOptions.isCustomElement = tag => tag.includes('-')
```
-#### Example Vite Config
+#### Exemplo de Configuração do Vite
```js
// vite.config.js
@@ -33,7 +33,7 @@ export default {
vue({
template: {
compilerOptions: {
- // treat all tags with a dash as custom elements
+ // trata todas as tags com traço como elementos customizados
isCustomElement: tag => tag.includes('-')
}
}
@@ -42,7 +42,7 @@ export default {
}
```
-#### Example Vue CLI Config
+#### Exemplo de Configuração do Vue CLI
```js
// vue.config.js
@@ -54,7 +54,7 @@ module.exports = {
.tap(options => ({
...options,
compilerOptions: {
- // treat any tag that starts with ion- as custom elements
+ // trata qualquer tag começando com ion- como elemento customizado
isCustomElement: tag => tag.startsWith('ion-')
}
}))
@@ -62,26 +62,26 @@ module.exports = {
}
```
-### Passing DOM Properties
+### Passando Propriedades do DOM
-Since DOM attributes can only be strings, we need to pass complex data to custom elements as DOM properties. When setting props on a custom element, Vue 3 automatically checks DOM-property presence using the `in` operator and will prefer setting the value as a DOM property if the key is present. This means that, in most cases, you won't need to think about this if the custom element follows the [recommended best practices](https://developers.google.com/web/fundamentals/web-components/best-practices#aim-to-keep-primitive-data-attributes-and-properties-in-sync,-reflecting-from-property-to-attribute,-and-vice-versa.).
+Como os atributos do DOM só podem ser strings, precisamos passar dados complexos para elementos customizados como propriedades do DOM. Ao definir props em um elemento customizado, o Vue 3 verifica automaticamente a presença da propriedade do DOM usando o operador `in` e prefere definir o valor como uma propriedade do DOM se a chave estiver presente. Isso significa que, na maioria dos casos, você não precisará pensar nisso se o elemento customizado seguir as [melhores práticas recomendadas](https://developers.google.com/web/fundamentals/web-components/best-practices#aim-to-keep-primitive-data-attributes-and-properties-in-sync,-reflecting-from-property-to-attribute,-and-vice-versa.).
-However, there could be rare cases where the data must be passed as a DOM property, but the custom element does not properly define/reflect the property (causing the `in` check to fail). In this case, you can force a `v-bind` binding to be set as a DOM property using the `.prop` modifier:
+No entanto, pode haver casos raros em que os dados devem ser passados como uma propriedade do DOM, mas o elemento customizado não define/reflete adequadamente a propriedade (fazendo com que a verificação `in` falhe). Neste caso, você pode forçar um vínculo `v-bind` a ser definido como uma propriedade do DOM usando o modificador `.prop`:
```html
-
+
```
-## Building Custom Elements with Vue
+## Construindo Elementos Customizados com Vue
-The primary benefit of custom elements is that they can be used with any framework, or even without a framework. This makes them ideal for distributing components where the end consumer may not be using the same frontend stack, or when you want to insulate the end application from the implementation details of the components it uses.
+O principal benefício dos elementos customizados é que eles podem ser usados com qualquer framework ou até mesmo sem um framework. Isso os torna ideais para distribuir componentes onde o consumidor final pode não estar usando a mesma stack de front-end ou quando você deseja isolar o aplicativo final dos detalhes de implementação dos componentes que ele usa.
### defineCustomElement
-Vue supports creating custom elements using exactly the same Vue component APIs via the [`defineCustomElement`](/api/global-api.html#definecustomelement) method. The method accepts the same argument as [`defineComponent`](/api/global-api.html#definecomponent), but instead returns a custom element constructor that extends `HTMLElement`:
+O Vue suporta a criação de elementos customizados usando exatamente as mesmas APIs de componentes Vue por meio do método [`defineCustomElement`](/api/global-api.html#definecustomelement). O método aceita o mesmo argumento que [`defineComponent`](/api/global-api.html#definecomponent), mas retorna um construtor de elemento customizados que estende `HTMLElement`:
```html
@@ -91,48 +91,48 @@ Vue supports creating custom elements using exactly the same Vue component APIs
import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
- // normal Vue component options here
+ // opções normais de componentes Vue aqui
props: {},
emits: {},
template: `...`,
- // defineCustomElement only: CSS to be injected into shadow root
- styles: [`/* inlined css */`]
+ // somente defineCustomElement: CSS a ser injetado na raiz sombra
+ styles: [`/* CSS inline */`]
})
-// Register the custom element.
-// After registration, all `` tags
-// on the page will be upgraded.
+// Registra o elemento personalizado.
+// Após o registro, todas as tags ``
+// na página serão atualizadas.
customElements.define('my-vue-element', MyVueElement)
-// You can also programmatically instantiate the element:
-// (can only be done after registration)
+// Você também pode instanciar programaticamente o elemento:
+// (só pode ser feito após o registro)
document.body.appendChild(
new MyVueElement({
- // initial props (optional)
+ // props iniciais (opcional)
})
)
```
-#### Lifecycle
+#### Ciclo de Vida
-- A Vue custom element will mount an internal Vue component instance inside its shadow root when the element's [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks) is called for the first time.
+- Um elemento customizado Vue montará uma instância interna do componente Vue dentro de sua raiz sombra quando o [`connectedCallback`](https://developer.mozilla.org/pt-BR/docs/Web/Web_Components/Using_custom_elements#usando_os_callbacks_do_ciclo_de_vida) do elemento for chamado pela primeira vez.
-- When the element's `disconnectedCallback` is invoked, Vue will check whether the element is detached from the document after a microtask tick.
+- Quando o `disconnectedCallback` do elemento é invocado, o Vue verificará se o elemento é desconectado do documento após uma microtarefa.
- - If the element is still in the document, it's a move and the component instance will be preserved;
+ - Se o elemento ainda estiver no documento, é uma movimentação e a instância do componente será preservada;
- - If the element is detached from the document, it's a removal and the component instance will be unmounted.
+ - Se o elemento for desanexado do documento, é uma remoção e a instância do componente será desmontada.
#### Props
-- All props declared using the `props` option will be defined on the custom element as properties. Vue will automatically handle the reflection between attributes / properties where appropriate.
+- Todas as props declaradas usando a opção `props` serão definidas no elemento customizado como propriedades. Vue lidará automaticamente com a reflexão entre atributos / propriedades onde apropriado.
- - Attributes are always reflected to corresponding properties.
+ - Os atributos são sempre refletidos nas propriedades correspondentes.
- - Properties with primitive values (`string`, `boolean` or `number`) are reflected as attributes.
+ - Propriedades com valores primitivos (`string`, `boolean` ou `number`) são refletidas como atributos.
-- Vue also automatically casts props declared with `Boolean` or `Number` types into the desired type when they are set as attributes (which are always strings). For example given the following props declaration:
+- Vue também converte automaticamente props declarados com tipos `Boolean` ou `Number` no tipo desejado quando são definidos como atributos (que são sempre strings). Por exemplo, dada a seguinte declaração de props:
```js
props: {
@@ -141,69 +141,69 @@ document.body.appendChild(
}
```
- And the custom element usage:
+ E o uso do elemento customizado:
```html
```
- In the component, `selected` will be cast to `true` (boolean) and `index` will be cast to `1` (number).
+ No componente, `selected` será convertido em `true` (booleano) e `index` será convertido em `1` (número).
-#### Events
+#### Eventos
-Events emitted via `this.$emit` or setup `emit` are dispatched as native [CustomEvents](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#adding_custom_data_%E2%80%93_customevent) on the custom element. Additional event arguments (payload) will be exposed as an array on the CustomEvent object as its `details` property.
+Eventos emitidos via `this.$emit` ou configuração `emit` são despachados como [CustomEvents](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events#adding_custom_data_%E2%80%93_customevent) nativos no elemento customizado. Argumentos de eventos adicionais (_payload_) serão expostos como um array no objeto CustomEvent como sua propriedade `details`.
#### Slots
-Inside the component, slots can be rendered using the ` ` element as usual. However when consuming the resulting element, it only accepts [native slots syntax](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots):
+Dentro do componente, os slots podem ser renderizados usando o elemento ` ` como de costume. No entanto, ao consumir o elemento resultante, ele aceita apenas [sintaxe de slots nativos](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots):
-- [Scoped slots](/guide/component-slots.html#scoped-slots) are not supported.
+- [Slots com escopo](/guide/component-slots.html#definicao-de-escopo-em-slots) não são compatíveis.
-- When passing named slots, use the `slot` attribute instead of the `v-slot` directive:
+- Ao passar slots nomeados, use o atributo `slot` em vez da diretiva `v-slot`:
```html
- hello
+ olá
```
-#### Provide / Inject
+#### Prover / Injetar
-The [Provide / Inject API](/guide/component-provide-inject.html#provide-inject) and its [Composition API equivalent](/api/composition-api.html#provide-inject) also work between Vue-defined custom elements. However, note that this works **only between custom elements**. i.e. a Vue-defined custom element won't be able to inject properties provided by a non-custom-element Vue component.
+A [API Prover / Injetar](/guide/component-provide-inject.html#prover-e-injetar-dados) e sua [equivalente na API de Composição](/api/composition-api.html#prover-injetar) também funcionam entre elementos customizados. No entanto, observe que isso funciona **somente entre elementos customizados**. ou seja, um elemento customizado definido pelo Vue não poderá injetar propriedades fornecidas por um componente Vue de elemento não customizado.
-### SFC as Custom Element
+### SFC como Elemento Customizado
-`defineCustomElement` also works with Vue Single File Components (SFCs). However, with the default tooling setup, the `
@@ -1447,7 +1447,7 @@ computed: {
-
Good
+Bom
```html
@@ -1474,22 +1474,22 @@ computed: {
```
-## Priority D Rules: Use with Caution
+## Regras Prioridade D: Use com Cautela
-### Element selectors with `scoped` use with caution
+### Seletores de elemento em `scoped` use com cautela
-**Element selectors should be avoided with `scoped`.**
+**Seletores de elemento devem ser evitados com o `scoped`.**
-Prefer class selectors over element selectors in `scoped` styles, because large numbers of element selectors are slow.
+Prefira seletores de classe ao invés de seletores de elemento em estilos `scoped`, pois um grande número de seletores de elemento são lentos.
-::: details Detailed Explanation
-To scope styles, Vue adds a unique attribute to component elements, such as `data-v-f3f3eg9`. Then selectors are modified so that only matching elements with this attribute are selected (e.g. `button[data-v-f3f3eg9]`).
+::: details Explicação Detalhada
+Para usar o escopo em estilos, o Vue adiciona um atributo único aos elementos de componente, como um `data-v-f3f3eg9`. Então os seletores são modificados para que apenas os elementos correspondentes com este atributo sejam selecionados. (ex.: `button[data-v-f3f3eg9]`).
-The problem is that large numbers of element-attribute selectors (e.g. `button[data-v-f3f3eg9]`) will be considerably slower than class-attribute selectors (e.g. `.btn-close[data-v-f3f3eg9]`), so class selectors should be preferred whenever possible.
+O problema é que um grande número de seletores de elemento (ex.: `button[data-v-f3f3eg9]`) serão consideravelmente mais lentos do que seletores de classe (ex.: `.btn-close[data-v-f3f3eg9]`), então seletores de classe devem ser preferidos sempre que possível.
:::
-
Bad
+Ruim
```html
@@ -1505,7 +1505,7 @@ button {
-
Good
+Bom
```html
@@ -1520,16 +1520,16 @@ button {
```
-### Implicit parent-child communication use with caution
+### Comunicação implícita entre componentes pai-filho use com cautela
-**Props and events should be preferred for parent-child component communication, instead of `this.$parent` or mutating props.**
+**Propriedades e eventos devem ser preferidos para a comunicação entre componentes pai-filho, ao invés de `this.$parent` ou mutação de propriedades.**
-An ideal Vue application is props down, events up. Sticking to this convention makes your components much easier to understand. However, there are edge cases where prop mutation or `this.$parent` can simplify two components that are already deeply coupled.
+Uma aplicação Vue ideal passa propriedades para baixo, e eventos para cima. Ater-se a esta convenção irá tornar os seus componentes muito mais fáceis de entender. Entretanto, há casos extremos onde a mutação de propriedade ou o `this.$parent` poderá simplificar dois componentes que já estão profundamente atrelados.
-The problem is, there are also many _simple_ cases where these patterns may offer convenience. Beware: do not be seduced into trading simplicity (being able to understand the flow of your state) for short-term convenience (writing less code).
+O problema é que existem também muitos casos _simples_ onde estes padrões podem oferecer conveniência. Cuidado: não seja seduzido a trocar simplicidade (ser capaz de entender o fluxo do seu estado) pela conveniência em curto prazo (escrever menos código).
-
Bad
+Ruim
```js
app.component('TodoItem', {
@@ -1572,7 +1572,7 @@ app.component('TodoItem', {
-
Good
+Bom
```js
app.component('TodoItem', {
@@ -1617,16 +1617,16 @@ app.component('TodoItem', {
```
-### Non-flux state management use with caution
+### Gerenciamento de estado sem Flux use com cautela
-**[Vuex](https://next.vuex.vuejs.org/) should be preferred for global state management, instead of `this.$root` or a global event bus.**
+**[Vuex](https://vuex.vuejs.org/ptbr) deve ser preferido para o gerenciamento de estado global, ao invés de `this.$root` ou um _event bus_ global.**
-Managing state on `this.$root` and/or using a global event bus can be convenient for very simple cases, but it is not appropriate for most applications.
+Gerenciar o estado em `this.$root` e/ou usando um _event bus_ global pode ser conveniente para casos muito simples, mas é inapropriado para a maioria das aplicações.
-Vuex is the [official flux-like implementation](/guide/state-management.html#official-flux-like-implementation) for Vue, and offers not only a central place to manage state, but also tools for organizing, tracking, and debugging state changes. It integrates well in the Vue ecosystem (including full [Vue DevTools](/guide/installation.html#vue-devtools) support).
+Vuex é a [implementação oficial no estilo Flux](/guide/state-management.html#implementacao-oficial-estilo-flux) para o Vue, e oferece não apenas um local central para gerenciar o estado, mas também ferramentas para organizar, rastrear, e depurar alterações de estado. Ele integra bem o ecossistema Vue (incluindo o completo suporte a [Vue DevTools](/guide/installation.html#vue-devtools)).
-
Bad
+Ruim
```js
// main.js
@@ -1655,7 +1655,7 @@ const app = createApp({
-
Good
+Bom
```js
// store/modules/todos.js
@@ -1705,7 +1705,7 @@ export default {
```
-
+