Skip to content

Render Mechanisms > Change Detection Caveats in Vue 2 の翻訳 #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 33 additions & 33 deletions src/guide/change-detection.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,64 @@
# Change Detection Caveats in Vue 2
# Vue 2 での変更検出の注意事項

> This page applies only to Vue 2.x and below, and assumes you've already read the [Reactivity Section](reactivity.md). Please read that section first.
> このページは Vue 2.x 以下にのみ適用され、すでに[リアクティブの探求](reactivity.md)を読んでいることが前提です。最初にそのセクションを読んでください。

Due to limitations in JavaScript, there are types of changes that Vue **cannot detect**. However, there are ways to circumvent them to preserve reactivity.
JavaScript の制限のため、Vue は、**検出することができない**変更のタイプがあります。しかし、それらを回避しリアクティビティを維持する方法はあります。

### For Objects
### オブジェクトに関して

Vue cannot detect property addition or deletion. Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the `data` object in order for Vue to convert it and make it reactive. For example:
Vue はプロパティの追加または削除を検出できません。Vue はインスタンスの初期化中に getter/setter の変換を行うため、全てのプロパティは Vue が変換してリアクティブにできるように `data` オブジェクトに存在しなければなりません。例えば:

```js
var vm = new Vue({
data: {
a: 1
}
})
// `vm.a` is now reactive
// `vm.a` は今リアクティブです

vm.b = 2
// `vm.b` is NOT reactive
// `vm.b` はリアクティブでは"ありません"
```

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it's possible to add reactive properties to a nested object using the `Vue.set(object, propertyName, value)` method:
Vue では、すでに作成されたインスタンスに対して新しいルートレベルのリアクティブなプロパティを動的に追加することはできません。しかしながら、`Vue.set(object, propertyName, value)` メソッドを使ってネストしたオブジェクトにリアクティブなプロパティを追加することができます:

```js
Vue.set(vm.someObject, 'b', 2)
```

You can also use the `vm.$set` instance method, which is an alias to the global `Vue.set`:
`vm.$set` インスタンスメソッドを使用することもできます。これはグローバルの `Vue.set` のエイリアスです:

```js
this.$set(this.someObject, 'b', 2)
```

Sometimes you may want to assign a number of properties to an existing object, for example using `Object.assign()` or `_.extend()`. However, new properties added to the object will not trigger changes. In such cases, create a fresh object with properties from both the original object and the mixin object:
既存のオブジェクトに複数のプロパティを割り当てたいということがあるかもしれません。例えば、`Object.assign()` `_.extend()` を使って。しかし、オブジェクトに追加された新しいプロパティは変更をトリガしません。このような場合は、元のオブジェクトとミックスインオブジェクトの両方のプロパティを持つ新たなオブジェクトを作成してください:

```js
// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
// `Object.assign(this.someObject, { a: 1, b: 2 })` の代わり
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
```

### For Arrays
### 配列に関して

Vue cannot detect the following changes to an array:
Vue は、配列における次の変更は検知できません:

1. When you directly set an item with the index, e.g. `vm.items[indexOfItem] = newValue`
2. When you modify the length of the array, e.g. `vm.items.length = newLength`
1. インデックスと一緒にアイテムを直接セットする場合、例えば `vm.items[indexOfItem] = newValue`
2. 配列の長さを変更する場合、例えば `vm.items.length = newLength`

For example:
:

```js
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // is NOT reactive
vm.items.length = 2 // is NOT reactive
vm.items[1] = 'x' // リアクティブでは"ありません"
vm.items.length = 2 // リアクティブでは"ありません"
```

To overcome caveat 1, both of the following will accomplish the same as `vm.items[indexOfItem] = newValue`, but will also trigger state updates in the reactivity system:
注意事項 1 を克服するに、次のいずれも `vm.items[indexOfItem] = newValue` と同じように機能しますが、リアクティビティシステムで状態の更新をトリガします:

```js
// Vue.set
Expand All @@ -70,43 +70,43 @@ Vue.set(vm.items, indexOfItem, newValue)
vm.items.splice(indexOfItem, 1, newValue)
```

You can also use the [`vm.$set`](https://vuejs.org/v2/api/#vm-set) instance method, which is an alias for the global `Vue.set`:
また、[`vm.$set`](https://vuejs.org/v2/api/#vm-set) インスタンスメソッドを使うこともできます。これはグローバルな `Vue.set` のエイリアスです:

```js
vm.$set(vm.items, indexOfItem, newValue)
```

To deal with caveat 2, you can use `splice`:
注意事項 2 に対応するには、`splice` を使うことができます:

```js
vm.items.splice(newLength)
```

## Declaring Reactive Properties
## リアクティブプロパティの宣言

Since Vue doesn't allow dynamically adding root-level reactive properties, you have to initialize component instances by declaring all root-level reactive data properties upfront, even with an empty value:
Vue では新しいルートレベルのリアクティブなプロパティを動的に追加することはできないため、インスタンスの初期化時に前もって全てのルートレベルのリアクティブな data プロパティを宣言する必要があります。空の値でもかまいません:

```js
var vm = new Vue({
data: {
// declare message with an empty value
// 空の値として message を宣言する
message: ''
},
template: '<div>{{ message }}</div>'
})
// set `message` later
// 後で`message` を追加する
vm.message = 'Hello!'
```

If you don't declare `message` in the data option, Vue will warn you that the render function is trying to access a property that doesn't exist.
data オプションで `message` を宣言していないと、Vue render 関数が存在しないプロパティにアクセスしようとしていることを警告します。

There are technical reasons behind this restriction - it eliminates a class of edge cases in the dependency tracking system, and also makes component instances play nicer with type checking systems. But there is also an important consideration in terms of code maintainability: the `data` object is like the schema for your component's state. Declaring all reactive properties upfront makes the component code easier to understand when revisited later or read by another developer.
この制限の背後には技術的な理由があります。それは依存性追跡システムにおける一連のエッジケースを排除し、また Vue インスタンスと型チェックシステムとの親和性を高めます。しかしコードの保守性の観点からも重要な事項があります: `data` オブジェクトはコンポーネントの状態のスキーマのようなものです。前もって全てのリアクティブなプロパティを宣言しておくと、後から見直したり別の開発者が読んだりしたときにコンポーネントのコードを簡単に理解することができます。

## Async Update Queue
## 非同期更新キュー

In case you haven't noticed yet, Vue performs DOM updates **asynchronously**. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations. Then, in the next event loop "tick", Vue flushes the queue and performs the actual (already de-duped) work. Internally Vue tries native `Promise.then`, `MutationObserver`, and `setImmediate` for the asynchronous queuing and falls back to `setTimeout(fn, 0)`.
おそらく既にお気づきでしょうが、Vue は **非同期** に DOM 更新を実行します。データ変更が検出されると、Vue はキューをオープンし、同じイベントループで起こる全てのデータ変更をバッファリングします。同じウォッチャが複数回トリガされる場合、キューには一度だけ入ります。この重複除外バッファリングは不要な計算や DOM 操作を回避する上で重要です。そして、次のイベントループ "tick" で、Vue はキューをフラッシュし、実際の(すでに重複が除外された)作業を実行します。内部的には、Vue は非同期キューイング向けにネイティブな `Promise.then``MutationObserver``setImmediate` が利用可能ならそれを使い、`setTimeout(fn, 0)` にフォールバックします。

For example, when you set `vm.someData = 'new value'`, the component will not re-render immediately. It will update in the next "tick", when the queue is flushed. Most of the time we don't need to care about this, but it can be tricky when you want to do something that depends on the post-update DOM state. Although Vue.js generally encourages developers to think in a "data-driven" fashion and avoid touching the DOM directly, sometimes it might be necessary to get your hands dirty. In order to wait until Vue.js has finished updating the DOM after a data change, you can use `Vue.nextTick(callback)` immediately after the data is changed. The callback will be called after the DOM has been updated. For example:
例として、`vm.someData = 'new value'` をセットした時、そのコンポーネントはすぐには再描画しません。 次の "tick" でキューがフラッシュされる時に更新します。ほとんどの場合、私達はこれについて気にする必要はありませんが、更新した DOM の状態に依存する何かをしたい時は注意が必要です。Vue.js は一般的に"データ駆動"的な流儀で考え、DOM を直接触るのを避けることを開発者に奨励しますが、時にはその手を汚す必要があるかもしれません。データの変更後に Vue.js DOM 更新の完了を待つには、データが変更された直後に `Vue.nextTick(callback)` を使用することができます。そのコールバックは DOM が更新された後に呼ばれます。例えば:

```html
<div id="example">{{ message }}</div>
Expand All @@ -119,14 +119,14 @@ var vm = new Vue({
message: '123'
}
})
vm.message = 'new message' // change data
vm.message = 'new message' // データを変更する
vm.$el.textContent === 'new message' // false
Vue.nextTick(function() {
vm.$el.textContent === 'new message' // true
})
```

There is also the `vm.$nextTick()` instance method, which is especially handy inside components, because it doesn't need global `Vue` and its callback's `this` context will be automatically bound to the current component instance:
`vm.$nextTick()` というインスタンスメソッドもあります。これは、グローバルな Vue を必要とせず、コールバックの `this` コンテキストが自動的に現在の Vue インスタンスに束縛されるため、コンポーネント内で特に役立ちます:

```js
Vue.component('example', {
Expand All @@ -148,7 +148,7 @@ Vue.component('example', {
})
```

Since `$nextTick()` returns a promise, you can achieve the same as the above using the new [ES2017 async/await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) syntax:
`$nextTick()` は Promise を返却するため、新しい [ES2017 async/await](https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function) 構文を用いて、同じことができます:

```js
methods: {
Expand Down