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;
}
});
非常感謝@Bert。的確,我隱約知道'let'和'const'是New Thing,但還沒有研究過它們,因爲'var'對我來說是「工作的」。 – wwninja
@wwninja很多情況下並不重要;這恰好是它所在的位置:)在'let'可用之前,修復涉及更多(它涉及在循環的每次迭代中創建閉包)。 – Bert