vm.property compared to this.property

Although it may seem like a simple question, I am in need of some clarification. Currently, I have vuejs running on a single page of my website. The vm app is running in the footer script of the page without utilizing an app.js file or templates/components.

When inside one of my vue methods, everything works perfectly fine:

newContainer(){
   this.attribute = 'value'; //this works!
}

However, when using axios and within its functions, I noticed that I have to approach it differently:

axios.post('my/route', {
        attribute: this.attribute //this works
    }).then(function (response) {
        vm.attribute = 'value'; //this works
        this.attribute = 'value'; //this does not work
    });

I understand that this issue could possibly be due to it being within a function where this.attribute does not work while vm.attribute does work. My question is why does this happen and if there is a better way to handle it?

Answer №1

Upon executing the code snippet provided, you will be able to view the following outcomes:

export default{
    data(){
        return{
            title:"Form Register",
            formdata:{},
            message:"",
            success:0,
        }
    },
    methods:{
       register(){
            this.axios.post("http://localhost:8888/form-register",this.formdata).then((response) => {
                   console.log(response);
                   if(response.data.success>0){
                       this.message="You register success";
                       this.success=response.data.success;
                   }
                   else{
                       this.message="Register to failed";
                       this.success=response.data.success;
                   }
              });
                
        },

    }
}

Answer №2

When utilizing arrow functions such as () => {...}, the current context is bound. This means that this will correctly refer to the intended context. Therefore, using arrow functions instead of function() {...} in cases where the context is not explicitly bound will result in proper functionality.

For example:

.then(response => {this.attribute = 'value'}

Answer №3

Developers often face a common stumbling block when working with axios functions. The issue arises because the code inside an axios function is out of scope of the object containing the axios method call. This can be better understood by comparing the original code block to the revised version below:

 var vm = {
      function doWork(){
        axios.post('my/route', {
              attribute: this.attribute //this works
        }).then(function (response) {
              vm.attribute = 'value'; //this works
              this.attribute = 'value'; //this does not work
         });
      }
 }

This rewritten version is essentially equivalent to:

 var vm = {
      function doWork(){
          axios.post('my/route', {
                attribute: this.attribute //this works
           }).then(followOnWork(response));
      }
 }

 function followOnWork(response){
      vm.attribute = 'value'; //this works
      this.attribute = 'value'; //this does not work
 }

In the refactored code, it's evident that followOnWork runs independently of the vm object. Therefore, any reference to a this variable in followOnWork does not correspond to the vm object. On the other hand, vm represents the actual name of the object and can be accessed from anywhere using the vm variable once the object is created.

To address this "out of scope" issue, you can utilize an arrow function (as suggested by @MakarovSergey) if ES6 is compatible with your setup.

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

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

The issues of cross-origin domains arise when utilizing iframes with src links originating from the server side

Encountering a cross-origin domain issue, receiving the following error while working with an iframe: candidateInterviewCtrl.js:39 Uncaught SecurityError: Blocked a frame with origin "http://localhost:9000" from accessing a frame with origin "http://local ...

Retrieving PHP variable within a JavaScript file

I have a PHP script running on my server that tracks the number of files in a specific directory. I want to retrieve this file count ($fileCount) in my JavaScript code. numberOfImages.php: <?php $dir = "/my/directory/"; $fi = new FilesystemIterator($d ...

Tips for hiding a popover in Angular when clicking outside of it

In a demo I created, rows are dynamically added when the user presses an "Add" button and fills in a name in an input field. Upon clicking "OK," a row is generated with a Star icon that should display a popover when clicked. While I have successfully imple ...

Utilizing the HTML button element within an ASP file combined with JavaScript can lead to the reloading of the

I am attempting to create a JavaScript function for an HTML button element. However, I have noticed that it causes the page to reload. Strangely, when I use an input with a button type, everything works perfectly. What could be causing this issue and why a ...

Looking for a way to sort through data using the current time as a filter

In my possession is an object presented below: const user = { id: 3, name: "Clark Kent", mobileNumber: "1234567892", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385d40595548545d674d4b ...

What is the best way to organize components in Vue.js?

Currently, I am facing a situation in my Vue router where most of the routes are structured like this: { path: '/somepath', name: 'SomeName', components:{ componentA: componentA, componentB: com ...

Pressing "Enter" initiates the submission of the form

My webpage contains a stylish GIF displayed as a button within a div. The script inside the div triggers a click event when the ENTER key is pressed, using $(this).click(). This click action has its own functionality. Everything functions smoothly in Fire ...

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

Guide on integrating AJAX with servlets and JSP for database-driven applications

What is the best way to integrate AJAX technology with servlets and JSP for a database application? I am currently developing a JSP page that makes calls to JavaScript. The JavaScript then calls a servlet where the database is accessed. How can I pass th ...

In JavaScript, when using the fetch function with JSON, it is possible to skip the

Here's an example of fetching review data from within a 'for loop': fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline') In this case, some products may not have reviews and will return a 404 response. Th ...

Customize Vuetify theme colors with your own unique color palette

Attempting to override certain classes src/plugins/vuetify.js import Vue from "vue" import Vuetify from "vuetify/lib/framework" Vue.use(Vuetify) export default new Vuetify({ theme: { primary: "#4BB7E8", ...

A comprehensive guide on how to find keywords within an array and then proceed to make all text within the parent div tag stand

I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script ...

Troubleshooting issues with JavaScript events in order to effectively implement popovers

I am facing an issue on a webpage that contains a significant amount of JavaScript. The Twitter bootstrap's popover widget is not functioning as expected. Specifically, when I hover over the icon that should trigger the "popover," nothing happens. I h ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

How can I fix the 'Null is not an object' error that occurs while trying to assess the RNRandomBytes.seed function?

Currently, I am in the process of creating a mobile application using expo and react-native. One of the features I am working on involves generating a passphrase for users on a specific screen. To achieve this task, I have integrated the react-native-bip39 ...

How can I retrieve variables from App.vue and use them in other components within Vue?

I've developed an app in Vue.js and I have a structure like this in my App.vue file: <template> <div id="app"> <router-view/> </div> </template> <script> export default { name: 'App', ...

Experiencing a 400 error while transitioning from ajax to $http?

I am facing an issue while trying to make a GET request using $http instead of ajax. The call functions perfectly with ajax, but when attempting the same with $http, I encounter a 400 (Bad Request) error. I have referenced the Angular documentation and bel ...

After the installation of Windows 10 and the latest version of NodeJS, Gatsby seems to be

The gatsby project I set up following the official website instructions seems to be malfunctioning. NodeJS version: v16.15.0, npm version: 8.8.0, gatsby version: 4.13.0, gatsby CLI version: 4.13.0 C:\Users\Dell\Desktop\New folder&bsol ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...