Troubleshooting Vue.js: Why is .bind(this) not behaving as anticipated?

Demo: https://codesandbox.io/s/23959y5wnp

I have a function being passed down and I'm trying to rebind the this by using .bind(this) on the function. However, the data that is returned still refers to the original component. What could I be missing here?

Expected: Test2 should display Test2 when the button is clicked

Code:

App.vue

<template>
  <div id="app">
    <img width="25%" src="./assets/logo.png" /><br />
    <Test1 :aFunction="passThis" /> <Test2 :aFunction="dontPassThis" />
  </div>
</template>

<script>
import Test1 from "./components/Test1";
import Test2 from "./components/Test2";

export default {
  name: "App",
  components: {
    Test1,
    Test2
  },
  data() {
    return {
      value: "original"
    };
  },
  methods: {
    dontPassThis($_) {
      console.log(this.value);
    },
    passThis($_) {
      console.log($_.value);
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Test1.vue

<template>
  <div>Test1 <button @click="() => aFunction(this)">click me</button></div>
</template>

<script>
export default {
  data() {
    return {
      value: "Test1"
    };
  },
  mounted() {
    this.aFunction(this);
  },
  props: {
    aFunction: {
      required: true,
      type: Function
    }
  }
};
</script>

Test2.vue

<template>
  <div>
    Test2

    <button @click="testFunction">click me</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      testFunction: null,
      value: "Test2"
    };
  },
  created() {
    this.testFunction = this.aFunction.bind(this);
  },
  props: {
    aFunction: {
      required: true,
      type: Function
    }
  }
};
</script>

Answer №1

Upon Vue's initialization, the component's methods are already bound, and it is not possible to bind them again (any subsequent attempts have no impact). This can be seen in Vue's source code as well as on StackOverflow.

When App is first initialized, its instance is bound as the context for the dontPassThis method within itself. The attempt to pass this method from App to Test2 via a prop, only results in an inconsequential additional binding that serves no practical purpose.

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

An error occurred while trying to update with Webpack Dev Server: [HMR] Update failed due to an issue fetching the update manifest,

I encountered an issue in the browser console while attempting to live reload / HMR on Webpack. The error arises after saving a file following a change. [HMR] Update failed: Error: Failed to fetch update manifest Internal Server Error Could the failure b ...

Using useState props in React Native navigation screens with React Navigation

I'm currently working on my first React Native app with react navigation after previously having a background in web react development. In the past, I typically used useState for managing state. For instance, rendering a list of components based on d ...

The value of req.session.returnTo is not defined

I have implemented passport for user authentication using discord oauth2. I want the users to be redirected back to the original page they came from instead of being directed to the home page or a dashboard. Even though I tried saving the URL in the sessi ...

The alert function is not being triggered upon receiving a JSON response

I am having trouble with an alert not firing a json response. The response appears in firebug, but after upgrading from php4.4.7 to php5.3.5, I encountered this error. It could be my mistake as well. Could someone please review my code and point out where ...

Update the referenced lists in ng-admin

I'm currently working with ng-admin alongside a restful API, I have various referenced lists that undergo frequent updates from the server side. Is there a method to automatically refresh these referenced lists every 5 seconds using ng-admin? EDIT: ...

transfer the output from the second selection to the adjacent div

I am utilizing a library called select2 specifically for single choice scenarios. My goal is to transfer the selected option to a different div once it has been chosen. Here is the code I have so far: https://jsfiddle.net/hxe7wr65/ Is there a way to ach ...

Explore the routing capabilities of the HERE Maps JS API, including features for ABR and height

Recently, I've encountered an issue with the HERE maps JS API routing feature. Specifically, I'm attempting to add restrictions based on factors like height or weight. Despite my efforts, it seems to be disregarding these restrictions. Additional ...

Combining a 3D array into a 2D array with the addition of HTML tags around each value using JavaScript

3D array // Array var x = { "letter": [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ], "line": [ { "data": [ 306, 830, 377, 651, 547, 369, 300, 148, 494 ] }, { "data": [ 88, 339, 298, 87, 96, 108, 93, 182, 64 ] }, { "data": [ 3157, 2943, ...

Struggling to separate a section of the array

Check out this array: [ '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a171319121b1f163a1f1915080a54191517">[email protected]</a>:qnyynf', '<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Establishing Accessor and Mutator Methods

The variables startStopA... and InitialValueA... that were originally in the component TableFields.vue need to be relocated to the store file index.js. However, upon moving them to the store, an error appears stating that setters are not set. I have extens ...

Issue while rendering Vuex

Currently in the process of setting up a project using Vuex and Vue, I have encountered a peculiar issue. It seems to be related to the order of rendering, but despite multiple attempts to modify the code, the problem persists. My approach involved access ...

Display streaming data continuously within an HTML page using Angular 16

Currently, I am actively developing a stream API that receives data with a 'Content-Type' of 'text/event-stream'. Below is a snippet from my stream.service.ts: connectToSse(): Observable<any> { return new Observable((observer ...

What is the best method for generating a vertical tab using JavaScript in a paragraph format?

Struggling to create a menu similar to this using bootstrap 4. Despite my efforts, I keep encountering various issues. Is there someone who can help me solve this problem? Remember, I am using bootstrap 4. Here is a demo: <!doctype html> <html ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

Experience the power of VueRouter with the advanced Vue Cypress Component Test Runner

I integrated the Cypress Vue Component Test runner into my existing Vue (Vite) app. However, upon running the test, I encountered an error stating that the $route in my component is undefined. Do you have any insights on what might be missing from my compo ...

What are the steps for configuring a dynamic variable?

One issue I encountered was setting up a variable in vue that updates when the screen orientation changes. Despite adding this variable to the data object, it did not become reactive as expected. This is my initial data function for the component: data() ...

What is the best way to save the various canvas images within a division as a single png file?

Hey there, I currently have a setup with multiple canvas elements within a main division structured like this: <div id="main"> <canvas id="one"> <canvas id="two"> <div id="main_2"> <canvas id="three"> </div ...

Looking to update the location of an element within a canvas using Vue and socket.io?

I am currently developing a 2D pong game using vue.js and socket.io. At the moment, I have a black rectangle displayed in a canvas. My goal is to make this rectangle move following the cursor of my mouse. The issue I am facing is that although my console l ...

Ensuring the consistency of actions through thorough testing

Currently utilizing xstate for the implementation of a login flow. Within my machine, the initialState triggers a Promise, which redirects to a state with an entry action if rejected. I am seeking to properly test the timing of when this action is called. ...