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>