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

Integrate CSS and JavaScript files into Node Express

I am facing an issue including my CSS file and JavaScript file in a node-express application, as I keep getting a 404 not found error. Here is the code snippet that I am using: 1. In server.js var http = require('http'); var app = require(' ...

Tips for applying multiple style properties to an element using JavaScript

I have been experimenting with different versions of this code in an attempt to modify a specific element for a coding challenge, but none of them seem to successfully change multiple styling properties of the element upon clicking on a button. Would great ...

The issue of AFrame content failing to display on Google Chrome when used with hyperHTML

There seems to be an issue with A-Frame content not rendering on Chrome, despite working fine on FireFox and Safari. According to the demonstration on CodePen here, const { hyper, wire } = hyperHTML; class Box extends hyper.Component { render() { retu ...

How can we integrate fixed-data-table-2 sorting with an existing redux store?

Any help or advice you can offer would be greatly appreciated. I am still fairly new to using react. I recently took on a project for a client that was already in progress, and everything has been going smoothly up until now. I've come across a stumb ...

What is the process for setting up a vertical carousel in Bootstrap 5 with a stationary previous image?

Looking for assistance with my vertical carousel project. Is there a way to create a vertical carousel in bootstrap 5 with the previous image fixed? I found a slider on this website: zara.com/jp/en/ I want to maintain the previous image in a fixed posit ...

Exploring the properties of a file directory

As I try to access the d attribute of a path that was generated using Javascript, the output of printing the path element appears as follows: path class=​"coastline" d="M641.2565741281438,207.45837080935186L640.7046722156485,207.0278378856494L640.698 ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...

including a personalized class to the div container

I have a unique component where data is passed to render specific CSS styles. Example: <title :profile="true" :class="true"/> Within my custom component, there is a div element like this: <div class="tabletitle"> ...

Instead of using a hardcoded value, opt for event.target.name when updating the state in a nested array

When working with a dynamically added nested array in my state, I encounter the challenge of not knowing the key/name of the array. This lack of knowledge makes it difficult to add, update, iterate, or remove items within the array. The problem lies in fun ...

In need of changing the date format post splitting

I need help converting a date from MM/DD/YY to YYYYMMDD The current code I have is giving me an incorrect output of 2211. How can I implement a check on the Month and Day values to add a leading zero when necessary? var arr = '1/1/22'; arr = NTE ...

What is the best way to include an API key in the response to an Angular client application?

I'm working on transferring my API key from NodeJS to an Angular client application using $http, but I am unclear on the approach. Below is a snippet from my NodeJS file: // http://api.openweathermap.org/data/2.5/weather var express = require(' ...

Tips on retrieving the text content of an HTML element using its tag

Is there a way to retrieve the selected text along with its HTML tags using window.getSelection()? When using window.getSelection(), it only returns plain text such as HELLO. However, I need the text with the HTML tag included, like this <b>Hello< ...

Guide to comparing the contents of two text fields and highlighting the altered characters using ReactJS

Is there a way to compare the contents of two Material-UI textfields and identify the characters that have changed in both? I came across a similar question, but it was specifically for ReactJS rather than C# Windows Forms: How can you highlight the chara ...

What are the best ways to prioritize custom events over ng-click events?

Recently, I developed a web application using AngularJS. One of the features I included was an input text box with a custom ng-on-blur event handler. Due to some issues with ng-blur, I decided to create my own custom directive called ngOnBlur. Here's ...

Supplier for a module relying on data received from the server

My current component relies on "MAT_DATE_FORMATS", but I am encountering an issue where the "useValue" needs to be retrieved from the server. Is there a way to make the provider asynchronous in this case? export const MY_FORMATS = { parse: { d ...

Is it possible to manipulate a parent component's state with a child component?

I have been experimenting with Material UI's react modal to create a modal as my child component. In the parent component, I have set up a state that controls the visibility of the modal and added a button inside the modal to close it. However, this s ...

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

Access the CSV file using Office365 Excel via a scripting tool

Objective I want to open a CSV file using Office365's Excel without actually saving the file on the client's machine. Challenge The issue with saving raw data on the client's machine is that it leads to clutter with old Excel files accumu ...

What is the best method for ensuring image orientation is displayed correctly?

When utilizing multer node and express for uploading images to my application, I've noticed that some of the images appear rotated 90 degrees once they reach the client side. What could be causing this issue, and how can I resolve it? Just to clarif ...

Organizing checkboxes to store selected values in an array using Vue.js

I am looking to implement a feature where a user can select checkboxes from a grouped list populated by an API call. When a checkbox is selected, I want to add the corresponding object to an array linked to the v-model of the checkbox input. Below are the ...