javascript - vue : $this=this Why does use outter 'this' to inner function?

标签 javascript vue.js

我在网上看到了一个代码。有一个$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/

相关文章:

javascript - 我正在尝试使用按钮随意移动 CSS 元素,我尝试使用 offset 并且 onlick 不起作用

javascript - 有没有办法访问页面上多个相同组件的属性?

vue.js - vue 语言服务器 : Elements in iteration expect to have 'v-bind:key' directives

JavaScript:替换十六进制字符

javascript - 无限滚动或大量 dom 元素的性能?

javascript - 字符串连接在 JS 范围内不起作用

vue.js - 文件名与仅在套管中已包含的文件名不同。Vetur(1149)

css - Bootstrap-vue:当您将鼠标悬停在工具提示本身(而不是按钮)上时如何隐藏 v-b-tooltip

javascript - 未捕获的类型错误 : not a function when calling method from data in Vue

javascript - 删除 Discover Meteor Book 中的 URL 字段