演示:https://codesandbox.io/s/23959y5wnp
所以我要传递一个函数,并想重新绑定<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
,所以我在函数上使用了this
,但是返回的数据仍然基于原始组件。我想念什么?
预期: .bind(this)
应该在按钮单击时打印出Test2
代码:
App.vue
Test2
Test1.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>
Test2.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>
答案 0 :(得分:3)
初始化期间binds the component's methods和functions cannot be bound more than once(随后的绑定均无效)已经提示。
因此,初始化App
时,Vue会将App
实例绑定为其dontPassThis
方法的上下文。 App
通过道具“传递” dontPassThis
到Test2
,Test2
随后尝试绑定,实际上什么也没做。