【发布时间】:2019-07-18 04:08:18
【问题描述】:
演示: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>
【问题讨论】:
-
testFunction不是导出对象的属性。testFunction是从导出对象中的data函数返回的对象.. -
@guest271314 for
Test2.vue我也尝试将@click更改为() => aFunction.bind(this)()。但它仍然打印出“原始” -
没试过vue.js。
data函数在哪里调用? -
@guest271314 该数据函数只是设置了组件,以便可以通过
this.X访问返回对象中的变量 -
为什么有两个不同的导出对象具有同名的属性
"data"?
标签: javascript vue.js vuejs2