What is the reason behind utilizing the external 'this' within the inner function in Vue: $this=this?

Recently, I came across some code online that included a line $this=this. My initial interpretation was that this line assigns the 'this' of the outer function to a variable, allowing it to be used in the inner function as well. However, upon further examination, I realized that using this directly in the inner function yielded the same result. Am I overlooking something important here?

<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>

Answer №1

No need to worry, you didn't overlook anything.

The code employs an arrow function to retain the current value of this, rendering the utilization of another variable unnecessary ($this).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a list of JSON data in HTML using Angular.js is a breeze

I am attempting to create an HTML list displaying the id fields of game objects from a json file. However, it is not appearing in my user interface. I am unsure why it is not rendering properly. ---core.js--- var gameapp = angular.module('gameapp&ap ...

Leverage the power of i18n in both vuejs components and blade.php templates

Is it possible to use i18n in both blade.php and Vue.js views? I have set up a json file for i18n as shown below: export default { "en": { "menu": { "home":"Home", "example":"Example" } } } Using this i18 ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Obtain the key's value from a JSON object that is nested within another

Managing a complex data structure is crucial in programming. How can I efficiently retrieve specific values using known keys from this nested data? Take, for instance: var data = { code: 42, items: [{ id: 1, category: [{ ...

How can you make a Tempory Drawer wider in Material Components Web?

Increasing the Width of a Temporary Drawer in Material-components-web Greetings! I am currently facing an issue with Material-components-web In the provided demo here, I would like to extend the width of the Temporary drawer to accommodate additional co ...

"Error" - The web service call cannot be processed as the parameter value for 'name' is missing

When using Ajax to call a server-side method, I encountered an error message: {"Message":"Invalid web service call, missing value for parameter: \u0027name\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(O ...

The jQuery UI Sortable functions are being triggered at lightning speed

I am currently working on a project where users can create a seating chart, add rows and tables, and move the tables between different rows. The functionality for adding rows and moving tables already exists in the code. However, I am facing an issue where ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Switching the cursor to the following input after a paste event using JQuery

I am currently working on an HTML form that consists of multiple input boxes. I'm looking to focus on the next input box after pasting content into one of them. Below is the code snippet I have been using: $("input").bind('paste', function( ...

When the user clicks, I plan to switch the audio source

I am looking to update the audio source when a button is clicked, but I am having trouble getting it to work. image description data() { return { audioSrc: '' } }, methods: { setActiveAudio(item) { this.$refs.audioE ...

In my experience, the GET request is functioning properly within Postman, but for some reason the POST method continues to send requests repeatedly

ISSUE: I am encountering a problem while making a POST request in Postman. The application keeps sending requests without receiving any response. I have read through various solutions for Postman hanging during a POST request, but none of them seem to sol ...

The CORS policy is blocking Django Vue Js Axios from functioning as expected

Utilizing Django as the backend and Vue as the frontend, I am using axios to send a request from Vue to Django. I have encountered CORS policy blocking even after trying various solutions. I have spent approximately 4 hours Googling and still facing this ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

Peer-to-peer Ajax image sharing

Currently, I'm utilizing Ajax to fetch images from a remote server. Initially, I attempted this by directly using the URL of the remote server - resulting in the returned image being a string (given that's how Ajax communicates). To rectify this, ...

The requested 'Pagination' component (imported as 'Pagination') could not be located within the 'swiper' library. Possible exports include Swiper and default

I was trying to implement pagination using swiper. I included the Pagination module with this import statement: import { Pagination } from "swiper"; Here's my configuration: The error that I encountered is : I have noticed that it w ...

Each time the Jquery callback function is executed, it will return just once

Whenever a user clicks on the "customize" link, I trigger a function to open a dialog box. This function includes a callback that returns an object when the user clicks "save". The problem is, each time the user clicks "customize", the object gets returned ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

Tips for combining values from two inputs to an angular ng-model in AngularJS

I am working with an angular application and I am trying to figure out how to combine values from multiple inputs into one ng-model. Here is an example of my current input: <input type="text" class="form-control input-md" name="type" ng-model="flat.f ...