Javascript vuejs-.bind(此)未按预期工作
演示: 因此,我正在传递一个函数,并希望重新绑定Javascript vuejs-.bind(此)未按预期工作,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,演示: 因此,我正在传递一个函数,并希望重新绑定this,因此我在函数上使用了.bind(this),但返回的数据仍然基于原始组件。我错过了什么 预期:Test2应在单击按钮时打印出Test2 代码: App.vue 从“/components/Test1”导入Test1; 从“/components/Test2”导入Test2; 导出默认值{ 名称:“应用程序”, 组成部分:{ 测试1, 测试2 }, 数据(){ 返回{ 价值:“原创” }; }, 方法:{ 不要跳过此($\uu1){ c
this
,因此我在函数上使用了.bind(this)
,但返回的数据仍然基于原始组件。我错过了什么
预期:Test2
应在单击按钮时打印出Test2
代码:
App.vue
从“/components/Test1”导入Test1;
从“/components/Test2”导入Test2;
导出默认值{
名称:“应用程序”,
组成部分:{
测试1,
测试2
},
数据(){
返回{
价值:“原创”
};
},
方法:{
不要跳过此($\uu1){
console.log(this.value);
},
passThis($\ux){
console.log($\ 0.value);
}
}
};
#应用程序{
字体系列:“Avenir”,Helvetica,Arial,无衬线;
-webkit字体平滑:抗锯齿;
-moz osx字体平滑:灰度;
文本对齐:居中;
颜色:#2c3e50;
边缘顶部:60像素;
}
Test1.vue
测试1单击我
导出默认值{
数据(){
返回{
值:“Test1”
};
},
安装的(){
this.a函数(this);
},
道具:{
A功能:{
要求:正确,
类型:功能
}
}
};
Test2.vue
测试2
点击我
导出默认值{
数据(){
返回{
testFunction:null,
值:“Test2”
};
},
创建(){
this.testFunction=this.affunction.bind(this);
},
道具:{
A功能:{
要求:正确,
类型:功能
}
}
};
Vue已在初始化过程中,并且(后续绑定无效)
因此,当初始化
App
时,Vue将App
实例绑定为其dontPassThis
方法的上下文App
“通过一个道具将”dontPassThis
传递给Test2
,该道具随后尝试绑定,但实际上什么也不做。testFunction
不是导出对象的属性testFunction
是从导出对象中的data
函数返回的对象。@guest271314 forTest2.vue
我还尝试将@单击
更改为()=>affunction.bind(this)(
)。但它仍然打印出“原件”,但没有尝试vue.js。名为“@guest271314”的data
函数在哪里?该数据函数只是设置组件,以便通过this.X
可以访问返回对象中的变量。为什么有两个不同的导出对象具有相同名称的属性“data”
?
<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>
<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>
<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>