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

Vue3 - Utilizing a method to dynamically alter an input property

Currently, I am in the process of developing a Vue application that incorporates a map feature. The main functionality involves determining whether a given position on the map is over water or land. If the position is over water, I want to iterate through ...

Ways to verify if one div in jQuery contains identical text to another div

I need help with a jQuery script to remove duplicate text in div elements Here's the requirement: If div1 contains the text "hi" and div2 also contains "hi", then div2 should be removed Below is my current code snippet: <script src="https:/ ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

Guide for using express.js

Similar to how you can use to view the source code of all classes in Java, is there a resource available to view the source code of the express module? ...

AngularJS login form with JSON data

I am currently learning Angular and focusing on the login form implementation. The specific model I am working with can be found in this PLNKR. There are two challenges that I am struggling to resolve. Issue 1: I'm trying to figure out how to tur ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Discovering Vue.js Event Handling: How to Identify If a Key Is Pressed While the Mouse Hovers over a Specific Element?

I am currently developing a Vue.js 3 multi-item selection feature. Each item is displayed as a <div> element with a checkbox inside. One functionality I am trying to add requires detecting when the Shift key is held down while the mouse hovers over ...

The dynamic loading of videos through the YouTube API

-Need to load multiple videos onto a page, keeping it simple -Each video has an ID stored in the database accessed via $slide['message'] -Currently only loading one video successfully, others show up as blank -Code is within a loop, attempt ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

Is it possible to repeatedly activate a function using onmousedown just like with onkeydown?

My goal is to have the onmousedown event trigger repeatedly when the left mouse button is held down, instead of just once upon clicking. Currently, it only fires a single time. wHandle.onmousedown = function (event) { console.log('mouse b ...

Troubleshooting a labeling problem in a donut chart with Chart.js

$(document).ready(function(){ function call() { $.ajax({ url: "chartjs/tempdata.php", method:"GET", cache: false, success: function(data) { console.log(data); var difference=[]; var percentage=[]; var finaldata=[]; for(var i in data) { //time.push( ...

VueJS encountered an error during rendering: TypeError - Unable to access the 'PRICE' property of undefined

My goal is to calculate the total bill, which is the sum of all product prices multiplied by their respective usage values, using the customerProduct data object. Once calculated, I want to display the bill amount. To achieve this, I have a computed method ...

Utilizing AngularJS to effectively group and filter using Ng-repeat

I am working with an array retrieved from an Azure server Log (clicks array) that I need to sort in a specific way. Below is the request: $http({ method: 'Get', headers: { 'Host': 'api.applicationinsights.io&apo ...

Map Row is unreturned

I am having trouble when attempting to map a JSON response from a MySQL query as I am receiving no response: data: NULL This is the code in question: const audience = rows.map((row) => { db.query(CountAudiences, [row.campaign], function(err, count ...

Ways to customize the border color on a Card component using React Material UI

Is there a way to change the border color of a Card component in React Material UI? I attempted using the style property with borderColor: "red" but it did not work. Any suggestions on how to achieve this? ...

The $http service encounters an error while attempting to retrieve a JSON file from the server

When attempting to fetch a file from the server, I utilize the $http service in the following manner: $http({url: url, method: "GET", withCredentials: true}); For some mysterious reason, an exception is only thrown when trying to retrieve JSON files from ...

Discover the inner workings of the code below: set a variable called "start" to the current time using the new Date().getTime() method. Create a loop that continuously checks if

I'm having trouble understanding how this code snippet works. Can someone please provide a demonstration? Thanks in advance.... It seems that the code is subtracting 'start' from the current date with new Date, resulting in 0 which is less t ...

Sorting a function with two parameters in descending order is possible even when dealing with an empty array and no initial value for reduction

My npm test is not passing the third out of six tests. I have attempted to sort it using the following code snippet: sumAll.sort(function(min,max)) { return max - min; } However, this approach did not work. I also tried incorporating conditionals in t ...

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...