From ab0e0aa9a6149750ac919f294b27a7ada52490ba Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 4 Jun 2018 19:00:31 -0300 Subject: [PATCH 01/21] First Commit --- docs/.vuepress/config.js | 46 +++++ docs/ptbr/README.md | 63 ++++++ docs/ptbr/api/README.md | 263 +++++++++++++++++++++++++ docs/ptbr/guide/README.md | 44 +++++ docs/ptbr/guide/actions.md | 178 +++++++++++++++++ docs/ptbr/guide/core-concepts.md | 13 ++ docs/ptbr/guide/forms.md | 60 ++++++ docs/ptbr/guide/getters.md | 116 +++++++++++ docs/ptbr/guide/hot-reload.md | 44 +++++ docs/ptbr/guide/modules.md | 320 +++++++++++++++++++++++++++++++ docs/ptbr/guide/mutations.md | 172 +++++++++++++++++ docs/ptbr/guide/plugins.md | 126 ++++++++++++ docs/ptbr/guide/state.md | 109 +++++++++++ docs/ptbr/guide/strict.md | 25 +++ docs/ptbr/guide/structure.md | 32 ++++ docs/ptbr/guide/testing.md | 240 +++++++++++++++++++++++ docs/ptbr/installation.md | 76 ++++++++ 17 files changed, 1927 insertions(+) create mode 100644 docs/ptbr/README.md create mode 100644 docs/ptbr/api/README.md create mode 100644 docs/ptbr/guide/README.md create mode 100644 docs/ptbr/guide/actions.md create mode 100644 docs/ptbr/guide/core-concepts.md create mode 100644 docs/ptbr/guide/forms.md create mode 100644 docs/ptbr/guide/getters.md create mode 100644 docs/ptbr/guide/hot-reload.md create mode 100644 docs/ptbr/guide/modules.md create mode 100644 docs/ptbr/guide/mutations.md create mode 100644 docs/ptbr/guide/plugins.md create mode 100644 docs/ptbr/guide/state.md create mode 100644 docs/ptbr/guide/strict.md create mode 100644 docs/ptbr/guide/structure.md create mode 100644 docs/ptbr/guide/testing.md create mode 100644 docs/ptbr/installation.md diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index d9653d2bf..1be5aa392 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -24,6 +24,11 @@ module.exports = { lang: 'kr', title: 'Vuex', description: 'Vue.js의 중앙 상태 관리' + }, + '/ptbr/': { + lang: 'pt-BR', + title: 'Vuex', + description: 'Gerenciamento de Estado Centralizado para Vue.js' } }, serviceWorker: true, @@ -234,6 +239,47 @@ module.exports = { '/kr/guide/testing', '/kr/guide/hot-reload' ] + }, + '/ptbr/': { + label: 'Português', + selectText: 'Idiomas', + editLinkText: 'Edite esta página no GitHub', + nav: [ + { + text: 'Guia', + link: '/ptbr/guide/' + }, + { + text: 'Referência da API', + link: '/ptbr/api/' + }, + { + text: 'Notas da Versão', + link: 'https://github.com/vuejs/vuex/releases' + } + ], + sidebar: [ + '/ptbr/installation', + '/ptbr/', + '/ptbr/guide/', + { + title: 'Core Concepts', + collapsable: false, + children: [ + '/ptbr/guide/state', + '/ptbr/guide/getters', + '/ptbr/guide/mutations', + '/ptbr/guide/actions', + '/ptbr/guide/modules' + ] + }, + '/ptbr/guide/structure', + '/ptbr/guide/plugins', + '/ptbr/guide/strict', + '/ptbr/guide/forms', + '/ptbr/guide/testing', + '/ptbr/guide/hot-reload' + ] } } } diff --git a/docs/ptbr/README.md b/docs/ptbr/README.md new file mode 100644 index 000000000..8162cbc54 --- /dev/null +++ b/docs/ptbr/README.md @@ -0,0 +1,63 @@ +# What is Vuex? + +Vuex is a **state management pattern + library** for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It also integrates with Vue's official [devtools extension](https://github.com/vuejs/vue-devtools) to provide advanced features such as zero-config time-travel debugging and state snapshot export / import. + +### What is a "State Management Pattern"? + +Let's start with a simple Vue counter app: + +``` js +new Vue({ + // state + data () { + return { + count: 0 + } + }, + // view + template: ` +
{{ count }}
+ `, + // actions + methods: { + increment () { + this.count++ + } + } +}) +``` + +It is a self-contained app with the following parts: + +- The **state**, which is the source of truth that drives our app; +- The **view**, which is just a declarative mapping of the **state**; +- The **actions**, which are the possible ways the state could change in reaction to user inputs from the **view**. + +This is an extremely simple representation of the concept of "one-way data flow": + +

+ +

+ +However, the simplicity quickly breaks down when we have **multiple components that share common state**: + +- Multiple views may depend on the same piece of state. +- Actions from different views may need to mutate the same piece of state. + +For problem one, passing props can be tedious for deeply nested components, and simply doesn't work for sibling components. For problem two, we often find ourselves resorting to solutions such as reaching for direct parent/child instance references or trying to mutate and synchronize multiple copies of the state via events. Both of these patterns are brittle and quickly lead to unmaintainable code. + +So why don't we extract the shared state out of the components, and manage it in a global singleton? With this, our component tree becomes a big "view", and any component can access the state or trigger actions, no matter where they are in the tree! + +In addition, by defining and separating the concepts involved in state management and enforcing certain rules, we also give our code more structure and maintainability. + +This is the basic idea behind Vuex, inspired by [Flux](https://facebook.github.io/flux/docs/overview.html), [Redux](http://redux.js.org/) and [The Elm Architecture](https://guide.elm-lang.org/architecture/). Unlike the other patterns, Vuex is also a library implementation tailored specifically for Vue.js to take advantage of its granular reactivity system for efficient updates. + +![vuex](/vuex.png) + +### When Should I Use It? + +Although Vuex helps us deal with shared state management, it also comes with the cost of more concepts and boilerplate. It's a trade-off between short term and long term productivity. + +If you've never built a large-scale SPA and jump right into Vuex, it may feel verbose and daunting. That's perfectly normal - if your app is simple, you will most likely be fine without Vuex. A simple [global event bus](https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication) may be all you need. But if you are building a medium-to-large-scale SPA, chances are you have run into situations that make you think about how to better handle state outside of your Vue components, and Vuex will be the natural next step for you. There's a good quote from Dan Abramov, the author of Redux: + +> Flux libraries are like glasses: you’ll know when you need them. diff --git a/docs/ptbr/api/README.md b/docs/ptbr/api/README.md new file mode 100644 index 000000000..906167686 --- /dev/null +++ b/docs/ptbr/api/README.md @@ -0,0 +1,263 @@ +--- +sidebar: auto +--- + +# API Reference + +## Vuex.Store + +``` js +import Vuex from 'vuex' + +const store = new Vuex.Store({ ...options }) +``` + +## Vuex.Store Constructor Options + +### state + +- type: `Object | Function` + + The root state object for the Vuex store. [Details](../guide/state.md) + + If you pass a function that returns an object, the returned object is used as the root state. This is useful when you want to reuse the state object especially for module reuse. [Details](../guide/modules.md#module-reuse) + +### mutations + +- type: `{ [type: string]: Function }` + + Register mutations on the store. The handler function always receives `state` as the first argument (will be module local state if defined in a module), and receives a second `payload` argument if there is one. + + [Details](../guide/mutations.md) + +### actions + +- type: `{ [type: string]: Function }` + + Register actions on the store. The handler function receives a `context` object that exposes the following properties: + + ``` js + { + state, // same as `store.state`, or local state if in modules + rootState, // same as `store.state`, only in modules + commit, // same as `store.commit` + dispatch, // same as `store.dispatch` + getters, // same as `store.getters`, or local getters if in modules + rootGetters // same as `store.getters`, only in modules + } + ``` + + And also receives a second `payload` argument if there is one. + + [Details](../guide/actions.md) + +### getters + +- type: `{ [key: string]: Function }` + + Register getters on the store. The getter function receives the following arguments: + + ``` + state, // will be module local state if defined in a module. + getters // same as store.getters + ``` + + Specific when defined in a module + + ``` + state, // will be module local state if defined in a module. + getters, // module local getters of the current module + rootState, // global state + rootGetters // all getters + ``` + + Registered getters are exposed on `store.getters`. + + [Details](../guide/getters.md) + +### modules + +- type: `Object` + + An object containing sub modules to be merged into the store, in the shape of: + + ``` js + { + key: { + state, + namespaced?, + mutations?, + actions?, + getters?, + modules? + }, + ... + } + ``` + + Each module can contain `state` and `mutations` similar to the root options. A module's state will be attached to the store's root state using the module's key. A module's mutations and getters will only receives the module's local state as the first argument instead of the root state, and module actions' `context.state` will also point to the local state. + + [Details](../guide/modules.md) + +### plugins + +- type: `Array` + + An array of plugin functions to be applied to the store. The plugin simply receives the store as the only argument and can either listen to mutations (for outbound data persistence, logging, or debugging) or dispatch mutations (for inbound data e.g. websockets or observables). + + [Details](../guide/plugins.md) + +### strict + +- type: `Boolean` +- default: `false` + + Force the Vuex store into strict mode. In strict mode any mutations to Vuex state outside of mutation handlers will throw an Error. + + [Details](../guide/strict.md) + +## Vuex.Store Instance Properties + +### state + +- type: `Object` + + The root state. Read only. + +### getters + +- type: `Object` + + Exposes registered getters. Read only. + +## Vuex.Store Instance Methods + +### commit + +- `commit(type: string, payload?: any, options?: Object)` +- `commit(mutation: Object, options?: Object)` + + Commit a mutation. `options` can have `root: true` that allows to commit root mutations in [namespaced modules](../guide/modules.md#namespacing). [Details](../guide/mutations.md) + +### dispatch + +- `dispatch(type: string, payload?: any, options?: Object)` +- `dispatch(action: Object, options?: Object)` + + Dispatch an action. `options` can have `root: true` that allows to dispatch root actions in [namespaced modules](../guide/modules.md#namespacing). Returns a Promise that resolves all triggered action handlers. [Details](../guide/actions.md) + +### replaceState + +- `replaceState(state: Object)` + + Replace the store's root state. Use this only for state hydration / time-travel purposes. + +### watch + +- `watch(fn: Function, callback: Function, options?: Object): Function` + + Reactively watch `fn`'s return value, and call the callback when the value changes. `fn` receives the store's state as the first argument, and getters as the second argument. Accepts an optional options object that takes the same options as Vue's `vm.$watch` method. + + To stop watching, call the returned unwatch function. + +### subscribe + +- `subscribe(handler: Function): Function` + + Subscribe to store mutations. The `handler` is called after every mutation and receives the mutation descriptor and post-mutation state as arguments: + + ``` js + store.subscribe((mutation, state) => { + console.log(mutation.type) + console.log(mutation.payload) + }) + ``` + + To stop subscribing, call the returned unsubscribe function. + + Most commonly used in plugins. [Details](../guide/plugins.md) + +### subscribeAction + +- `subscribeAction(handler: Function): Function` + + > New in 2.5.0 + + Subscribe to store actions. The `handler` is called for every dispatched action and receives the action descriptor and current store state as arguments: + + ``` js + store.subscribeAction((action, state) => { + console.log(action.type) + console.log(action.payload) + }) + ``` + + To stop subscribing, call the returned unsubscribe function. + + Most commonly used in plugins. [Details](../guide/plugins.md) + +### registerModule + +- `registerModule(path: string | Array, module: Module, options?: Object)` + + Register a dynamic module. [Details](../guide/modules.md#dynamic-module-registration) + + `options` can have `preserveState: true` that allows to preserve the previous state. Useful with Server Side Rendering. + +### unregisterModule + +- `unregisterModule(path: string | Array)` + + Unregister a dynamic module. [Details](../guide/modules.md#dynamic-module-registration) + +### hotUpdate + +- `hotUpdate(newOptions: Object)` + + Hot swap new actions and mutations. [Details](../guide/hot-reload.md) + +## Component Binding Helpers + +### mapState + +- `mapState(namespace?: string, map: Array | Object): Object` + + Create component computed options that return the sub tree of the Vuex store. [Details](../guide/state.md#the-mapstate-helper) + + The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + + The second object argument's members can be a function. `function(state: any)` + +### mapGetters + +- `mapGetters(namespace?: string, map: Array | Object): Object` + + Create component computed options that return the evaluated value of a getter. [Details](../guide/getters.md#the-mapgetters-helper) + + The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + +### mapActions + +- `mapActions(namespace?: string, map: Array | Object): Object` + + Create component methods options that dispatch an action. [Details](../guide/actions.md#dispatching-actions-in-components) + + The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + + The second object argument's members can be a function. `function(dispatch: function, ...args: any[])` + +### mapMutations + +- `mapMutations(namespace?: string, map: Array | Object): Object` + + Create component methods options that commit a mutation. [Details](../guide/mutations.md#committing-mutations-in-components) + + The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + +  The second object argument's members can be a function. `function(commit: function, ...args: any[])` + +### createNamespacedHelpers + +- `createNamespacedHelpers(namespace: string): Object` + + Create namespaced component binding helpers. The returned object contains `mapState`, `mapGetters`, `mapActions` and `mapMutations` that are bound with the given namespace. [Details](../guide/modules.md#binding-helpers-with-namespace) diff --git a/docs/ptbr/guide/README.md b/docs/ptbr/guide/README.md new file mode 100644 index 000000000..496c665f7 --- /dev/null +++ b/docs/ptbr/guide/README.md @@ -0,0 +1,44 @@ +# Getting Started + +At the center of every Vuex application is the **store**. A "store" is basically a container that holds your application **state**. There are two things that make a Vuex store different from a plain global object: + +1. Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. + +2. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly **committing mutations**. This ensures every state change leaves a track-able record, and enables tooling that helps us better understand our applications. + +### The Simplest Store + +> **NOTE:** We will be using ES2015 syntax for code examples for the rest of the docs. If you haven't picked it up, [you should](https://babeljs.io/docs/learn-es2015/)! + +After [installing](../installation.md) Vuex, let's create a store. It is pretty straightforward - just provide an initial state object, and some mutations: + +``` js +// Make sure to call Vue.use(Vuex) first if using a module system + +const store = new Vuex.Store({ + state: { + count: 0 + }, + mutations: { + increment (state) { + state.count++ + } + } +}) +``` + +Now, you can access the state object as `store.state`, and trigger a state change with the `store.commit` method: + +``` js +store.commit('increment') + +console.log(store.state.count) // -> 1 +``` + +Again, the reason we are committing a mutation instead of changing `store.state.count` directly, is because we want to explicitly track it. This simple convention makes your intention more explicit, so that you can reason about state changes in your app better when reading the code. In addition, this gives us the opportunity to implement tools that can log every mutation, take state snapshots, or even perform time travel debugging. + +Using store state in a component simply involves returning the state within a computed property, because the store state is reactive. Triggering changes simply means committing mutations in component methods. + +Here's an example of the [most basic Vuex counter app](https://jsfiddle.net/n9jmu5v7/1269/). + +Next, we will discuss each core concept in much finer details, starting with [State](state.md). diff --git a/docs/ptbr/guide/actions.md b/docs/ptbr/guide/actions.md new file mode 100644 index 000000000..c89fffe0b --- /dev/null +++ b/docs/ptbr/guide/actions.md @@ -0,0 +1,178 @@ +# Actions + +Actions are similar to mutations, the differences being that: + +- Instead of mutating the state, actions commit mutations. +- Actions can contain arbitrary asynchronous operations. + +Let's register a simple action: + +``` js +const store = new Vuex.Store({ + state: { + count: 0 + }, + mutations: { + increment (state) { + state.count++ + } + }, + actions: { + increment (context) { + context.commit('increment') + } + } +}) +``` + +Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call `context.commit` to commit a mutation, or access the state and getters via `context.state` and `context.getters`. We will see why this context object is not the store instance itself when we introduce [Modules](modules.md) later. + +In practice, we often use ES2015 [argument destructuring](https://github.com/lukehoban/es6features#destructuring) to simplify the code a bit (especially when we need to call `commit` multiple times): + +``` js +actions: { + increment ({ commit }) { + commit('increment') + } +} +``` + +### Dispatching Actions + +Actions are triggered with the `store.dispatch` method: + +``` js +store.dispatch('increment') +``` + +This may look dumb at first sight: if we want to increment the count, why don't we just call `store.commit('increment')` directly? Remember that **mutations have to be synchronous**? Actions don't. We can perform **asynchronous** operations inside an action: + +``` js +actions: { + incrementAsync ({ commit }) { + setTimeout(() => { + commit('increment') + }, 1000) + } +} +``` + +Actions support the same payload format and object-style dispatch: + +``` js +// dispatch with a payload +store.dispatch('incrementAsync', { + amount: 10 +}) + +// dispatch with an object +store.dispatch({ + type: 'incrementAsync', + amount: 10 +}) +``` + +A more practical example of real-world actions would be an action to checkout a shopping cart, which involves **calling an async API** and **committing multiple mutations**: + +``` js +actions: { + checkout ({ commit, state }, products) { + // save the items currently in the cart + const savedCartItems = [...state.cart.added] + // send out checkout request, and optimistically + // clear the cart + commit(types.CHECKOUT_REQUEST) + // the shop API accepts a success callback and a failure callback + shop.buyProducts( + products, + // handle success + () => commit(types.CHECKOUT_SUCCESS), + // handle failure + () => commit(types.CHECKOUT_FAILURE, savedCartItems) + ) + } +} +``` + +Note we are performing a flow of asynchronous operations, and recording the side effects (state mutations) of the action by committing them. + +### Dispatching Actions in Components + +You can dispatch actions in components with `this.$store.dispatch('xxx')`, or use the `mapActions` helper which maps component methods to `store.dispatch` calls (requires root `store` injection): + +``` js +import { mapActions } from 'vuex' + +export default { + // ... + methods: { + ...mapActions([ + 'increment', // map `this.increment()` to `this.$store.dispatch('increment')` + + // `mapActions` also supports payloads: + 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)` + ]), + ...mapActions({ + add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')` + }) + } +} +``` + +### Composing Actions + +Actions are often asynchronous, so how do we know when an action is done? And more importantly, how can we compose multiple actions together to handle more complex async flows? + +The first thing to know is that `store.dispatch` can handle Promise returned by the triggered action handler and it also returns Promise: + +``` js +actions: { + actionA ({ commit }) { + return new Promise((resolve, reject) => { + setTimeout(() => { + commit('someMutation') + resolve() + }, 1000) + }) + } +} +``` + +Now you can do: + +``` js +store.dispatch('actionA').then(() => { + // ... +}) +``` + +And also in another action: + +``` js +actions: { + // ... + actionB ({ dispatch, commit }) { + return dispatch('actionA').then(() => { + commit('someOtherMutation') + }) + } +} +``` + +Finally, if we make use of [async / await](https://tc39.github.io/ecmascript-asyncawait/), we can compose our actions like this: + +``` js +// assuming `getData()` and `getOtherData()` return Promises + +actions: { + async actionA ({ commit }) { + commit('gotData', await getData()) + }, + async actionB ({ dispatch, commit }) { + await dispatch('actionA') // wait for `actionA` to finish + commit('gotOtherData', await getOtherData()) + } +} +``` + +> It's possible for a `store.dispatch` to trigger multiple action handlers in different modules. In such a case the returned value will be a Promise that resolves when all triggered handlers have been resolved. diff --git a/docs/ptbr/guide/core-concepts.md b/docs/ptbr/guide/core-concepts.md new file mode 100644 index 000000000..22ce634e9 --- /dev/null +++ b/docs/ptbr/guide/core-concepts.md @@ -0,0 +1,13 @@ +# Core Concepts + +We will be learning the core concepts of Vuex in these chapters. They are: + +- [State](state.md) +- [Getters](getters.md) +- [Mutations](mutations.md) +- [Actions](actions.md) +- [Modules](modules.md) + +A deep understanding of all these concepts is essential for using vuex. + +Let's get started. diff --git a/docs/ptbr/guide/forms.md b/docs/ptbr/guide/forms.md new file mode 100644 index 000000000..37fd58e56 --- /dev/null +++ b/docs/ptbr/guide/forms.md @@ -0,0 +1,60 @@ +# Form Handling + +When using Vuex in strict mode, it could be a bit tricky to use `v-model` on a piece of state that belongs to Vuex: + +``` html + +``` + +Assuming `obj` is a computed property that returns an Object from the store, the `v-model` here will attempt to directly mutate `obj.message` when the user types in the input. In strict mode, this will result in an error because the mutation is not performed inside an explicit Vuex mutation handler. + +The "Vuex way" to deal with it is binding the ``'s value and call an action on the `input` or `change` event: + +``` html + +``` +``` js +// ... +computed: { + ...mapState({ + message: state => state.obj.message + }) +}, +methods: { + updateMessage (e) { + this.$store.commit('updateMessage', e.target.value) + } +} +``` + +And here's the mutation handler: + +``` js +// ... +mutations: { + updateMessage (state, message) { + state.obj.message = message + } +} +``` + +### Two-way Computed Property + +Admittedly, the above is quite a bit more verbose than `v-model` + local state, and we lose some of the useful features from `v-model` as well. An alternative approach is using a two-way computed property with a setter: + +``` html + +``` +``` js +// ... +computed: { + message: { + get () { + return this.$store.state.obj.message + }, + set (value) { + this.$store.commit('updateMessage', value) + } + } +} +``` diff --git a/docs/ptbr/guide/getters.md b/docs/ptbr/guide/getters.md new file mode 100644 index 000000000..124f38fac --- /dev/null +++ b/docs/ptbr/guide/getters.md @@ -0,0 +1,116 @@ +# Getters + +Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them: + +``` js +computed: { + doneTodosCount () { + return this.$store.state.todos.filter(todo => todo.done).length + } +} +``` + +If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared helper and import it in multiple places - both are less than ideal. + +Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed. + +Getters will receive the state as their 1st argument: + +``` js +const store = new Vuex.Store({ + state: { + todos: [ + { id: 1, text: '...', done: true }, + { id: 2, text: '...', done: false } + ] + }, + getters: { + doneTodos: state => { + return state.todos.filter(todo => todo.done) + } + } +}) +``` + +### Property-Style Access + +The getters will be exposed on the `store.getters` object, and you access values as properties: + +``` js +store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }] +``` + +Getters will also receive other getters as the 2nd argument: + +``` js +getters: { + // ... + doneTodosCount: (state, getters) => { + return getters.doneTodos.length + } +} +``` + +``` js +store.getters.doneTodosCount // -> 1 +``` + +We can now easily make use of it inside any component: + +``` js +computed: { + doneTodosCount () { + return this.$store.getters.doneTodosCount + } +} +``` + +Note that getters accessed as properties are cached as part of Vue's reactivity system. + +### Method-Style Access + +You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store: + +```js +getters: { + // ... + getTodoById: (state) => (id) => { + return state.todos.find(todo => todo.id === id) + } +} +``` + +``` js +store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false } +``` + +Note that getters accessed via methods will run each time you call them, and the result is not cached. + +### The `mapGetters` Helper + +The `mapGetters` helper simply maps store getters to local computed properties: + +``` js +import { mapGetters } from 'vuex' + +export default { + // ... + computed: { + // mix the getters into computed with object spread operator + ...mapGetters([ + 'doneTodosCount', + 'anotherGetter', + // ... + ]) + } +} +``` + +If you want to map a getter to a different name, use an object: + +``` js +...mapGetters({ + // map `this.doneCount` to `this.$store.getters.doneTodosCount` + doneCount: 'doneTodosCount' +}) +``` diff --git a/docs/ptbr/guide/hot-reload.md b/docs/ptbr/guide/hot-reload.md new file mode 100644 index 000000000..453343c70 --- /dev/null +++ b/docs/ptbr/guide/hot-reload.md @@ -0,0 +1,44 @@ +# Hot Reloading + +Vuex supports hot-reloading mutations, modules, actions and getters during development, using webpack's [Hot Module Replacement API](https://webpack.js.org/guides/hot-module-replacement/). You can also use it in Browserify with the [browserify-hmr](https://github.com/AgentME/browserify-hmr/) plugin. + +For mutations and modules, you need to use the `store.hotUpdate()` API method: + +``` js +// store.js +import Vue from 'vue' +import Vuex from 'vuex' +import mutations from './mutations' +import moduleA from './modules/a' + +Vue.use(Vuex) + +const state = { ... } + +const store = new Vuex.Store({ + state, + mutations, + modules: { + a: moduleA + } +}) + +if (module.hot) { + // accept actions and mutations as hot modules + module.hot.accept(['./mutations', './modules/a'], () => { + // require the updated modules + // have to add .default here due to babel 6 module output + const newMutations = require('./mutations').default + const newModuleA = require('./modules/a').default + // swap in the new actions and mutations + store.hotUpdate({ + mutations: newMutations, + modules: { + a: newModuleA + } + }) + }) +} +``` + +Checkout the [counter-hot example](https://github.com/vuejs/vuex/tree/dev/examples/counter-hot) to play with hot-reload. diff --git a/docs/ptbr/guide/modules.md b/docs/ptbr/guide/modules.md new file mode 100644 index 000000000..1ba8fb07c --- /dev/null +++ b/docs/ptbr/guide/modules.md @@ -0,0 +1,320 @@ +# Modules + +Due to using a single state tree, all state of our application is contained inside one big object. However, as our application grows in scale, the store can get really bloated. + +To help with that, Vuex allows us to divide our store into **modules**. Each module can contain its own state, mutations, actions, getters, and even nested modules - it's fractal all the way down: + +``` js +const moduleA = { + state: { ... }, + mutations: { ... }, + actions: { ... }, + getters: { ... } +} + +const moduleB = { + state: { ... }, + mutations: { ... }, + actions: { ... } +} + +const store = new Vuex.Store({ + modules: { + a: moduleA, + b: moduleB + } +}) + +store.state.a // -> `moduleA`'s state +store.state.b // -> `moduleB`'s state +``` + +### Module Local State + +Inside a module's mutations and getters, the first argument received will be **the module's local state**. + +``` js +const moduleA = { + state: { count: 0 }, + mutations: { + increment (state) { + // `state` is the local module state + state.count++ + } + }, + + getters: { + doubleCount (state) { + return state.count * 2 + } + } +} +``` + +Similarly, inside module actions, `context.state` will expose the local state, and root state will be exposed as `context.rootState`: + +``` js +const moduleA = { + // ... + actions: { + incrementIfOddOnRootSum ({ state, commit, rootState }) { + if ((state.count + rootState.count) % 2 === 1) { + commit('increment') + } + } + } +} +``` + +Also, inside module getters, the root state will be exposed as their 3rd argument: + +``` js +const moduleA = { + // ... + getters: { + sumWithRootCount (state, getters, rootState) { + return state.count + rootState.count + } + } +} +``` + +### Namespacing + +By default, actions, mutations and getters inside modules are still registered under the **global namespace** - this allows multiple modules to react to the same mutation/action type. + +If you want your modules to be more self-contained or reusable, you can mark it as namespaced with `namespaced: true`. When the module is registered, all of its getters, actions and mutations will be automatically namespaced based on the path the module is registered at. For example: + +``` js +const store = new Vuex.Store({ + modules: { + account: { + namespaced: true, + + // module assets + state: { ... }, // module state is already nested and not affected by namespace option + getters: { + isAdmin () { ... } // -> getters['account/isAdmin'] + }, + actions: { + login () { ... } // -> dispatch('account/login') + }, + mutations: { + login () { ... } // -> commit('account/login') + }, + + // nested modules + modules: { + // inherits the namespace from parent module + myPage: { + state: { ... }, + getters: { + profile () { ... } // -> getters['account/profile'] + } + }, + + // further nest the namespace + posts: { + namespaced: true, + + state: { ... }, + getters: { + popular () { ... } // -> getters['account/posts/popular'] + } + } + } + } + } +}) +``` + +Namespaced getters and actions will receive localized `getters`, `dispatch` and `commit`. In other words, you can use the module assets without writing prefix in the same module. Toggling between namespaced or not does not affect the code inside the module. + +#### Accessing Global Assets in Namespaced Modules + +If you want to use global state and getters, `rootState` and `rootGetters` are passed as the 3rd and 4th arguments to getter functions, and also exposed as properties on the `context` object passed to action functions. + +To dispatch actions or commit mutations in the global namespace, pass `{ root: true }` as the 3rd argument to `dispatch` and `commit`. + +``` js +modules: { + foo: { + namespaced: true, + + getters: { + // `getters` is localized to this module's getters + // you can use rootGetters via 4th argument of getters + someGetter (state, getters, rootState, rootGetters) { + getters.someOtherGetter // -> 'foo/someOtherGetter' + rootGetters.someOtherGetter // -> 'someOtherGetter' + }, + someOtherGetter: state => { ... } + }, + + actions: { + // dispatch and commit are also localized for this module + // they will accept `root` option for the root dispatch/commit + someAction ({ dispatch, commit, getters, rootGetters }) { + getters.someGetter // -> 'foo/someGetter' + rootGetters.someGetter // -> 'someGetter' + + dispatch('someOtherAction') // -> 'foo/someOtherAction' + dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction' + + commit('someMutation') // -> 'foo/someMutation' + commit('someMutation', null, { root: true }) // -> 'someMutation' + }, + someOtherAction (ctx, payload) { ... } + } + } +} +``` + +#### Register Global Action in Namespaced Modules + +If you want to register global actions in namespaced modules, you can mark it with `root: true` and place the action definition to function `handler`. For example: + +``` js +{ + actions: { + someOtherAction ({dispatch}) { + dispatch('someAction') + } + }, + modules: { + foo: { + namespaced: true, + + actions: { + someAction: { + root: true, + handler (namespacedContext, payload) { ... } // -> 'someAction' + } + } + } + } +} +``` + +#### Binding Helpers with Namespace + +When binding a namespaced module to components with the `mapState`, `mapGetters`, `mapActions` and `mapMutations` helpers, it can get a bit verbose: + +``` js +computed: { + ...mapState({ + a: state => state.some.nested.module.a, + b: state => state.some.nested.module.b + }) +}, +methods: { + ...mapActions([ + 'some/nested/module/foo', + 'some/nested/module/bar' + ]) +} +``` + +In such cases, you can pass the module namespace string as the first argument to the helpers so that all bindings are done using that module as the context. The above can be simplified to: + +``` js +computed: { + ...mapState('some/nested/module', { + a: state => state.a, + b: state => state.b + }) +}, +methods: { + ...mapActions('some/nested/module', [ + 'foo', + 'bar' + ]) +} +``` + +Furthermore, you can create namespaced helpers by using `createNamespacedHelpers`. It returns an object having new component binding helpers that are bound with the given namespace value: + +``` js +import { createNamespacedHelpers } from 'vuex' + +const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') + +export default { + computed: { + // look up in `some/nested/module` + ...mapState({ + a: state => state.a, + b: state => state.b + }) + }, + methods: { + // look up in `some/nested/module` + ...mapActions([ + 'foo', + 'bar' + ]) + } +} +``` + +#### Caveat for Plugin Developers + +You may care about unpredictable namespacing for your modules when you create a [plugin](plugins.md) that provides the modules and let users add them to a Vuex store. Your modules will be also namespaced if the plugin users add your modules under a namespaced module. To adapt this situation, you may need to receive a namespace value via your plugin option: + +``` js +// get namespace value via plugin option +// and returns Vuex plugin function +export function createPlugin (options = {}) { + return function (store) { + // add namespace to plugin module's types + const namespace = options.namespace || '' + store.dispatch(namespace + 'pluginAction') + } +} +``` + +### Dynamic Module Registration + +You can register a module **after** the store has been created with the `store.registerModule` method: + +``` js +// register a module `myModule` +store.registerModule('myModule', { + // ... +}) + +// register a nested module `nested/myModule` +store.registerModule(['nested', 'myModule'], { + // ... +}) +``` + +The module's state will be exposed as `store.state.myModule` and `store.state.nested.myModule`. + +Dynamic module registration makes it possible for other Vue plugins to also leverage Vuex for state management by attaching a module to the application's store. For example, the [`vuex-router-sync`](https://github.com/vuejs/vuex-router-sync) library integrates vue-router with vuex by managing the application's route state in a dynamically attached module. + +You can also remove a dynamically registered module with `store.unregisterModule(moduleName)`. Note you cannot remove static modules (declared at store creation) with this method. + +It may be likely that you want to preserve the previous state when registering a new module, such as preserving state from a Server Side Rendered app. You can do achieve this with `preserveState` option: `store.registerModule('a', module, { preserveState: true })` + +### Module Reuse + +Sometimes we may need to create multiple instances of a module, for example: + +- Creating multiple stores that use the same module (e.g. To [avoid stateful singletons in the SSR](https://ssr.vuejs.org/en/structure.html#avoid-stateful-singletons) when the `runInNewContext` option is `false` or `'once'`); +- Register the same module multiple times in the same store. + +If we use a plain object to declare the state of the module, then that state object will be shared by reference and cause cross store/module state pollution when it's mutated. + +This is actually the exact same problem with `data` inside Vue components. So the solution is also the same - use a function for declaring module state (supported in 2.3.0+): + +``` js +const MyReusableModule = { + state () { + return { + foo: 'bar' + } + }, + // mutations, actions, getters... +} +``` diff --git a/docs/ptbr/guide/mutations.md b/docs/ptbr/guide/mutations.md new file mode 100644 index 000000000..00f18b1b6 --- /dev/null +++ b/docs/ptbr/guide/mutations.md @@ -0,0 +1,172 @@ +# Mutations + +The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string **type** and a **handler**. The handler function is where we perform actual state modifications, and it will receive the state as the first argument: + +``` js +const store = new Vuex.Store({ + state: { + count: 1 + }, + mutations: { + increment (state) { + // mutate state + state.count++ + } + } +}) +``` + +You cannot directly call a mutation handler. Think of it more like event registration: "When a mutation with type `increment` is triggered, call this handler." To invoke a mutation handler, you need to call `store.commit` with its type: + +``` js +store.commit('increment') +``` + +### Commit with Payload + +You can pass an additional argument to `store.commit`, which is called the **payload** for the mutation: + +``` js +// ... +mutations: { + increment (state, n) { + state.count += n + } +} +``` +``` js +store.commit('increment', 10) +``` + +In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive: + +``` js +// ... +mutations: { + increment (state, payload) { + state.count += payload.amount + } +} +``` + +``` js +store.commit('increment', { + amount: 10 +}) +``` + +### Object-Style Commit + +An alternative way to commit a mutation is by directly using an object that has a `type` property: + +``` js +store.commit({ + type: 'increment', + amount: 10 +}) +``` + +When using object-style commit, the entire object will be passed as the payload to mutation handlers, so the handler remains the same: + +``` js +mutations: { + increment (state, payload) { + state.count += payload.amount + } +} +``` + +### Mutations Follow Vue's Reactivity Rules + +Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue: + +1. Prefer initializing your store's initial state with all desired fields upfront. + +2. When adding new properties to an Object, you should either: + + - Use `Vue.set(obj, 'newProp', 123)`, or + + - Replace that Object with a fresh one. For example, using the stage-3 [object spread syntax](https://github.com/sebmarkbage/ecmascript-rest-spread) we can write it like this: + + ``` js + state.obj = { ...state.obj, newProp: 123 } + ``` + +### Using Constants for Mutation Types + +It is a commonly seen pattern to use constants for mutation types in various Flux implementations. This allows the code to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application: + +``` js +// mutation-types.js +export const SOME_MUTATION = 'SOME_MUTATION' +``` + +``` js +// store.js +import Vuex from 'vuex' +import { SOME_MUTATION } from './mutation-types' + +const store = new Vuex.Store({ + state: { ... }, + mutations: { + // we can use the ES2015 computed property name feature + // to use a constant as the function name + [SOME_MUTATION] (state) { + // mutate state + } + } +}) +``` + +Whether to use constants is largely a preference - it can be helpful in large projects with many developers, but it's totally optional if you don't like them. + +### Mutations Must Be Synchronous + +One important rule to remember is that **mutation handler functions must be synchronous**. Why? Consider the following example: + +``` js +mutations: { + someMutation (state) { + api.callAsyncMethod(() => { + state.count++ + }) + } +} +``` + +Now imagine we are debugging the app and looking at the devtool's mutation logs. For every mutation logged, the devtool will need to capture a "before" and "after" snapshots of the state. However, the asynchronous callback inside the example mutation above makes that impossible: the callback is not called yet when the mutation is committed, and there's no way for the devtool to know when the callback will actually be called - any state mutation performed in the callback is essentially un-trackable! + +### Committing Mutations in Components + +You can commit mutations in components with `this.$store.commit('xxx')`, or use the `mapMutations` helper which maps component methods to `store.commit` calls (requires root `store` injection): + +``` js +import { mapMutations } from 'vuex' + +export default { + // ... + methods: { + ...mapMutations([ + 'increment', // map `this.increment()` to `this.$store.commit('increment')` + + // `mapMutations` also supports payloads: + 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)` + ]), + ...mapMutations({ + add: 'increment' // map `this.add()` to `this.$store.commit('increment')` + }) + } +} +``` + +### On to Actions + +Asynchronicity combined with state mutation can make your program very hard to reason about. For example, when you call two methods both with async callbacks that mutate the state, how do you know when they are called and which callback was called first? This is exactly why we want to separate the two concepts. In Vuex, **mutations are synchronous transactions**: + +``` js +store.commit('increment') +// any state change that the "increment" mutation may cause +// should be done at this moment. +``` + +To handle asynchronous operations, let's introduce [Actions](actions.md). diff --git a/docs/ptbr/guide/plugins.md b/docs/ptbr/guide/plugins.md new file mode 100644 index 000000000..afccfe31c --- /dev/null +++ b/docs/ptbr/guide/plugins.md @@ -0,0 +1,126 @@ +# Plugins + +Vuex stores accept the `plugins` option that exposes hooks for each mutation. A Vuex plugin is simply a function that receives the store as the only argument: + +``` js +const myPlugin = store => { + // called when the store is initialized + store.subscribe((mutation, state) => { + // called after every mutation. + // The mutation comes in the format of `{ type, payload }`. + }) +} +``` + +And can be used like this: + +``` js +const store = new Vuex.Store({ + // ... + plugins: [myPlugin] +}) +``` + +### Committing Mutations Inside Plugins + +Plugins are not allowed to directly mutate state - similar to your components, they can only trigger changes by committing mutations. + +By committing mutations, a plugin can be used to sync a data source to the store. For example, to sync a websocket data source to the store (this is just a contrived example, in reality the `createPlugin` function can take some additional options for more complex tasks): + +``` js +export default function createWebSocketPlugin (socket) { + return store => { + socket.on('data', data => { + store.commit('receiveData', data) + }) + store.subscribe(mutation => { + if (mutation.type === 'UPDATE_DATA') { + socket.emit('update', mutation.payload) + } + }) + } +} +``` + +``` js +const plugin = createWebSocketPlugin(socket) + +const store = new Vuex.Store({ + state, + mutations, + plugins: [plugin] +}) +``` + +### Taking State Snapshots + +Sometimes a plugin may want to receive "snapshots" of the state, and also compare the post-mutation state with pre-mutation state. To achieve that, you will need to perform a deep-copy on the state object: + +``` js +const myPluginWithSnapshot = store => { + let prevState = _.cloneDeep(store.state) + store.subscribe((mutation, state) => { + let nextState = _.cloneDeep(state) + + // compare `prevState` and `nextState`... + + // save state for next mutation + prevState = nextState + }) +} +``` + +**Plugins that take state snapshots should be used only during development.** When using webpack or Browserify, we can let our build tools handle that for us: + +``` js +const store = new Vuex.Store({ + // ... + plugins: process.env.NODE_ENV !== 'production' + ? [myPluginWithSnapshot] + : [] +}) +``` + +The plugin will be used by default. For production, you will need [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) for webpack or [envify](https://github.com/hughsk/envify) for Browserify to convert the value of `process.env.NODE_ENV !== 'production'` to `false` for the final build. + +### Built-in Logger Plugin + +> If you are using [vue-devtools](https://github.com/vuejs/vue-devtools) you probably don't need this. + +Vuex comes with a logger plugin for common debugging usage: + +``` js +import createLogger from 'vuex/dist/logger' + +const store = new Vuex.Store({ + plugins: [createLogger()] +}) +``` + +The `createLogger` function takes a few options: + +``` js +const logger = createLogger({ + collapsed: false, // auto-expand logged mutations + filter (mutation, stateBefore, stateAfter) { + // returns `true` if a mutation should be logged + // `mutation` is a `{ type, payload }` + return mutation.type !== "aBlacklistedMutation" + }, + transformer (state) { + // transform the state before logging it. + // for example return only a specific sub-tree + return state.subTree + }, + mutationTransformer (mutation) { + // mutations are logged in the format of `{ type, payload }` + // we can format it any way we want. + return mutation.type + }, + logger: console, // implementation of the `console` API, default `console` +}) +``` + +The logger file can also be included directly via a ` + +``` + +### NPM + +``` bash +npm install vuex --save +``` + +### Yarn + +``` bash +yarn add vuex +``` + +When used with a module system, you must explicitly install Vuex via `Vue.use()`: + +``` js +import Vue from 'vue' +import Vuex from 'vuex' + +Vue.use(Vuex) +``` + +You don't need to do this when using global script tags. + +### Promise + +Vuex requires [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). If your supporting browsers do not implement Promise (e.g. IE), you can use a polyfill library, such as [es6-promise](https://github.com/stefanpenner/es6-promise). + +You can include it via CDN: + +``` html + +``` + +Then `window.Promise` will be available automatically. + +If you prefer using a package manager such as NPM or Yarn, install it with the following commands: + +``` bash +npm install es6-promise --save # NPM +yarn add es6-promise # Yarn +``` + +Furthermore, add the below line into anywhere in your code before using Vuex: + +``` js +import 'es6-promise/auto' +``` + +### Dev Build + +You will have to clone directly from GitHub and build `vuex` yourself if +you want to use the latest dev build. + +``` bash +git clone https://github.com/vuejs/vuex.git node_modules/vuex +cd node_modules/vuex +npm install +npm run build +``` From bd79bccadf971442e71b45674395be1440cd9e70 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 6 Jun 2018 10:51:21 -0300 Subject: [PATCH 02/21] Translated the inital files --- docs/ptbr/README.md | 40 +++++++++++++++++++-------------------- docs/ptbr/installation.md | 26 ++++++++++++------------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/docs/ptbr/README.md b/docs/ptbr/README.md index 8162cbc54..768124544 100644 --- a/docs/ptbr/README.md +++ b/docs/ptbr/README.md @@ -1,10 +1,10 @@ -# What is Vuex? +# O que é Vuex? -Vuex is a **state management pattern + library** for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It also integrates with Vue's official [devtools extension](https://github.com/vuejs/vue-devtools) to provide advanced features such as zero-config time-travel debugging and state snapshot export / import. +O Vuex é um **padrão de gerenciamento de estado + biblioteca** para aplicativos Vue.js. Ele serve como um _store_ centralizado para todos os componentes em uma aplicação, com regras garantindo que o estado só possa ser mutado de forma previsível. Ele também se integra com a extensão oficial [Vue devtools](https://github.com/vuejs/vue-devtools) para fornecer recursos avançados sem configurações adicionais, como depuração viajando pelo histórico de estado (_time travel_) e exportação/importação de registros de estado em determinado momento. -### What is a "State Management Pattern"? +### O que é um "Padrão de Gerenciamento do Estado"? -Let's start with a simple Vue counter app: +Vamos começar com um aplicativo simples de contador Vue: ``` js new Vue({ @@ -27,37 +27,37 @@ new Vue({ }) ``` -It is a self-contained app with the following parts: +É um aplicativo independente com as seguintes partes: -- The **state**, which is the source of truth that drives our app; -- The **view**, which is just a declarative mapping of the **state**; -- The **actions**, which are the possible ways the state could change in reaction to user inputs from the **view**. +- O **estado** (_state_), que é a fonte da verdade que direciona nosso aplicativo; +- A **_view_**, que é apenas um mapeamento declarativo do **estado**; +- As **ações** (_actions_), que são as possíveis maneiras pelas quais o estado pode mudar em reação às interações dos usuários da **_view_**. -This is an extremely simple representation of the concept of "one-way data flow": +Esta é uma representação extremamente simples do conceito de "fluxo de dados unidirecional" (_one-way_):

-However, the simplicity quickly breaks down when we have **multiple components that share common state**: +No entanto, a simplicidade é quebrada rapidamente quando temos **vários componentes que compartilham um estado comum**: -- Multiple views may depend on the same piece of state. -- Actions from different views may need to mutate the same piece of state. +- Múltiplas _views_ podem depender do mesmo pedaço de estado. +- Ações de diferentes _views_ podem precisar mudar o mesmo pedaço de estado. -For problem one, passing props can be tedious for deeply nested components, and simply doesn't work for sibling components. For problem two, we often find ourselves resorting to solutions such as reaching for direct parent/child instance references or trying to mutate and synchronize multiple copies of the state via events. Both of these patterns are brittle and quickly lead to unmaintainable code. +Para o problema um, passar propriedades pode ser entediante para componentes profundamente aninhados e simplesmente não funcionam para componentes irmãos. Para o problema dois, frequentemente nos encontramos recorrendo a soluções como alcançar referências diretas da instância pai/filho ou tentar alterar e sincronizar várias cópias do estado por meio de eventos. Ambos os padrões são frágeis e levam rapidamente a um código não-sustentável. -So why don't we extract the shared state out of the components, and manage it in a global singleton? With this, our component tree becomes a big "view", and any component can access the state or trigger actions, no matter where they are in the tree! +Então, por que não extraímos o estado compartilhado dos componentes, e o gerenciamos em um _singleton_ global? Com isso, nossa árvore de componentes se torna uma grande "_view_", e qualquer componente pode acessar o estado ou acionar ações, não importando onde elas estejam na árvore! -In addition, by defining and separating the concepts involved in state management and enforcing certain rules, we also give our code more structure and maintainability. +Além disso, definindo e separando os conceitos envolvidos no gerenciamento do estado e aplicando certas regras, também damos ao nosso código mais estrutura e sustentabilidade. -This is the basic idea behind Vuex, inspired by [Flux](https://facebook.github.io/flux/docs/overview.html), [Redux](http://redux.js.org/) and [The Elm Architecture](https://guide.elm-lang.org/architecture/). Unlike the other patterns, Vuex is also a library implementation tailored specifically for Vue.js to take advantage of its granular reactivity system for efficient updates. +Esta é a ideia básica por trás do Vuex, inspirada por [Flux](https://facebook.github.io/flux/docs/overview.html), [Redux](http://redux.js.org/) e [The Elm Architecture](https://guide.elm-lang.org/architecture/). Ao contrário dos outros padrões, o Vuex também é uma implementação de biblioteca adaptada especificamente para o Vue.js tirar proveito de seu sistema de reatividade granular para atualizações eficientes. ![vuex](/vuex.png) -### When Should I Use It? +### Quando usar o Vuex? -Although Vuex helps us deal with shared state management, it also comes with the cost of more concepts and boilerplate. It's a trade-off between short term and long term productivity. +Embora o Vuex nos ajude a lidar com o gerenciamento de estado compartilhado, ele também vem com o custo de mais conceitos e códigos repetitivos. É uma escolha difícil entre produtividade de curto e longo prazo -If you've never built a large-scale SPA and jump right into Vuex, it may feel verbose and daunting. That's perfectly normal - if your app is simple, you will most likely be fine without Vuex. A simple [global event bus](https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication) may be all you need. But if you are building a medium-to-large-scale SPA, chances are you have run into situations that make you think about how to better handle state outside of your Vue components, and Vuex will be the natural next step for you. There's a good quote from Dan Abramov, the author of Redux: +Se você nunca construiu um SPA em grande escala e for direto para o Vuex, ele pode parecer detalhado e desanimador. Isso é perfeitamente normal - se o seu aplicativo é simples, você provavelmente ficará bem sem o Vuex. Um simples [global event bus](https://br.vuejs.org/v2/guide/components.html#Comunicacao-Nao-Pai-Filho) pode ser tudo que você precisa. Mas, se você está criando um SPA de médio a grande porte, é provável que tenha encontrado situações que fazem você pensar em como lidar melhor com o estado fora de seus componentes do Vue, e o Vuex será o próximo passo natural para você. Há uma boa citação de Dan Abramov, o autor do Redux: -> Flux libraries are like glasses: you’ll know when you need them. +> As bibliotecas _Flux_ são como óculos: você saberá quando precisar delas. diff --git a/docs/ptbr/installation.md b/docs/ptbr/installation.md index 23f7a2ba5..f081295d5 100644 --- a/docs/ptbr/installation.md +++ b/docs/ptbr/installation.md @@ -1,14 +1,14 @@ -# Installation +# Instalação -### Direct Download / CDN +### Download Direto / CDN [https://unpkg.com/vuex](https://unpkg.com/vuex) -[Unpkg.com](https://unpkg.com) provides NPM-based CDN links. The above link will always point to the latest release on NPM. You can also use a specific version/tag via URLs like `https://unpkg.com/vuex@2.0.0`. +[Unpkg.com](https://unpkg.com) fornece os links de CDN baseados em NPM. O link acima sempre apontará para a última versão do NPM. Você também pode usar uma versão/tag específica por meio de URLs como `https://unpkg.com/vuex@2.0.0`. -Include `vuex` after Vue and it will install itself automatically: +Inclua o `vuex` após o Vue e ele se instalará automaticamente: ``` html @@ -27,7 +27,7 @@ npm install vuex --save yarn add vuex ``` -When used with a module system, you must explicitly install Vuex via `Vue.use()`: +Quando usado com um sistema de módulos, você deve instalar o Vuex obrigatóriamente via `Vue.use()`: ``` js import Vue from 'vue' @@ -36,28 +36,28 @@ import Vuex from 'vuex' Vue.use(Vuex) ``` -You don't need to do this when using global script tags. +Você não precisa fazer isso se for incluir o `vuex` via tags script. ### Promise -Vuex requires [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). If your supporting browsers do not implement Promise (e.g. IE), you can use a polyfill library, such as [es6-promise](https://github.com/stefanpenner/es6-promise). +Vuex requer [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises). Se os seus navegadores não implementarem o _Promise_ (e.g. IE), você pode usar uma biblioteca _polyfill_, como a [es6-promise](https://github.com/stefanpenner/es6-promise). -You can include it via CDN: +Você pode incluí-la via CDN: ``` html ``` -Then `window.Promise` will be available automatically. +Então o `window.Promise` estará disponível automaticamente. -If you prefer using a package manager such as NPM or Yarn, install it with the following commands: +Se você preferir usar um gerenciador de pacotes como NPM ou Yarn, instale-o com os seguintes comandos: ``` bash npm install es6-promise --save # NPM yarn add es6-promise # Yarn ``` -Furthermore, add the below line into anywhere in your code before using Vuex: +Além disso, adicione a linha abaixo em qualquer lugar no seu código antes de usar o Vuex: ``` js import 'es6-promise/auto' @@ -65,8 +65,8 @@ import 'es6-promise/auto' ### Dev Build -You will have to clone directly from GitHub and build `vuex` yourself if -you want to use the latest dev build. +Você terá que clonar diretamente do GitHub e fazer o _build_ do `vuex` se +quiser usar a compilação mais recente do dev. ``` bash git clone https://github.com/vuejs/vuex.git node_modules/vuex From cf0a3f7821ffb3e999a70a472d19569f9a57cc28 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 7 Jun 2018 20:18:59 -0300 Subject: [PATCH 03/21] Translated the api docs --- docs/ptbr/api/README.md | 138 ++++++++++++++++++++-------------------- 1 file changed, 69 insertions(+), 69 deletions(-) diff --git a/docs/ptbr/api/README.md b/docs/ptbr/api/README.md index 906167686..192655acc 100644 --- a/docs/ptbr/api/README.md +++ b/docs/ptbr/api/README.md @@ -2,7 +2,7 @@ sidebar: auto --- -# API Reference +# Referência da API ## Vuex.Store @@ -12,74 +12,74 @@ import Vuex from 'vuex' const store = new Vuex.Store({ ...options }) ``` -## Vuex.Store Constructor Options +## Vuex.Store Opções do Construtor -### state +### estado - type: `Object | Function` - The root state object for the Vuex store. [Details](../guide/state.md) + O objeto raiz de estado para o _store_ Vuex. [Detalhes](../guide/state.md) - If you pass a function that returns an object, the returned object is used as the root state. This is useful when you want to reuse the state object especially for module reuse. [Details](../guide/modules.md#module-reuse) + Se você passar uma função que retorna um objeto, o objeto retornado é usado como o estado da raiz. Isso é útil quando você deseja reutilizar o objeto de estado, especialmente para reutilização de módulos. [Detalhes](../guide/modules.md#reutilização-do-módulo) -### mutations +### mutações - type: `{ [type: string]: Function }` - Register mutations on the store. The handler function always receives `state` as the first argument (will be module local state if defined in a module), and receives a second `payload` argument if there is one. + Registra mutações no _store_. A função do manipulador sempre recebe `estado` como o 1º argumento (será o estado local do módulo se definido em um módulo) e receberá um 2º argumento _payload_ se houver um. - [Details](../guide/mutations.md) + [Detalhes](../guide/mutations.md) -### actions +### ações - type: `{ [type: string]: Function }` - Register actions on the store. The handler function receives a `context` object that exposes the following properties: + Registra ações no _store_. A função do manipulador recebe um objeto _context_ que expõe as seguintes propriedades: ``` js { - state, // same as `store.state`, or local state if in modules - rootState, // same as `store.state`, only in modules - commit, // same as `store.commit` - dispatch, // same as `store.dispatch` - getters, // same as `store.getters`, or local getters if in modules - rootGetters // same as `store.getters`, only in modules + state, // o mesmo que `store.state`, ou estado local se estiver em módulos + rootState, // o mesmo que `store.state`, apenas em módulos + commit, // o mesmo que `store.commit` + dispatch, // o mesmo que `store.dispatch` + getters, // o mesmo que `store.getters`, ou com getters locais se estiver em módulos + rootGetters // o mesmo que `store.getters`, apenas em módulos } ``` - And also receives a second `payload` argument if there is one. + E também recebe um 2º argumento _payload_ se houver um. - [Details](../guide/actions.md) + [Detalhes](../guide/actions.md) ### getters - type: `{ [key: string]: Function }` - Register getters on the store. The getter function receives the following arguments: + Registra _getters_ no _store_. A função _getter_ recebe os seguintes argumentos: ``` - state, // will be module local state if defined in a module. - getters // same as store.getters + state, // será estado local do módulo se definido em um módulo. + getters // o mesmo que store.getters ``` - Specific when defined in a module + Específico quando definido em um módulo ``` - state, // will be module local state if defined in a module. - getters, // module local getters of the current module - rootState, // global state - rootGetters // all getters + state, // será estado local do módulo se definido em um módulo. + getters, // módulo de getters locais do módulo atual + rootState, // estado global + rootGetters // todos os getters ``` - Registered getters are exposed on `store.getters`. + Os _getters_ registrados estão expostos em _store.getters_. - [Details](../guide/getters.md) + [Detalhes](../guide/getters.md) -### modules +### módulos - type: `Object` - An object containing sub modules to be merged into the store, in the shape of: + Um objeto contendo sub módulos a serem incorporados no _store_, de forma que: ``` js { @@ -95,76 +95,76 @@ const store = new Vuex.Store({ ...options }) } ``` - Each module can contain `state` and `mutations` similar to the root options. A module's state will be attached to the store's root state using the module's key. A module's mutations and getters will only receives the module's local state as the first argument instead of the root state, and module actions' `context.state` will also point to the local state. + Cada módulo pode conter `estado` e `mutações` semelhantes às opções raiz. O estado de um módulo será anexado ao estado da raiz do _store_ usando a chave do módulo. As mutações e _getters_ de um módulo receberão apenas o estado local do módulo como o 1º argumento em vez do estado da raiz e as ações do módulo _context.state_ também apontarão para o estado local. - [Details](../guide/modules.md) + [Detalhes](../guide/modules.md) ### plugins - type: `Array` - An array of plugin functions to be applied to the store. The plugin simply receives the store as the only argument and can either listen to mutations (for outbound data persistence, logging, or debugging) or dispatch mutations (for inbound data e.g. websockets or observables). + Um _array_ de funções de plug-in a serem aplicadas no _store_. O plug-in simplesmente recebe o _store_ como o único argumento e pode ouvir mutações (para persistência de dados de saída, registro ou depuração) ou mutações de despacho (para dados de entrada, por exemplo, websockets ou _observables_). - [Details](../guide/plugins.md) + [Detalhes](../guide/plugins.md) ### strict - type: `Boolean` - default: `false` - Force the Vuex store into strict mode. In strict mode any mutations to Vuex state outside of mutation handlers will throw an Error. + Força o _store_ Vuex em modo estrito. No modo estrito, qualquer mutação ao estado do Vuex fora dos manipuladores de mutação acusará um erro. - [Details](../guide/strict.md) + [Detalhes](../guide/strict.md) -## Vuex.Store Instance Properties +## Vuex.Store Propriedades da Instância ### state - type: `Object` - The root state. Read only. + O estado raiz. Apenas leitura. ### getters - type: `Object` - Exposes registered getters. Read only. + Expõe os _getters_ registrados. Apenas leitura. -## Vuex.Store Instance Methods +## Vuex.Store Métodos da Instância ### commit - `commit(type: string, payload?: any, options?: Object)` - `commit(mutation: Object, options?: Object)` - Commit a mutation. `options` can have `root: true` that allows to commit root mutations in [namespaced modules](../guide/modules.md#namespacing). [Details](../guide/mutations.md) + Confirma (ou faz um _Commit_ de) uma mutação. _options_ pode ter _root: true_ que permite confirmar mutações da raiz em [módulos namespaced](../guide/modules.md#namespacing). [Detalhes](../guide/mutations.md) ### dispatch - `dispatch(type: string, payload?: any, options?: Object)` - `dispatch(action: Object, options?: Object)` - Dispatch an action. `options` can have `root: true` that allows to dispatch root actions in [namespaced modules](../guide/modules.md#namespacing). Returns a Promise that resolves all triggered action handlers. [Details](../guide/actions.md) + Despacha uma ação. _options_ pode ter _root: true_ que permite despachar ações para raiz em [módulos namespaced](../guide/modules.md#namespacing). Retorna um _Promise_ que resolve todos os manipuladores de ação acionados. [Detalhes](../guide/actions.md) ### replaceState - `replaceState(state: Object)` - Replace the store's root state. Use this only for state hydration / time-travel purposes. + Substitua o estado da raiz do _store_. Use isso apenas para fins de _hydration_ / _time-travel_. ### watch - `watch(fn: Function, callback: Function, options?: Object): Function` - Reactively watch `fn`'s return value, and call the callback when the value changes. `fn` receives the store's state as the first argument, and getters as the second argument. Accepts an optional options object that takes the same options as Vue's `vm.$watch` method. + Visualiza de forma reativa um valor de retorno de `fn`, e chama o _callback_ para o retorno de chamada quando o valor for alterado. O `fn` recebe o estado do _store_ como o 1º argumento, e os _getters_ como o 2º argumento. Aceita um objeto de opções opcional que leva as mesmas opções que o método _vm.$watch_ do Vue. - To stop watching, call the returned unwatch function. + Para parar um _watch_, chame a função _unwatch_ retornada. ### subscribe - `subscribe(handler: Function): Function` - Subscribe to store mutations. The `handler` is called after every mutation and receives the mutation descriptor and post-mutation state as arguments: + Assina as mutações do _store_. O `manipulador` é chamado após cada mutação e recebe o descritor de mutação e o estado pós-mutação como argumentos: ``` js store.subscribe((mutation, state) => { @@ -173,17 +173,17 @@ const store = new Vuex.Store({ ...options }) }) ``` - To stop subscribing, call the returned unsubscribe function. + Para cancelar a assinatura, chame a função _unsubscribe_ retornada. - Most commonly used in plugins. [Details](../guide/plugins.md) + Mais comumente usado em plugins. [Detalhes](../guide/plugins.md) ### subscribeAction - `subscribeAction(handler: Function): Function` - > New in 2.5.0 + > Novo na 2.5.0 - Subscribe to store actions. The `handler` is called for every dispatched action and receives the action descriptor and current store state as arguments: + Assina as ações do _store_. O `manipulador` é chamado para cada ação despachada e recebe o descritor de ação e o estado atual do _store_ como argumentos: ``` js store.subscribeAction((action, state) => { @@ -192,72 +192,72 @@ const store = new Vuex.Store({ ...options }) }) ``` - To stop subscribing, call the returned unsubscribe function. + Para cancelar a assinatura, chame a função _unsubscribe_ retornada. - Most commonly used in plugins. [Details](../guide/plugins.md) + Mais comumente usado em plugins. [Detalhes](../guide/plugins.md) ### registerModule - `registerModule(path: string | Array, module: Module, options?: Object)` - Register a dynamic module. [Details](../guide/modules.md#dynamic-module-registration) + Registra um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-módulo-dinâmico) - `options` can have `preserveState: true` that allows to preserve the previous state. Useful with Server Side Rendering. + _options_ can have _preserveState: true_ que permite preservar o estado anterior. Útil com renderização do lado do servidor (_server-side-rendering_). ### unregisterModule - `unregisterModule(path: string | Array)` - Unregister a dynamic module. [Details](../guide/modules.md#dynamic-module-registration) + Cancela o registro de um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-módulo-dinâmico) ### hotUpdate - `hotUpdate(newOptions: Object)` - Hot swap new actions and mutations. [Details](../guide/hot-reload.md) + Faz _Hot_ _swap_ de novas ações e mutações. [Detalhes](../guide/hot-reload.md) -## Component Binding Helpers +## Métodos Auxiliares dos Componentes ### mapState - `mapState(namespace?: string, map: Array | Object): Object` - Create component computed options that return the sub tree of the Vuex store. [Details](../guide/state.md#the-mapstate-helper) + Criar dados computados do componente que retornam a subárvore do _store_ Vuex. [Detalhes](../guide/state.md#o-auxiliar-mapstate) - The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) - The second object argument's members can be a function. `function(state: any)` + O segundo objeto que compõem os argumentos pode ser uma função. `function(state: any)` ### mapGetters - `mapGetters(namespace?: string, map: Array | Object): Object` - Create component computed options that return the evaluated value of a getter. [Details](../guide/getters.md#the-mapgetters-helper) + Criar dados computados do componente que retornam o valor calculado de um _getter_. [Detalhes](../guide/getters.md#o-auxiliar-mapgetters) - The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) ### mapActions - `mapActions(namespace?: string, map: Array | Object): Object` - Create component methods options that dispatch an action. [Details](../guide/actions.md#dispatching-actions-in-components) + Criar opções de métodos nos componentes que despacham uma ação. [Detalhes](../guide/actions.md#ações-de-despacho-em-componentes) - The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) - The second object argument's members can be a function. `function(dispatch: function, ...args: any[])` + O segundo objeto que compõem os argumentos pode ser uma função. `function(dispatch: function, ...args: any[])` ### mapMutations - `mapMutations(namespace?: string, map: Array | Object): Object` - Create component methods options that commit a mutation. [Details](../guide/mutations.md#committing-mutations-in-components) + Criar opções de métodos nos componentes que confirmam (ou fazem um _commit_ de) uma mutação. [Detalhes](../guide/mutations.md#fazendo-commit-de-mutações-em-componente) - The first argument can optionally be a namespace string. [Details](../guide/modules.md#binding-helpers-with-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) -  The second object argument's members can be a function. `function(commit: function, ...args: any[])` +  O segundo objeto que compõem os argumentos pode ser uma função. `function(commit: function, ...args: any[])` ### createNamespacedHelpers - `createNamespacedHelpers(namespace: string): Object` - Create namespaced component binding helpers. The returned object contains `mapState`, `mapGetters`, `mapActions` and `mapMutations` that are bound with the given namespace. [Details](../guide/modules.md#binding-helpers-with-namespace) + Cria um componente _namespaced_ dos métodos auxiliares. O objeto retornado possui _mapState_, _mapGetters_, _mapActions_ e _mapMutations_, que estão conectados com o dado _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) From 2faaa8180b94601df316d7535449ebdbfd110983 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Jun 2018 16:02:04 -0300 Subject: [PATCH 04/21] Translate some files --- docs/ptbr/guide/actions.md | 72 ++++++++++++++++---------------- docs/ptbr/guide/core-concepts.md | 16 +++---- docs/ptbr/guide/forms.md | 14 ++++--- 3 files changed, 52 insertions(+), 50 deletions(-) diff --git a/docs/ptbr/guide/actions.md b/docs/ptbr/guide/actions.md index c89fffe0b..8a66eab85 100644 --- a/docs/ptbr/guide/actions.md +++ b/docs/ptbr/guide/actions.md @@ -1,11 +1,11 @@ -# Actions +# Ações -Actions are similar to mutations, the differences being that: +As ações são semelhantes às mutações, as diferenças são as seguintes: -- Instead of mutating the state, actions commit mutations. -- Actions can contain arbitrary asynchronous operations. +- Em vez de mudar o estado, as ações confirmam (ou fazem _commit_ de) mutações. +- As ações podem conter operações assíncronas arbitrárias. -Let's register a simple action: +Vamos registrar uma ação simples: ``` js const store = new Vuex.Store({ @@ -25,9 +25,9 @@ const store = new Vuex.Store({ }) ``` -Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call `context.commit` to commit a mutation, or access the state and getters via `context.state` and `context.getters`. We will see why this context object is not the store instance itself when we introduce [Modules](modules.md) later. +Os manipuladores de ação recebem um objeto _context_ que expõe o mesmo conjunto de métodos/propriedades na instância do _store_, para que você possa chamar _context.commit_ para confirmar uma mutação ou acessar o estado e os _getters_ através do _context.state_ e do _context.getters_. Veremos por que esse objeto _context_ não é a própria instância do _store_ quando apresentarmos [Módulos](modules.md) mais tarde. -In practice, we often use ES2015 [argument destructuring](https://github.com/lukehoban/es6features#destructuring) to simplify the code a bit (especially when we need to call `commit` multiple times): +Na prática, muitas vezes usamos ES2015 [desestruturação de argumentos](https://github.com/lukehoban/es6features#destructuring) para simplificar um pouco o código (especialmente quando precisamos usar _commit_ várias vezes): ``` js actions: { @@ -37,15 +37,15 @@ actions: { } ``` -### Dispatching Actions +### Ações de Despacho -Actions are triggered with the `store.dispatch` method: +As ações são acionadas com o método _store.dispatch_: ``` js store.dispatch('increment') ``` -This may look dumb at first sight: if we want to increment the count, why don't we just call `store.commit('increment')` directly? Remember that **mutations have to be synchronous**? Actions don't. We can perform **asynchronous** operations inside an action: +Isso pode parecer óbvio à primeira vista: se quisermos incrementar a contagem, por que não chamamos `store.commit('increment')` diretamente? Você se lembra que **as mutações devem ser síncronas**? As ações não. Podemos executar **operações assíncronas** dentro de uma ação: ``` js actions: { @@ -57,48 +57,48 @@ actions: { } ``` -Actions support the same payload format and object-style dispatch: +As ações suportam o mesmo formato de _payload_ e despacho estilo-objeto: ``` js -// dispatch with a payload +// despacho com um payload store.dispatch('incrementAsync', { amount: 10 }) -// dispatch with an object +// despacho com objeto store.dispatch({ type: 'incrementAsync', amount: 10 }) ``` -A more practical example of real-world actions would be an action to checkout a shopping cart, which involves **calling an async API** and **committing multiple mutations**: +Um exemplo mais prático de ações reais seria uma ação para fazer _checkout_ de um carrinho de compras, que envolve **chamar uma API assíncrona** e **confirmar múltiplas mutações**: ``` js actions: { checkout ({ commit, state }, products) { - // save the items currently in the cart + // salva os itens que estão no carrinho const savedCartItems = [...state.cart.added] - // send out checkout request, and optimistically - // clear the cart + // envia solicitação de checkout, e otimista + // limpa o carrinho commit(types.CHECKOUT_REQUEST) - // the shop API accepts a success callback and a failure callback + // a API da loja aceita um callback bem-sucedido e um callback com falha shop.buyProducts( products, - // handle success + // callback em caso de sucesso () => commit(types.CHECKOUT_SUCCESS), - // handle failure + // callback em caso de falha () => commit(types.CHECKOUT_FAILURE, savedCartItems) ) } } ``` -Note we are performing a flow of asynchronous operations, and recording the side effects (state mutations) of the action by committing them. +Observe que estamos realizando um fluxo de operações assíncronas, e gravando os efeitos colaterais (mutações de estado) da ação confirmando-os (ou fazendo _commit_ deles). -### Dispatching Actions in Components +### Ações de Despacho em Componentes -You can dispatch actions in components with `this.$store.dispatch('xxx')`, or use the `mapActions` helper which maps component methods to `store.dispatch` calls (requires root `store` injection): +Você pode despachar ações em componentes com `this.$store.dispatch('xxx')`, ou usar o auxiliar _mapActions_ que mapeia métodos do componente para chamadas do _store.dispatch_ (esta ação requer injeção do _store_ na instância raiz): ``` js import { mapActions } from 'vuex' @@ -107,23 +107,23 @@ export default { // ... methods: { ...mapActions([ - 'increment', // map `this.increment()` to `this.$store.dispatch('increment')` + 'increment', // mapeia `this.increment()` para `this.$store.dispatch('increment')` - // `mapActions` also supports payloads: - 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)` + // `mapActions` também suporta payloads: + 'incrementBy' // mapeia `this.incrementBy(amount)` para `this.$store.dispatch('incrementBy', amount)` ]), ...mapActions({ - add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')` + add: 'increment' // mapeia `this.add()` para `this.$store.dispatch('increment')` }) } } ``` -### Composing Actions +### Composição de Ações -Actions are often asynchronous, so how do we know when an action is done? And more importantly, how can we compose multiple actions together to handle more complex async flows? +As ações geralmente são assíncronas, então como sabemos quando uma ação é realizada? E mais importante, como podemos compor ações múltiplas em conjunto para lidar com fluxos assíncronos mais complexos? -The first thing to know is that `store.dispatch` can handle Promise returned by the triggered action handler and it also returns Promise: +A primeira coisa a saber é que o _store.dispatch_ pode manipular o _Promise_ retornado pelo manipulador de ação acionado e também retorna _Promise_: ``` js actions: { @@ -138,7 +138,7 @@ actions: { } ``` -Now you can do: +Agora você pode fazer: ``` js store.dispatch('actionA').then(() => { @@ -146,7 +146,7 @@ store.dispatch('actionA').then(() => { }) ``` -And also in another action: +E também em outra ação: ``` js actions: { @@ -159,20 +159,20 @@ actions: { } ``` -Finally, if we make use of [async / await](https://tc39.github.io/ecmascript-asyncawait/), we can compose our actions like this: +Finalmente, se fizermos uso de [async / await](https://tc39.github.io/ecmascript-asyncawait/), podemos compor nossas ações como esta: ``` js -// assuming `getData()` and `getOtherData()` return Promises +// assumindo que `getData()` e `getOtherData()` retornam Promises actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { - await dispatch('actionA') // wait for `actionA` to finish + await dispatch('actionA') // espera que `actionA` termine commit('gotOtherData', await getOtherData()) } } ``` -> It's possible for a `store.dispatch` to trigger multiple action handlers in different modules. In such a case the returned value will be a Promise that resolves when all triggered handlers have been resolved. +> É possível para um _store.dispatch_ desencadear vários manipuladores de ação em diferentes módulos. Neste caso, o valor retornado será um _Promise_ que resolve quando todos os manipuladores desencadeados foram resolvidos. diff --git a/docs/ptbr/guide/core-concepts.md b/docs/ptbr/guide/core-concepts.md index 22ce634e9..63d30c989 100644 --- a/docs/ptbr/guide/core-concepts.md +++ b/docs/ptbr/guide/core-concepts.md @@ -1,13 +1,13 @@ -# Core Concepts +# Conceitos Básicos -We will be learning the core concepts of Vuex in these chapters. They are: +Vamos aprender os conceitos básicos do Vuex nestes capítulos. São eles: -- [State](state.md) +- [Estado](state.md) - [Getters](getters.md) -- [Mutations](mutations.md) -- [Actions](actions.md) -- [Modules](modules.md) +- [Mutações](mutations.md) +- [Ações](actions.md) +- [Módulos](modules.md) -A deep understanding of all these concepts is essential for using vuex. +Uma compreensão profunda de todos esses conceitos é essencial para o uso de vuex. -Let's get started. +Vamos começar. diff --git a/docs/ptbr/guide/forms.md b/docs/ptbr/guide/forms.md index 37fd58e56..0ea4306de 100644 --- a/docs/ptbr/guide/forms.md +++ b/docs/ptbr/guide/forms.md @@ -1,6 +1,6 @@ -# Form Handling +# Manipulação de Formulários -When using Vuex in strict mode, it could be a bit tricky to use `v-model` on a piece of state that belongs to Vuex: +Ao usar o Vuex no modo estrito, pode ser um pouco complicado usar `v-model` em um pedaço do estado que pertence ao Vuex: ``` html @@ -8,7 +8,9 @@ When using Vuex in strict mode, it could be a bit tricky to use `v-model` on a p Assuming `obj` is a computed property that returns an Object from the store, the `v-model` here will attempt to directly mutate `obj.message` when the user types in the input. In strict mode, this will result in an error because the mutation is not performed inside an explicit Vuex mutation handler. -The "Vuex way" to deal with it is binding the ``'s value and call an action on the `input` or `change` event: +Assumindo que `obj` é um dado computado que retorna um Objeto do _store_, o `v-model` aqui tentará alterar diretamente o `obj.message` quando o usuário digitar alguma coisa. No modo estrito, isso resultará em um erro porque a mutação não é executada dentro de um manipulador explícito de mutação Vuex. + +O "modo Vuex" para lidar com isso é vinculando o valor do(s) ``'s e chamar uma ação no evento `input` ou `change`: ``` html @@ -27,7 +29,7 @@ methods: { } ``` -And here's the mutation handler: +E aqui está o manipulador de mutação: ``` js // ... @@ -38,9 +40,9 @@ mutations: { } ``` -### Two-way Computed Property +### Dados Computados Bidirecionais (Two-way) -Admittedly, the above is quite a bit more verbose than `v-model` + local state, and we lose some of the useful features from `v-model` as well. An alternative approach is using a two-way computed property with a setter: +É certo que o acima é um pouco mais verboso do que o `v-model` + estado local, e também perdemos alguns dos recursos úteis do `v-model`. Uma abordagem alternativa está usando uma dado computado bidirecional com um _setter_: ``` html From 880a4679c791086bd09a88050295a0ab2818fa7f Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Jun 2018 19:49:06 -0300 Subject: [PATCH 05/21] Translate some more files --- docs/ptbr/guide/getters.md | 34 ++++++------ docs/ptbr/guide/hot-reload.md | 16 +++--- docs/ptbr/guide/modules.md | 99 ++++++++++++++++++----------------- 3 files changed, 76 insertions(+), 73 deletions(-) diff --git a/docs/ptbr/guide/getters.md b/docs/ptbr/guide/getters.md index 124f38fac..911e2aeac 100644 --- a/docs/ptbr/guide/getters.md +++ b/docs/ptbr/guide/getters.md @@ -1,6 +1,6 @@ # Getters -Sometimes we may need to compute derived state based on store state, for example filtering through a list of items and counting them: +Às vezes, talvez precisemos calcular o estado derivado com base no estado do _store_, por exemplo, filtrar através de uma lista de itens e contá-los: ``` js computed: { @@ -10,11 +10,11 @@ computed: { } ``` -If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared helper and import it in multiple places - both are less than ideal. +Se mais do que um componente precisa fazer uso disso, temos que duplicar a função, ou extraí-lo em um auxiliar compartilhado e importá-lo em vários lugares - ambos são menos do que o ideal. -Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed. +O Vuex nos permite definir _getters_ no _store_. Você pode pensar neles como dados computados para os _stores_. Como os dados computados, o resultado de um _getter_ é armazenado em cache com base em suas dependências e só será reavaliado quando algumas de suas dependências forem alteradas. -Getters will receive the state as their 1st argument: +Os _getters_ receberão o estado como 1º argumento: ``` js const store = new Vuex.Store({ @@ -32,15 +32,15 @@ const store = new Vuex.Store({ }) ``` -### Property-Style Access +### Acesso Estilo-Propriedade -The getters will be exposed on the `store.getters` object, and you access values as properties: +Os _getters_ serão expostos no objeto _store.getters_ e você acessa valores como propriedades: ``` js store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }] ``` -Getters will also receive other getters as the 2nd argument: +Os _getters_ também receberão outros _getters_ como o 2º argumento: ``` js getters: { @@ -55,7 +55,7 @@ getters: { store.getters.doneTodosCount // -> 1 ``` -We can now easily make use of it inside any component: +Agora podemos usar facilmente isso dentro de qualquer componente: ``` js computed: { @@ -65,11 +65,11 @@ computed: { } ``` -Note that getters accessed as properties are cached as part of Vue's reactivity system. +Observe que os _getters_ acessados ​​como propriedades são armazenados em cache como parte do sistema de reatividade do Vue. -### Method-Style Access +### Acesso Estilo-Método -You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store: +Você também pode passar argumentos para os _getters_ retornando uma função. Isso é particularmente útil quando você deseja consultar um _array_ no _store_: ```js getters: { @@ -84,11 +84,11 @@ getters: { store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false } ``` -Note that getters accessed via methods will run each time you call them, and the result is not cached. +Observe que os _getters_ acessados ​​via métodos serão executados toda vez que você os chamar, e o resultado não será armazenado em cache. -### The `mapGetters` Helper +### O Auxiliar `mapGetters` -The `mapGetters` helper simply maps store getters to local computed properties: +O auxiliar `mapGetters` simplesmente mapeia os _getters_ do _store_ para os dados computados locais: ``` js import { mapGetters } from 'vuex' @@ -96,7 +96,7 @@ import { mapGetters } from 'vuex' export default { // ... computed: { - // mix the getters into computed with object spread operator + // mistura os getters nos dados computatos com o operador spread ...mapGetters([ 'doneTodosCount', 'anotherGetter', @@ -106,11 +106,11 @@ export default { } ``` -If you want to map a getter to a different name, use an object: +Se você deseja mapear um _getter_ com um nome diferente, use um objeto: ``` js ...mapGetters({ - // map `this.doneCount` to `this.$store.getters.doneTodosCount` + // mapeia `this.doneCount` para `this.$store.getters.doneTodosCount` doneCount: 'doneTodosCount' }) ``` diff --git a/docs/ptbr/guide/hot-reload.md b/docs/ptbr/guide/hot-reload.md index 453343c70..204032b83 100644 --- a/docs/ptbr/guide/hot-reload.md +++ b/docs/ptbr/guide/hot-reload.md @@ -1,8 +1,8 @@ -# Hot Reloading +# Hot Reloading (Recarregamento Rápido) -Vuex supports hot-reloading mutations, modules, actions and getters during development, using webpack's [Hot Module Replacement API](https://webpack.js.org/guides/hot-module-replacement/). You can also use it in Browserify with the [browserify-hmr](https://github.com/AgentME/browserify-hmr/) plugin. +O Vuex suporta _hot-reloading_ de mutações, módulos, ações e _getters_ durante o desenvolvimento, utilizando o _webpack_ [Hot Module Replacement API](https://webpack.js.org/guides/hot-module-replacement/). Você também pode usá-lo no Browserify com o _plugin_ [browserify-hmr](https://github.com/AgentME/browserify-hmr/). -For mutations and modules, you need to use the `store.hotUpdate()` API method: +Para mutações e módulos, você precisa usar o método da API `store.hotUpdate()`: ``` js // store.js @@ -24,13 +24,13 @@ const store = new Vuex.Store({ }) if (module.hot) { - // accept actions and mutations as hot modules + // aceita ações e mutações como 'hot modules' module.hot.accept(['./mutations', './modules/a'], () => { - // require the updated modules - // have to add .default here due to babel 6 module output + // requer os módulos atualizados + // tem que adicionar .default aqui devido à saída do módulo babel 6 const newMutations = require('./mutations').default const newModuleA = require('./modules/a').default - // swap in the new actions and mutations + // troca nas novas ações e mutações store.hotUpdate({ mutations: newMutations, modules: { @@ -41,4 +41,4 @@ if (module.hot) { } ``` -Checkout the [counter-hot example](https://github.com/vuejs/vuex/tree/dev/examples/counter-hot) to play with hot-reload. +Confira o [counter-hot example](https://github.com/vuejs/vuex/tree/dev/examples/counter-hot) para brincar com o hot-reload. diff --git a/docs/ptbr/guide/modules.md b/docs/ptbr/guide/modules.md index 1ba8fb07c..b25d6eb9e 100644 --- a/docs/ptbr/guide/modules.md +++ b/docs/ptbr/guide/modules.md @@ -1,8 +1,8 @@ -# Modules +# Módulos -Due to using a single state tree, all state of our application is contained inside one big object. However, as our application grows in scale, the store can get really bloated. +Devido ao uso de uma única árvore de estado, todo o estado de nossa aplicação está contido dentro de um grande objeto. No entanto, à medida que nosso aplicativo cresce em escala, o _store_ pode ficar realmente inchado. -To help with that, Vuex allows us to divide our store into **modules**. Each module can contain its own state, mutations, actions, getters, and even nested modules - it's fractal all the way down: +Para ajudar com isso, o Vuex nos permite dividir nosso _store_ em **módulos**. Cada módulo pode conter seu próprio estado, mutações, ações, _getters_ e até módulos aninhados - é todo o complexo caminho abaixo: ``` js const moduleA = { @@ -29,16 +29,16 @@ store.state.a // -> `moduleA`'s state store.state.b // -> `moduleB`'s state ``` -### Module Local State +### Estado Local do Módulo -Inside a module's mutations and getters, the first argument received will be **the module's local state**. +Dentro das mutações e _getters_ de um módulo, o 1º argumento recebido será **o estado local do módulo**. ``` js const moduleA = { state: { count: 0 }, mutations: { increment (state) { - // `state` is the local module state + // `state` é o estado local do módulo state.count++ } }, @@ -51,7 +51,7 @@ const moduleA = { } ``` -Similarly, inside module actions, `context.state` will expose the local state, and root state will be exposed as `context.rootState`: +Da mesma forma, dentro das ações do módulo, _context.state_ irá expor o estado local, e o estado raiz será exposto como _context.rootState_: ``` js const moduleA = { @@ -66,7 +66,7 @@ const moduleA = { } ``` -Also, inside module getters, the root state will be exposed as their 3rd argument: +Além disso, dentro do módulo _getters_, o estado raiz será exibido como seu 3º argumento: ``` js const moduleA = { @@ -81,9 +81,9 @@ const moduleA = { ### Namespacing -By default, actions, mutations and getters inside modules are still registered under the **global namespace** - this allows multiple modules to react to the same mutation/action type. +Por padrão, ações, mutações e _getters_ dentro dos módulos ainda são registrados sob o **namespace global** - isso permite que vários módulos reajam ao mesmo tipo de ação/mutação. -If you want your modules to be more self-contained or reusable, you can mark it as namespaced with `namespaced: true`. When the module is registered, all of its getters, actions and mutations will be automatically namespaced based on the path the module is registered at. For example: +Se você quer que seus módulos sejam mais independentes ou reutilizáveis, você pode marcá-los como _namespaced_ com _namespaced: true_. Quando o módulo é registrado, todos os _getters_, ações e mutações serão automaticamente _namespaced_ com base no caminho no qual o módulo está registrado. Por exemplo: ``` js const store = new Vuex.Store({ @@ -92,7 +92,7 @@ const store = new Vuex.Store({ namespaced: true, // module assets - state: { ... }, // module state is already nested and not affected by namespace option + state: { ... }, // o estado do módulo já está aninhado e não é afetado pela opção de namespace getters: { isAdmin () { ... } // -> getters['account/isAdmin'] }, @@ -103,9 +103,9 @@ const store = new Vuex.Store({ login () { ... } // -> commit('account/login') }, - // nested modules + // módulos aninhados modules: { - // inherits the namespace from parent module + // herda o namespace do modulo pai myPage: { state: { ... }, getters: { @@ -113,7 +113,7 @@ const store = new Vuex.Store({ } }, - // further nest the namespace + // aninhar ainda mais o namespace posts: { namespaced: true, @@ -128,13 +128,13 @@ const store = new Vuex.Store({ }) ``` -Namespaced getters and actions will receive localized `getters`, `dispatch` and `commit`. In other words, you can use the module assets without writing prefix in the same module. Toggling between namespaced or not does not affect the code inside the module. +Os _getters_ e as ações _namespaced_ receberão _getters_, _dispatch_ e _commit_ localizados. Em outras palavras, você pode usar os recursos do módulo sem escrever prefixo no mesmo módulo. Alternar entre _namespaced_ ou não, não afeta o código dentro do módulo. -#### Accessing Global Assets in Namespaced Modules +#### Acessando Recursos Globais em Módulos Namespaced -If you want to use global state and getters, `rootState` and `rootGetters` are passed as the 3rd and 4th arguments to getter functions, and also exposed as properties on the `context` object passed to action functions. +Se você quiser usar estado global e _getters_, _rootState_ e _rootGetters_ são passados como o 3º e 4º argumentos para funções _getter_, e também expostos como propriedades no objeto _context_ passado para funções de ação. -To dispatch actions or commit mutations in the global namespace, pass `{ root: true }` as the 3rd argument to `dispatch` and `commit`. +Para despachar ações confirmar (ou fazer um _commit_ de) mutações no _namespace_ global, passe `{root: true}` como o 3º argumento para _dispatch_ e _commit_. ``` js modules: { @@ -142,8 +142,8 @@ modules: { namespaced: true, getters: { - // `getters` is localized to this module's getters - // you can use rootGetters via 4th argument of getters + // `getters` está localizado nos getters deste módulo + // você pode usar rootGetters como 4º argumento de getters someGetter (state, getters, rootState, rootGetters) { getters.someOtherGetter // -> 'foo/someOtherGetter' rootGetters.someOtherGetter // -> 'someOtherGetter' @@ -152,8 +152,8 @@ modules: { }, actions: { - // dispatch and commit are also localized for this module - // they will accept `root` option for the root dispatch/commit + // dispatch e commit também estão localizados para este módulo + // eles aceitarão a opção `root` para o dispatch/commit da raiz someAction ({ dispatch, commit, getters, rootGetters }) { getters.someGetter // -> 'foo/someGetter' rootGetters.someGetter // -> 'someGetter' @@ -170,9 +170,9 @@ modules: { } ``` -#### Register Global Action in Namespaced Modules +#### Registrar Ação Global em Módulos com Namespaces -If you want to register global actions in namespaced modules, you can mark it with `root: true` and place the action definition to function `handler`. For example: +Se você quiser registrar ações globais em módulos com namespaces, você pode marcá-lo com _root: true_ e colocar a definição de ação na função _handler_. Por exemplo: ``` js { @@ -196,9 +196,9 @@ If you want to register global actions in namespaced modules, you can mark it wi } ``` -#### Binding Helpers with Namespace +#### Usando Métodos Auxiliares com Namespace -When binding a namespaced module to components with the `mapState`, `mapGetters`, `mapActions` and `mapMutations` helpers, it can get a bit verbose: +Ao vincular um módulo com _namespace_ aos componentes com os auxiliares _mapState_, _mapGetters_, _mapActions_ e _mapMutations_, ele pode ficar um pouco verboso: ``` js computed: { @@ -215,7 +215,7 @@ methods: { } ``` -In such cases, you can pass the module namespace string as the first argument to the helpers so that all bindings are done using that module as the context. The above can be simplified to: +Nesses casos, você pode passar a _string_ do _namespace_ do módulo como o 1º argumento para os auxiliares, de modo que todas as ligações sejam feitas usando esse módulo como o contexto. O acima pode ser simplificado para: ``` js computed: { @@ -232,7 +232,7 @@ methods: { } ``` -Furthermore, you can create namespaced helpers by using `createNamespacedHelpers`. It returns an object having new component binding helpers that are bound with the given namespace value: +Além disso, você pode criar auxiliares com _namespace_ usando _createNamespacedHelpers_. Ele retorna um objeto com novos métodos auxiliares dos componentes vinculados ao valor do _namespace_ fornecido: ``` js import { createNamespacedHelpers } from 'vuex' @@ -241,14 +241,14 @@ const { mapState, mapActions } = createNamespacedHelpers('some/nested/module') export default { computed: { - // look up in `some/nested/module` + // procure em `some/nested/module` ...mapState({ a: state => state.a, b: state => state.b }) }, methods: { - // look up in `some/nested/module` + // procure em `some/nested/module` ...mapActions([ 'foo', 'bar' @@ -257,57 +257,60 @@ export default { } ``` -#### Caveat for Plugin Developers +#### Advertência para Desenvolvedores de Plug-ins -You may care about unpredictable namespacing for your modules when you create a [plugin](plugins.md) that provides the modules and let users add them to a Vuex store. Your modules will be also namespaced if the plugin users add your modules under a namespaced module. To adapt this situation, you may need to receive a namespace value via your plugin option: +Você pode se preocupar com espaços de nomes imprevisíveis para seus módulos quando você cria um [plugin](plugins.md) que fornece os módulos e permite que os usuários os incluam em um _store_ Vuex. Seus módulos também serão _namespaced_ se os usuários do plugin adicionarem seus módulos em um módulo _namespaced_. Para adaptar esta situação, você pode precisar receber um valor de _namespace_ através de uma opção sua no plugin: ``` js -// get namespace value via plugin option -// and returns Vuex plugin function +// obtem valor do namespace via opção no plugin +// e retorna a função plugin do Vuex export function createPlugin (options = {}) { return function (store) { // add namespace to plugin module's types + // adicionar namespace aos tipos de módulo do plug-in const namespace = options.namespace || '' store.dispatch(namespace + 'pluginAction') } } ``` -### Dynamic Module Registration +### Registro de Módulo Dinâmico -You can register a module **after** the store has been created with the `store.registerModule` method: +Você pode registrar um módulo **após** o _store_ ser criado com o método _store.registerModule_: ``` js -// register a module `myModule` +// registra um módulo `myModule` store.registerModule('myModule', { // ... }) -// register a nested module `nested/myModule` +// registra um módulo aninhado `nested/myModule` store.registerModule(['nested', 'myModule'], { // ... }) ``` -The module's state will be exposed as `store.state.myModule` and `store.state.nested.myModule`. +Os estados do módulo serão expostos como _store.state.myModule_ e _store.state.nested.myModule_. -Dynamic module registration makes it possible for other Vue plugins to also leverage Vuex for state management by attaching a module to the application's store. For example, the [`vuex-router-sync`](https://github.com/vuejs/vuex-router-sync) library integrates vue-router with vuex by managing the application's route state in a dynamically attached module. +O registro de módulo dinâmico possibilita que outros plug-ins Vue aproveitem também o Vuex para gerenciamento de estado, anexando um módulo ao _store_ do aplicativo. Por exemplo, a biblioteca [`vuex-router-sync`](https://github.com/vuejs/vuex-router-sync) integra o vue-router com o vuex gerenciando o estado da rota do aplicativo em um módulo conectado dinamicamente. -You can also remove a dynamically registered module with `store.unregisterModule(moduleName)`. Note you cannot remove static modules (declared at store creation) with this method. +Você também pode remover um módulo dinamicamente registrado com o `store.unregisterModule(moduleName)`. Note que você não pode remover módulos estáticos (declarados na criação do _store_) com este método. -It may be likely that you want to preserve the previous state when registering a new module, such as preserving state from a Server Side Rendered app. You can do achieve this with `preserveState` option: `store.registerModule('a', module, { preserveState: true })` +É bem provável que você queira preservar o estado anterior ao registrar um novo módulo, como preservar o estado de um aplicativo Renderizado no Lado do Servidor (_Server_ _Side_ _Rendered_). Você pode fazer isso com a opção `preserveState`:`store.registerModule('a', module, {preserveState: true})` -### Module Reuse +### Reutilização do Módulo -Sometimes we may need to create multiple instances of a module, for example: +Às vezes, podemos precisar criar várias instâncias de um módulo, por exemplo: -- Creating multiple stores that use the same module (e.g. To [avoid stateful singletons in the SSR](https://ssr.vuejs.org/en/structure.html#avoid-stateful-singletons) when the `runInNewContext` option is `false` or `'once'`); -- Register the same module multiple times in the same store. +- Criando multiplos _stores_ que usam o mesmo módulo (e.g. Para [evitar Singletons com informações de estado no SSR](https://ssr.vuejs.org/en/structure.html#avoid-stateful-singletons) quando a opção _runInNewContext_ é _false_ ou `'_once_'`); +- Registrar o mesmo módulo várias vezes no mesmo _store_. -If we use a plain object to declare the state of the module, then that state object will be shared by reference and cause cross store/module state pollution when it's mutated. +Se usarmos um objeto simples para declarar o estado do módulo, esse objeto de estado será compartilhado por referência e causará poluição entre estados de _store_/módulo quando ele sofrer uma mutação. This is actually the exact same problem with `data` inside Vue components. So the solution is also the same - use a function for declaring module state (supported in 2.3.0+): +Este é exatamente o mesmo problema com _data_ dentro dos componentes do Vue. Então a solução também é a mesma - use uma função para declarar o estado do módulo (suportado em 2.3.0+): + ``` js const MyReusableModule = { state () { @@ -315,6 +318,6 @@ const MyReusableModule = { foo: 'bar' } }, - // mutations, actions, getters... + // mutações, ações, getters... } ``` From f45a57f3285b8ce57bb0d45774b665ad68ad1337 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Jun 2018 20:20:49 -0300 Subject: [PATCH 06/21] One more file --- docs/ptbr/guide/mutations.md | 70 +++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/docs/ptbr/guide/mutations.md b/docs/ptbr/guide/mutations.md index 00f18b1b6..e2c9e01f4 100644 --- a/docs/ptbr/guide/mutations.md +++ b/docs/ptbr/guide/mutations.md @@ -1,7 +1,9 @@ -# Mutations +# Mutações The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string **type** and a **handler**. The handler function is where we perform actual state modifications, and it will receive the state as the first argument: +A única maneira de realmente mudar de estado em um _store_ Vuex é por confirmar (ou fazer _commit_ de) uma mutação. As mutações do Vuex são muito semelhantes aos eventos: cada mutação tem uma cadeia de caracteres **tipo** e um **manipulador**. A função do manipulador é onde realizamos modificações de estado reais e ele receberá o estado como o 1º argumento: + ``` js const store = new Vuex.Store({ state: { @@ -9,22 +11,22 @@ const store = new Vuex.Store({ }, mutations: { increment (state) { - // mutate state + // muda o estado state.count++ } } }) ``` -You cannot directly call a mutation handler. Think of it more like event registration: "When a mutation with type `increment` is triggered, call this handler." To invoke a mutation handler, you need to call `store.commit` with its type: +Você não pode chamar diretamente um manipulador de mutação. Pense nisso mais como registro de evento: "Quando uma mutação com o tipo _increment_ é acionada, chame este manipulador." Para invocar um manipulador de mutação, você precisa chamar _store.commit_ com seu tipo: ``` js store.commit('increment') ``` -### Commit with Payload +### Commit com Payload -You can pass an additional argument to `store.commit`, which is called the **payload** for the mutation: +Você pode passar um argumento adicional para o _store.commit_, que é chamado de **payload** para a mutação: ``` js // ... @@ -38,7 +40,7 @@ mutations: { store.commit('increment', 10) ``` -In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive: +Na maioria dos casos, o _payload_ deve ser um objeto para que possa conter vários campos, e a mutação gravada também será mais descritiva: ``` js // ... @@ -55,9 +57,9 @@ store.commit('increment', { }) ``` -### Object-Style Commit +### Confirmação (ou Commit) Estilo-Objeto -An alternative way to commit a mutation is by directly using an object that has a `type` property: +Uma maneira alternativa de confirmar (ou fazer um _commit_ de) uma mutação é usando diretamente um objeto que tenha uma propriedade `type`: ``` js store.commit({ @@ -66,7 +68,7 @@ store.commit({ }) ``` -When using object-style commit, the entire object will be passed as the payload to mutation handlers, so the handler remains the same: +Ao usar a Confirmação Estilo-Objeto, o objeto inteiro será passado como o _payload_ para os manipuladores de mutação, portanto, o manipulador permanecerá o mesmo: ``` js mutations: { @@ -76,25 +78,27 @@ mutations: { } ``` -### Mutations Follow Vue's Reactivity Rules +### Mutações Seguem as Regras de Reatividade do Vue Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue: -1. Prefer initializing your store's initial state with all desired fields upfront. +Como o estado de um _store_ Vuex é reativado pelo Vue, quando alteramos o estado, os componentes do Vue observando o estado serão atualizados automaticamente. Isso também significa que as mutações do Vuex estão sujeitas às mesmas ressalvas de reatividade ao trabalhar com o Vue simples: -2. When adding new properties to an Object, you should either: +1. Prefira inicializar o estado inicial do seu _store_ com todos os campos desejados antecipadamente. - - Use `Vue.set(obj, 'newProp', 123)`, or +2. Ao adicionar novas propriedades a um Objeto, você deve: - - Replace that Object with a fresh one. For example, using the stage-3 [object spread syntax](https://github.com/sebmarkbage/ecmascript-rest-spread) we can write it like this: + - Usar `Vue.set(obj, 'newProp', 123)`, ou + + - Substitua esse objeto por um novo. Por exemplo, usando o _stage-3_ [object spread syntax](https://github.com/sebmarkbage/ecmascript-rest-spread) nós podemos escrevê-lo assim: ``` js state.obj = { ...state.obj, newProp: 123 } ``` -### Using Constants for Mutation Types +### Usando Constantes para Tipos de Mutação -It is a commonly seen pattern to use constants for mutation types in various Flux implementations. This allows the code to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application: +É um padrão comumente visto usar constantes para tipos de mutação em várias implementações do _Flux_. Isso permite que o código aproveite as ferramentas como os _linters_, e colocar todas as constantes em um único arquivo permite que seus colaboradores tenham uma visão geral das mutações possíveis em todo o aplicativo: ``` js // mutation-types.js @@ -109,8 +113,8 @@ import { SOME_MUTATION } from './mutation-types' const store = new Vuex.Store({ state: { ... }, mutations: { - // we can use the ES2015 computed property name feature - // to use a constant as the function name + // podemos usar o recurso de nome do dado computado do ES2015 + // para usar uma constante como o nome da função [SOME_MUTATION] (state) { // mutate state } @@ -118,12 +122,14 @@ const store = new Vuex.Store({ }) ``` -Whether to use constants is largely a preference - it can be helpful in large projects with many developers, but it's totally optional if you don't like them. +Se usar constantes é em grande parte uma preferência - pode ser útil em grandes projetos com muitos desenvolvedores, mas é totalmente opcional se você não gostar deles. -### Mutations Must Be Synchronous +### Mutações Devem Ser Síncronas One important rule to remember is that **mutation handler functions must be synchronous**. Why? Consider the following example: +Uma regra importante a lembrar é que **as funções do manipulador de mutação devem ser síncronas**. Por quê? Considere o seguinte exemplo: + ``` js mutations: { someMutation (state) { @@ -134,11 +140,11 @@ mutations: { } ``` -Now imagine we are debugging the app and looking at the devtool's mutation logs. For every mutation logged, the devtool will need to capture a "before" and "after" snapshots of the state. However, the asynchronous callback inside the example mutation above makes that impossible: the callback is not called yet when the mutation is committed, and there's no way for the devtool to know when the callback will actually be called - any state mutation performed in the callback is essentially un-trackable! +Agora imagine que estamos depurando o aplicativo e observando os logs de mutação do devtool. Para cada mutação registrada, o devtool precisará capturar os momentos "antes" e "depois" do estado. No entanto, o _callback_ assíncrono dentro da mutação de exemplo acima torna isso impossível: o _callback_ ainda não é chamado quando a mutação é confirmada (ou o _commit_ da mutação é feito) e não há como o devtool saber quando o _callback_ será realmente chamado - qualquer mutação de estado executada no _callback_ é essencialmente impossível de rastrear! -### Committing Mutations in Components +### Confirmando (ou fazendo Commits de) Mutações em Componentes -You can commit mutations in components with `this.$store.commit('xxx')`, or use the `mapMutations` helper which maps component methods to `store.commit` calls (requires root `store` injection): +Você pode confirmar (ou fazer _commit_ de) mutações em componentes com `this.$store.commit('xxx')`, ou use o auxiliar `mapMutations` que mapeia métodos de componentes para chamadas _store.commit_ (requer injeção _store_ raiz): ``` js import { mapMutations } from 'vuex' @@ -147,26 +153,26 @@ export default { // ... methods: { ...mapMutations([ - 'increment', // map `this.increment()` to `this.$store.commit('increment')` + 'increment', // mapeia `this.increment()` para `this.$store.commit('increment')` - // `mapMutations` also supports payloads: - 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)` + // `mapMutations` também suporta payloads: + 'incrementBy' // mapeia `this.incrementBy(amount)` para `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ - add: 'increment' // map `this.add()` to `this.$store.commit('increment')` + add: 'increment' // mapeia `this.add()` para `this.$store.commit('increment')` }) } } ``` -### On to Actions +### Vamos as Ações -Asynchronicity combined with state mutation can make your program very hard to reason about. For example, when you call two methods both with async callbacks that mutate the state, how do you know when they are called and which callback was called first? This is exactly why we want to separate the two concepts. In Vuex, **mutations are synchronous transactions**: +Assincronia combinada com mutação de estado pode tornar seu programa muito difícil de ser compreendido. Por exemplo, quando você chama dois métodos com _callbacks_ assíncronos que alteram o estado, como você sabe quando eles são chamados e qual _callback_ foi chamado primeiro? É exatamente por isso que queremos separar os dois conceitos. No Vuex, **mutações são transações síncronas**: ``` js store.commit('increment') -// any state change that the "increment" mutation may cause -// should be done at this moment. +// qualquer mudança de estado que a mutação "increment" pode causar +// deve ser feito neste momento. ``` -To handle asynchronous operations, let's introduce [Actions](actions.md). +Para lidar com operações assíncronas, vamos apresentar [Ações](actions.md). From 1c7731c45af0e10214cd4faa9f937855be83fa4c Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Jun 2018 20:28:46 -0300 Subject: [PATCH 07/21] made some fixes in translation --- docs/ptbr/guide/mutations.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/ptbr/guide/mutations.md b/docs/ptbr/guide/mutations.md index e2c9e01f4..8e012c3d3 100644 --- a/docs/ptbr/guide/mutations.md +++ b/docs/ptbr/guide/mutations.md @@ -1,7 +1,5 @@ # Mutações -The only way to actually change state in a Vuex store is by committing a mutation. Vuex mutations are very similar to events: each mutation has a string **type** and a **handler**. The handler function is where we perform actual state modifications, and it will receive the state as the first argument: - A única maneira de realmente mudar de estado em um _store_ Vuex é por confirmar (ou fazer _commit_ de) uma mutação. As mutações do Vuex são muito semelhantes aos eventos: cada mutação tem uma cadeia de caracteres **tipo** e um **manipulador**. A função do manipulador é onde realizamos modificações de estado reais e ele receberá o estado como o 1º argumento: ``` js @@ -80,8 +78,6 @@ mutations: { ### Mutações Seguem as Regras de Reatividade do Vue -Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue: - Como o estado de um _store_ Vuex é reativado pelo Vue, quando alteramos o estado, os componentes do Vue observando o estado serão atualizados automaticamente. Isso também significa que as mutações do Vuex estão sujeitas às mesmas ressalvas de reatividade ao trabalhar com o Vue simples: 1. Prefira inicializar o estado inicial do seu _store_ com todos os campos desejados antecipadamente. @@ -116,7 +112,7 @@ const store = new Vuex.Store({ // podemos usar o recurso de nome do dado computado do ES2015 // para usar uma constante como o nome da função [SOME_MUTATION] (state) { - // mutate state + // muda o estado } } }) From fc1c20ecabad698b8cd621e4b6f9e75e41667df2 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Jun 2018 20:37:37 -0300 Subject: [PATCH 08/21] made some fixes in translation --- docs/ptbr/api/README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/ptbr/api/README.md b/docs/ptbr/api/README.md index 192655acc..92b524b46 100644 --- a/docs/ptbr/api/README.md +++ b/docs/ptbr/api/README.md @@ -20,7 +20,7 @@ const store = new Vuex.Store({ ...options }) O objeto raiz de estado para o _store_ Vuex. [Detalhes](../guide/state.md) - Se você passar uma função que retorna um objeto, o objeto retornado é usado como o estado da raiz. Isso é útil quando você deseja reutilizar o objeto de estado, especialmente para reutilização de módulos. [Detalhes](../guide/modules.md#reutilização-do-módulo) + Se você passar uma função que retorna um objeto, o objeto retornado é usado como o estado da raiz. Isso é útil quando você deseja reutilizar o objeto de estado, especialmente para reutilização de módulos. [Detalhes](../guide/modules.md#reutilizacao-do-modulo) ### mutações @@ -200,7 +200,7 @@ const store = new Vuex.Store({ ...options }) - `registerModule(path: string | Array, module: Module, options?: Object)` - Registra um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-módulo-dinâmico) + Registra um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-modulo-dinamico) _options_ can have _preserveState: true_ que permite preservar o estado anterior. Útil com renderização do lado do servidor (_server-side-rendering_). @@ -208,7 +208,7 @@ const store = new Vuex.Store({ ...options }) - `unregisterModule(path: string | Array)` - Cancela o registro de um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-módulo-dinâmico) + Cancela o registro de um módulo dinâmico. [Detalhes](../guide/modules.md#registro-de-modulo-dinamico) ### hotUpdate @@ -224,7 +224,7 @@ const store = new Vuex.Store({ ...options }) Criar dados computados do componente que retornam a subárvore do _store_ Vuex. [Detalhes](../guide/state.md#o-auxiliar-mapstate) - O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace) O segundo objeto que compõem os argumentos pode ser uma função. `function(state: any)` @@ -234,15 +234,15 @@ const store = new Vuex.Store({ ...options }) Criar dados computados do componente que retornam o valor calculado de um _getter_. [Detalhes](../guide/getters.md#o-auxiliar-mapgetters) - O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace) ### mapActions - `mapActions(namespace?: string, map: Array | Object): Object` - Criar opções de métodos nos componentes que despacham uma ação. [Detalhes](../guide/actions.md#ações-de-despacho-em-componentes) + Criar opções de métodos nos componentes que despacham uma ação. [Detalhes](../guide/actions.md#acoes-de-despacho-em-componentes) - O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace) O segundo objeto que compõem os argumentos pode ser uma função. `function(dispatch: function, ...args: any[])` @@ -250,9 +250,9 @@ const store = new Vuex.Store({ ...options }) - `mapMutations(namespace?: string, map: Array | Object): Object` - Criar opções de métodos nos componentes que confirmam (ou fazem um _commit_ de) uma mutação. [Detalhes](../guide/mutations.md#fazendo-commit-de-mutações-em-componente) + Criar opções de métodos nos componentes que confirmam (ou fazem um _commit_ de) uma mutação. [Detalhes](../guide/mutations.md#confirmando-ou-fazendo-commits-de-mutacoes-em-componentes) - O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) + O 1º argumento pode ser opcionalmente uma _String_ com _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace)  O segundo objeto que compõem os argumentos pode ser uma função. `function(commit: function, ...args: any[])` @@ -260,4 +260,4 @@ const store = new Vuex.Store({ ...options }) - `createNamespacedHelpers(namespace: string): Object` - Cria um componente _namespaced_ dos métodos auxiliares. O objeto retornado possui _mapState_, _mapGetters_, _mapActions_ e _mapMutations_, que estão conectados com o dado _namespace_. [Detalhes](../guide/modules.md#usando-métodos-auxiliares-com-namespace) + Cria um componente _namespaced_ dos métodos auxiliares. O objeto retornado possui _mapState_, _mapGetters_, _mapActions_ e _mapMutations_, que estão conectados com o dado _namespace_. [Detalhes](../guide/modules.md#usando-metodos-auxiliares-com-namespace) From 0a2ff9e62fb7d209aa95495a2d51beeb5b5b581b Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Jun 2018 20:59:51 -0300 Subject: [PATCH 09/21] make some fixes and translates --- docs/.vuepress/config.js | 2 +- docs/ptbr/guide/README.md | 2 +- docs/ptbr/guide/strict.md | 12 ++++++------ docs/ptbr/guide/structure.md | 28 ++++++++++++++-------------- 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 1be5aa392..8c0a21102 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -263,7 +263,7 @@ module.exports = { '/ptbr/', '/ptbr/guide/', { - title: 'Core Concepts', + title: 'Conceitos Básicos', collapsable: false, children: [ '/ptbr/guide/state', diff --git a/docs/ptbr/guide/README.md b/docs/ptbr/guide/README.md index 496c665f7..fe5143f9f 100644 --- a/docs/ptbr/guide/README.md +++ b/docs/ptbr/guide/README.md @@ -1,4 +1,4 @@ -# Getting Started +# Começando At the center of every Vuex application is the **store**. A "store" is basically a container that holds your application **state**. There are two things that make a Vuex store different from a plain global object: diff --git a/docs/ptbr/guide/strict.md b/docs/ptbr/guide/strict.md index f75fb6dec..e07c3f653 100644 --- a/docs/ptbr/guide/strict.md +++ b/docs/ptbr/guide/strict.md @@ -1,6 +1,6 @@ -# Strict Mode +# Modo Estrito -To enable strict mode, simply pass in `strict: true` when creating a Vuex store: +Para habilitar o modo estrito, simplesmente passe _strict: true_ ao criar um _store_ Vuex: ``` js const store = new Vuex.Store({ @@ -9,13 +9,13 @@ const store = new Vuex.Store({ }) ``` -In strict mode, whenever Vuex state is mutated outside of mutation handlers, an error will be thrown. This ensures that all state mutations can be explicitly tracked by debugging tools. +Em modo estrito, sempre que o estado do Vuex é mudado fora dos manipuladores de mutação, um erro será lançado. Isso garante que todas as mutações do estado possam ser explicitamente rastreadas por ferramentas de depuração. -### Development vs. Production +### Desenvolvimento vs. Produção -**Do not enable strict mode when deploying for production!** Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost. +**Não habilite o modo estrito ao fazer um _deploy_ para a produção!** O modo estrito executa um observador profundo síncrono na árvore de estados para detectar mutações inapropriadas e pode ser bastante caro quando você faz grande quantidade de mutações no estado. Certifique-se de desligá-lo na produção para evitar o custo de desempenho. -Similar to plugins, we can let the build tools handle that: +Semelhante aos plugins, podemos deixar as ferramentas de compilação lidar com isso: ``` js const store = new Vuex.Store({ diff --git a/docs/ptbr/guide/structure.md b/docs/ptbr/guide/structure.md index 2ba11e37b..b5cac0b86 100644 --- a/docs/ptbr/guide/structure.md +++ b/docs/ptbr/guide/structure.md @@ -1,32 +1,32 @@ -# Application Structure +# Estrutura da Aplicação -Vuex doesn't really restrict how you structure your code. Rather, it enforces a set of high-level principles: +O Vuex não restringe realmente como você estrutura seu código. Em vez disso, ele impõe um conjunto de princípios de alto nível: -1. Application-level state is centralized in the store. +1. O estado do nível do aplicativo é centralizado no _store_. -2. The only way to mutate the state is by committing **mutations**, which are synchronous transactions. +2. A única maneira de mudar o estado é confirmando (ou fazendo _commit_ das) **mutações**, que são transações síncronas -3. Asynchronous logic should be encapsulated in, and can be composed with **actions**. +3. A lógica assíncrona deve ser encapsulada e pode ser composta com **ações**. -As long as you follow these rules, it's up to you how to structure your project. If your store file gets too big, simply start splitting the actions, mutations and getters into separate files. +Enquanto você seguir estas regras, depende de você como estruturar seu projeto. Se o arquivo do seu _store_ for muito grande, basta começar a dividir as ações, mutações e _getters_ em arquivos separados. -For any non-trivial app, we will likely need to leverage modules. Here's an example project structure: +Para qualquer aplicativo não trivial, provavelmente precisaremos aproveitar os módulos. Aqui está um exemplo de estrutura de projeto: ``` bash ├── index.html ├── main.js ├── api -│   └── ... # abstractions for making API requests +│   └── ... # abstrações para fazer requisições a API ├── components │   ├── App.vue │   └── ... └── store - ├── index.js # where we assemble modules and export the store - ├── actions.js # root actions - ├── mutations.js # root mutations + ├── index.js # onde montamos módulos e exportamos a store + ├── actions.js # ações raiz + ├── mutations.js # mutações raiz └── modules -    ├── cart.js # cart module -    └── products.js # products module +    ├── cart.js # módulo cart +    └── products.js # módulo products ``` -As a reference, check out the [Shopping Cart Example](https://github.com/vuejs/vuex/tree/dev/examples/shopping-cart). +Como referência, confira o [Exemplo do Carrinho de Compras](https://github.com/vuejs/vuex/tree/dev/examples/shopping-cart). From a6fb8e3f674160866801fc830817960ca69105f3 Mon Sep 17 00:00:00 2001 From: Ibrahim Brumate Date: Sat, 9 Jun 2018 22:40:51 -0300 Subject: [PATCH 10/21] Add more translations and fixes --- docs/ptbr/guide/README.md | 24 ++++++++-------- docs/ptbr/guide/modules.md | 2 +- docs/ptbr/guide/mutations.md | 4 +-- docs/ptbr/guide/plugins.md | 56 ++++++++++++++++++------------------ 4 files changed, 42 insertions(+), 44 deletions(-) diff --git a/docs/ptbr/guide/README.md b/docs/ptbr/guide/README.md index fe5143f9f..f9f56360a 100644 --- a/docs/ptbr/guide/README.md +++ b/docs/ptbr/guide/README.md @@ -1,19 +1,19 @@ # Começando -At the center of every Vuex application is the **store**. A "store" is basically a container that holds your application **state**. There are two things that make a Vuex store different from a plain global object: +No centro de cada aplicação Vuex existe o **_store_**. Um "_store_" é basicamente um recipiente que contém o **estado** da sua aplicação. Há duas coisas que tornam um _store_ Vuex diferente de um objeto global simples: -1. Vuex stores are reactive. When Vue components retrieve state from it, they will reactively and efficiently update if the store's state changes. +1. Os _stores_ Vuex são reativos. Quando os componentes do Vue obtêm o estado dele, eles atualizarão de forma reativa e eficiente se o estado do _store_ mudar. -2. You cannot directly mutate the store's state. The only way to change a store's state is by explicitly **committing mutations**. This ensures every state change leaves a track-able record, and enables tooling that helps us better understand our applications. +2. Você não pode alterar diretamente os estados do _store_. A única maneira de mudar o estado de um _store_ é explicitamente **confirmando (ou fazendo _commit_ de) mutações**. Isso garante que cada mudança de estado deixe um registro rastreável, e permite ferramentas que nos ajudem a entender melhor nossas aplicações. -### The Simplest Store +### O Store Mais Simples -> **NOTE:** We will be using ES2015 syntax for code examples for the rest of the docs. If you haven't picked it up, [you should](https://babeljs.io/docs/learn-es2015/)! +> **NOTA:** Vamos usar a sintaxe ES2015 para exemplos de código para o resto da documentação. Se você ainda não aprendeu como usá-la, [veja aqui](https://babeljs.io/docs/learn-es2015/)! -After [installing](../installation.md) Vuex, let's create a store. It is pretty straightforward - just provide an initial state object, and some mutations: +Após [instalar](../installation.md) o Vuex, vamos criar um _store_. É bem simples - basta fornecer um objeto de estado inicial, e algumas mutações: ``` js -// Make sure to call Vue.use(Vuex) first if using a module system +// Certifique-se de chamar Vue.use(Vuex) primeiro se estiver usando o sistema de módulos const store = new Vuex.Store({ state: { @@ -27,7 +27,7 @@ const store = new Vuex.Store({ }) ``` -Now, you can access the state object as `store.state`, and trigger a state change with the `store.commit` method: +Agora, você pode acessar o objeto de estado como _store.state_ e acionar uma mudança de estado com o método _store.commit_: ``` js store.commit('increment') @@ -35,10 +35,10 @@ store.commit('increment') console.log(store.state.count) // -> 1 ``` -Again, the reason we are committing a mutation instead of changing `store.state.count` directly, is because we want to explicitly track it. This simple convention makes your intention more explicit, so that you can reason about state changes in your app better when reading the code. In addition, this gives us the opportunity to implement tools that can log every mutation, take state snapshots, or even perform time travel debugging. +Novamente, a razão pela qual estamos confirmando (ou fazendo _commit_ de) uma mutação em vez de mudar _store.state.count_ diretamente, é porque queremos rastreá-la explicitamente. Esta convenção simples torna sua intenção mais explícita, de modo que você possa ter melhores argumetos sobre as mudanças de estado em seu aplicativo ao ler o código. Além disso, isso nos dá a oportunidade de implementar ferramentas que podem registrar cada mutação, capturar momentos do estado ou mesmo realizar depuração viajando pelo histórico de estado (_time travel_). -Using store state in a component simply involves returning the state within a computed property, because the store state is reactive. Triggering changes simply means committing mutations in component methods. +Usar o estado do _store_ em um componente simplesmente envolve o retorno do estado dentro de um dado computado, porque o estado do _store_ é reativo. Acionar alterações simplesmente significa confirmar (ou fazer _commit_ de) mutações nos métodos dos componentes. -Here's an example of the [most basic Vuex counter app](https://jsfiddle.net/n9jmu5v7/1269/). +Aqui está um exemplo do [aplicativo de contador do Vuex mais básico](https://jsfiddle.net/n9jmu5v7/1269/). -Next, we will discuss each core concept in much finer details, starting with [State](state.md). +Em seguida, discutiremos cada conceito chave em mais detalhes, começando com [Estado](state.md). diff --git a/docs/ptbr/guide/modules.md b/docs/ptbr/guide/modules.md index b25d6eb9e..0cf2ff6aa 100644 --- a/docs/ptbr/guide/modules.md +++ b/docs/ptbr/guide/modules.md @@ -81,7 +81,7 @@ const moduleA = { ### Namespacing -Por padrão, ações, mutações e _getters_ dentro dos módulos ainda são registrados sob o **namespace global** - isso permite que vários módulos reajam ao mesmo tipo de ação/mutação. +Por padrão, ações, mutações e _getters_ dentro dos módulos ainda são registrados sob o **_namespace_ global** - isso permite que vários módulos reajam ao mesmo tipo de ação/mutação. Se você quer que seus módulos sejam mais independentes ou reutilizáveis, você pode marcá-los como _namespaced_ com _namespaced: true_. Quando o módulo é registrado, todos os _getters_, ações e mutações serão automaticamente _namespaced_ com base no caminho no qual o módulo está registrado. Por exemplo: diff --git a/docs/ptbr/guide/mutations.md b/docs/ptbr/guide/mutations.md index 8e012c3d3..f2a5a5805 100644 --- a/docs/ptbr/guide/mutations.md +++ b/docs/ptbr/guide/mutations.md @@ -24,7 +24,7 @@ store.commit('increment') ### Commit com Payload -Você pode passar um argumento adicional para o _store.commit_, que é chamado de **payload** para a mutação: +Você pode passar um argumento adicional para o _store.commit_, que é chamado de **_payload_** para a mutação: ``` js // ... @@ -122,8 +122,6 @@ Se usar constantes é em grande parte uma preferência - pode ser útil em grand ### Mutações Devem Ser Síncronas -One important rule to remember is that **mutation handler functions must be synchronous**. Why? Consider the following example: - Uma regra importante a lembrar é que **as funções do manipulador de mutação devem ser síncronas**. Por quê? Considere o seguinte exemplo: ``` js diff --git a/docs/ptbr/guide/plugins.md b/docs/ptbr/guide/plugins.md index afccfe31c..2e670a3ca 100644 --- a/docs/ptbr/guide/plugins.md +++ b/docs/ptbr/guide/plugins.md @@ -1,18 +1,18 @@ # Plugins -Vuex stores accept the `plugins` option that exposes hooks for each mutation. A Vuex plugin is simply a function that receives the store as the only argument: +Os _stores_ do Vuex aceitam a opção _plugins_ que expõe _hooks_ para cada mutação. Um _plugin_ Vuex é simplesmente uma função que recebe um _store_ como seu único argumento: ``` js const myPlugin = store => { - // called when the store is initialized + // chamado quando o store é inicializado store.subscribe((mutation, state) => { - // called after every mutation. - // The mutation comes in the format of `{ type, payload }`. + // chamada após cada mutação. + // A mutação vem no formato de `{ type, payload }`. }) } ``` -And can be used like this: +E pode ser usada assim: ``` js const store = new Vuex.Store({ @@ -21,11 +21,11 @@ const store = new Vuex.Store({ }) ``` -### Committing Mutations Inside Plugins +### Confirmando (ou fazendo _commit_ de) Mutações Dentro de Plugins -Plugins are not allowed to directly mutate state - similar to your components, they can only trigger changes by committing mutations. +_Plugins_ não tem permissão para alterar o estado diretamente - similar aos componentes, eles podem apenas acionar mudanças fazendo o _commit_ de mutações. -By committing mutations, a plugin can be used to sync a data source to the store. For example, to sync a websocket data source to the store (this is just a contrived example, in reality the `createPlugin` function can take some additional options for more complex tasks): +Por fazer _commit_ de mutações, um _plugin_ pode ser usado para sincronizar uma fonte de dados ao _store_. Por exemplo, para sincronizar uma fonte de dados _websocket_ ao _store_ (isso é só um exemplo inventado, na realidade a função _createPlugin_ pode receber parâmetros adicionais para tarefas mais complexas): ``` js export default function createWebSocketPlugin (socket) { @@ -52,9 +52,9 @@ const store = new Vuex.Store({ }) ``` -### Taking State Snapshots +### Capturando os Momentos do Estado -Sometimes a plugin may want to receive "snapshots" of the state, and also compare the post-mutation state with pre-mutation state. To achieve that, you will need to perform a deep-copy on the state object: +Às vezes, um _plugin_ pode querer receber "momentos" do estado, e também comparar o estado pós-mutação com o estado de pré-mutação. Para conseguir isso, você precisará realizar uma cópia-profunda do objeto de estado: ``` js const myPluginWithSnapshot = store => { @@ -62,15 +62,15 @@ const myPluginWithSnapshot = store => { store.subscribe((mutation, state) => { let nextState = _.cloneDeep(state) - // compare `prevState` and `nextState`... + // compara `prevState` e `nextState`... - // save state for next mutation + // salva o estado para a próxima mutação prevState = nextState }) } ``` -**Plugins that take state snapshots should be used only during development.** When using webpack or Browserify, we can let our build tools handle that for us: +**_Plugins_ que capturam momentos do estado devem ser usados apenas durante o desenvolvimento.** Quando usamos _webpack_ ou _Browserify_, podemos construir nossas próprias ferramentas _build_ que lidam com isso para nós: ``` js const store = new Vuex.Store({ @@ -81,13 +81,13 @@ const store = new Vuex.Store({ }) ``` -The plugin will be used by default. For production, you will need [DefinePlugin](https://webpack.js.org/plugins/define-plugin/) for webpack or [envify](https://github.com/hughsk/envify) for Browserify to convert the value of `process.env.NODE_ENV !== 'production'` to `false` for the final build. +O _plugin_ vai ser usado por padrão. Para produção, você vai precisar do [DefinePlugin](https://webpack.github.io/docs/list-of-plugins.html#defineplugin) para webpack ou [envify](https://github.com/hughsk/envify) para Browserify para converter o valor do `process.env.NODE_ENV !== 'production'` para _false_ no _build_ final. -### Built-in Logger Plugin +### Plugin de Log Integrado -> If you are using [vue-devtools](https://github.com/vuejs/vue-devtools) you probably don't need this. +> Se você está usando [vue-devtools](https://github.com/vuejs/vue-devtools) provavelmente não precisará disso. -Vuex comes with a logger plugin for common debugging usage: +Vuex vem com um _plugin_ de _log_ para casos comuns de depuração: ``` js import createLogger from 'vuex/dist/logger' @@ -97,30 +97,30 @@ const store = new Vuex.Store({ }) ``` -The `createLogger` function takes a few options: +A função _createLogger_ tem algumas opções: ``` js const logger = createLogger({ - collapsed: false, // auto-expand logged mutations + collapsed: false, // expande automaticamente mutações registradas no log filter (mutation, stateBefore, stateAfter) { - // returns `true` if a mutation should be logged - // `mutation` is a `{ type, payload }` + // retorna `true` se uma mutação deve ser registrada no log + // `mutation` é um `{ type, payload }` return mutation.type !== "aBlacklistedMutation" }, transformer (state) { - // transform the state before logging it. - // for example return only a specific sub-tree + // transforma o estado antes de regitrá-lo no log. + // por exemplo, retorna apenas uma sub-árvore específica return state.subTree }, mutationTransformer (mutation) { - // mutations are logged in the format of `{ type, payload }` - // we can format it any way we want. + // mutações são registradas no log no formato de `{ type, payload }` + // mas podemos formatá-las como quisermos. return mutation.type }, - logger: console, // implementation of the `console` API, default `console` + logger: console, // implementação da API `console`, default `console` }) ``` -The logger file can also be included directly via a `