2017-06-17 70 views
2

試驗在Vue.js中動態添加監視器。所需/實際結果之間的斷開顯示在下面的註釋部分。偶爾/業餘編碼員在這裏;我懷疑Vue的問題較少,對JavaScript基礎知識的理解更多。提前致謝!在for循環中設置vue.js監視器

new Vue({ 
    el: '#app', 
    data: { 
     a: 1, 
     b: 2, 
     c: 3 
    }, 
    methods: { 
     setUpWatchers(array) { 
      for (var i in array) { 
       var key = array[i]; 

       this.$watch(key, function(newValue) { 
        console.log(key + ': ' + newValue); 

        //desired output is: 
        // a: 4 
        // b: 5 
        // c: 6 

        //actual output is: 
        // c: 4 
        // c: 5 
        // c: 6 

       }); 
      } 
     } 
    }, 
    created() { 
     this.setUpWatchers(['a', 'b', 'c']); 

     this.a = 4; 
     this.b = 5; 
     this.c = 6; 
    } 
}); 

回答

0

你是對的,這是一個經典的JavaScript「gotcha」。

var聲明的變量具有函數範圍。在循環中聲明的函數中使用var所有(您聲明3; $ watch的處理程序)使用same變量,該變量在循環完成後指向c

一個快速解決方法是用let聲明你的變量。 let具有塊範圍,因此在循環中聲明的每個函數都只能訪問該函數創建時存在的變量的副本。

這是一個工作示例。

new Vue({ 
 
    el: '#app', 
 
    data: { 
 
     a: 1, 
 
     b: 2, 
 
     c: 3 
 
    }, 
 
    methods: { 
 
     setUpWatchers(array) { 
 
      for (let i in array) { 
 
       let key = array[i]; 
 

 
       this.$watch(key, function(newValue) { 
 
        console.log(key + ': ' + newValue); 
 
       }); 
 
      } 
 
     } 
 
    }, 
 
    created() { 
 
     this.setUpWatchers(['a', 'b', 'c']); 
 

 
     this.a = 4; 
 
     this.b = 5; 
 
     this.c = 6; 
 
    } 
 
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script> 
 
<div id="app"></div>

理想的情況下,這幾天,你應該使用letconst和幾乎從來沒有var。有許多資源可用於描述差異。

+0

非常感謝@Bert。的確,我隱約知道'let'和'const'是New Thing,但還沒有研究過它們,因爲'var'對我來說是「工作的」。 – wwninja

+0

@wwninja很多情況下並不重要;這恰好是它所在的位置:)在'let'可用之前,修復涉及更多(它涉及在循環的每次迭代中創建閉包)。 – Bert