我在网上看到了一个代码。有一个$this=this。在我看来,这一行将外部函数的“this”分配给一个变量。它使得外部的“this”能够在内部函数中使用。但如果我直接在内部函数中使用它,没有什么区别。我错过了什么?
<div id="app">
<ul>
<li v-for="(item, index) in goods" :key="index">
<span>name:{{item.name}}</span>
<span>price:{{item.price.toFixed(2)}}</span>
<span>number:{{item.num}}</span>
<br>
<input type="button" value="+" @click="item.num += 1">
<input type="button" value="-" @click="item.num -= 1">
</li>
</ul>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
goods: []
},
created () {
let $this = this;
setTimeout(() => {
$this.goods = [
{
name: 'android',
price: 12.99
},
{
name: 'IOS',
price: 13.99
},
{
name: 'javaScript',
price: 14.99
}
];
$this.goods.forEach(item => {
item.num = 1;
});
}, 3000);
}
});
</script>
最佳答案
你没有错过任何东西。
由于代码使用箭头函数来捕获 this
的当前值,因此使用另一个变量 ($this
) 是没有意义的。
关于javascript - vue : $this=this Why does use outter 'this' to inner function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55899734/