14
14

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 5 years have passed since last update.

Vue.jsでオブジェクトにキーを追加/deleteしてもDOMに反映されない

Last updated at Posted at 2017-12-13

オブジェクトに変更を加えてもDOMに反映されない

Vue.jsではdataの変更を検知して自動的にDOMに反映されますが、オブジェクトの場合事情がことなります。

<!- HTML ->
<div id="app">
  <div v-for='v, k in obj'>
    <p>{{ k }} is {{ v }}</p>
  </div>
  <button v-on:click='appendKey'>append</button>
  <button v-on:click='deleteKey'>delete</button>
</div>
// javascript
new Vue({
  el: '#app',
  data: {
    obj: {
      'hoge': 1
    }
  },
  methods: {
    appendKey: function(){
      this.obj.fuga = 2;
    },
    deleteKey: function(){
      delete this.obj.hoge;
    }
  }
})

ボタンを押してもDOMに反映されない

まんまと落とし穴に落ちる

よくある初心者の落とし穴
https://jp.vuejs.org/2016/02/06/common-gotchas/

リアクティブの探求
https://jp.vuejs.org/v2/guide/reactivity.html#変更検出の注意事項

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

こうやる

$set or $deleteを使う

// javascript
new Vue({
  el: '#app',
  data: {
    obj: {
      'hoge': 1
    }
  },
  methods: {
    appendKey: function(){
      this.$set(this.obj, 'fuga', 2);
    },
    deleteKey: function(){
      this.$delete(this.obj, 'fuga');
    }
  }
})
14
14
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
14
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?