0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue+Typescript 変更を追跡する(ちゃんとWatchする)ようなオブジェクトの扱い方

Posted at

前回、Vue + Typescriptで配列の変更を検知しない問題について書きました。

今回はObjectの扱いについてですが、
Objectは配列と比べるとかなり気楽に扱えます。

というのも、Typescriptだと未定義・未initializeのオブジェクトを使うことはほぼないので、
公式に記載されているような以下のアウトな形式

Vue はプロパティの追加または削除を検出できません。


const vm = { a: 1 }
// `vm.a` は今リアクティブです

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

ですが、これもVue + Typescriptではおそらく以下のように書く必要がありますので

// 型を定義してあげる必要がある。ここで上の例のようにbが抜けていると、そもそもコンパイルが通らない
interface Vm {
  a: number;
  b: number;
}

@Component({
  components: {
  }
})

export default class Qiita extends Vue {
  // 初期化してあげないといけない(これはStateとかに持たせたほうが管理が楽です)
  private vm: Vm = {
    a: 0,
    b: 0
  }

これであれば、変更は正常に検知されます。
Typescriptの強みですね。

もちろん、状況によってはany型などでオブジェクトを定義しなければならない局面もあるでしょう。
その場合は、公式にあるようにObject.assignを使えば解決することができます。

this.vm = Object.assign({}, this.vm, { a: 1, b: 2 })

基本問題になるのは前回解説した配列で、
配列が空でv-forを回していたりすると、検知できない!といったケースが多いです。

オブジェクトに配列があるデータなどの扱いは注意しましょう!というお話しでした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?