天天看點

深度監視(watch)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <!-- 
      1.深度監視:
        1.vue中的watch預設不檢測對象内部值的改變
        2.配置deep:true可以監測對象内部值的改變
       備注:
        1.vue自身可以監測對象内部值的改變,但vue提供的watch預設是不可以
        2.使用watch時根據資料的具體結構,決定是否采用深度監視
     -->
  </head>
  <body>
    <script src="./vue.js"></script>
    <div id="root">
      <h1>1的值:{{numbers.a}}</h1>
      <button @click='numbers.a++'>add</button>
      <h1>b的值:{{numbers.b}}</h1>
      <button @click='numbers.b++'>add</button>
      <br>    </div>

    <script>
      Vue.config.productionTip = false;
    const vm = new Vue({
        el : '#root',
        data:{
          inHot:true,
          numbers:{
            a:1,
            b:1
          }
        },
          //監視多級結果裡某一個屬性的變化
          watch:{
            'numbers.a':{
              handler() {
                  console.log('111')
              }
            },
          //監視多級結果所有屬性的變化
            numbers:{
              //true開啟所有屬性的變化
             deep:true,
              handler() {
                console.log('number改變')
              }
            }
          },
      })

    </script>

  </body>
</html>