vue.js入門_12_監視プロパティ(deepオプション)

by s9iwork

HTML

<div id="app">
  <div  class="block">
    <div>
      <h2>deep</h2>
      <h3>color</h3>
      <p>{{ color1 }}</p>
      <h3>color2</h3>
      <p>{{ color2.name }}</p>
      <h3>colors</h3>
      <p>{{ colors[0].name }}</p>
    </div>
    <div>
      <h2>immediate</h2>
      <h3>color3</h3>
      <p>{{ color3 }}</p>
    </div>
  </div>
  <input type="text" v-model:value="newColor">
  <button v-on:click="update">update</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

CSS

h2 {
  font-size: 1.2rem;
}

h2::before {
  content: "■";
}

.block {
  display: flex;
}

.block > div {
  margin-right: 50px;
}

JavaScript

new Vue({
  el: '#app',
  data: {
    color1: 'red',
    color2: {
      name: 'red'
    },
    colors: [{
      name: 'red'
    }],
    color3: 'red',
    newColor: '',
  },
  watch: {
    color1: {
      handler: function(newValue, oldValue) {
        console.log('color1 update')
      },
    },
    color2: {
      handler: function(newValue, oldValue) {
        console.log('color2 update')
      },
      deep: true
    },
    colors: {
      handler: function(newValue, oldValue) {
        console.log('colors update')
      },
      deep: true
    },
    color3: {
      handler: function(newValue, oldValue) {
        console.log('color3 update')
      },
      immediate: true
    },
  },
  methods: {
    update: function() {
      this.color1 = this.newColor
      // ■deep
      // オブジェクト
      // case1:deep=falseでも検知される
//      this.color2 = {
//        name: this.newColor
//      }
      // case2:deep=falseだと検知されない 
      this.color2.name = this.newColor

      // 配列
      // case1:deep=falseでも検知される
//      this.colors = [{
//        name: this.newColor
//      }]
      // case2:deep=falseだと検知されない
      this.colors[0].name = this.newColor
      // case3:deep=falseだと検知されない
//      this.colors[0] = {
//        name: this.newColor
//      }

      // ■immediate
      this.color3 = this.newColor
    },
  }
})