Демо: https://codesandbox.io/s/23959y5wnp
Итак, я пропускаю функцию и хотел бы перепривязать this
, чтобы я использовал .bind(this)
для функции, но возвращаемые данные все еще основаны наоригинальный компонент.Чего мне не хватает?
Ожидается: Test2
должен распечатать Test2
при нажатии кнопки
Код:
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>