通常,当您在 vanilla JS 中的按钮上注册事件侦听器时,如果您传递使用“this”关键字的回调函数并且它不是箭头函数,则当该函数被执行时,“this”将引用按钮元素并你必须使用 .bind() 方法来克服这个问题。但是当你将一个像“props”这样的回调函数从父组件传递给子组件,并在那里使用它,并且该函数也使用“this”关键字时,为什么子组件中的“this”引用了父 vue 实例而不是子 vue 实例?vue 是否在幕后使用了一些绑定?谁能解释一下?我有本教程,其中有父组件和子组件以及道具的用例,道具是使用“this”的回调函数:
// Parent component
<template>
<div class="component">
<h1>The User Component</h1>
<p>I'm an awesome User!</p>
<button @click="changeName">Change my Name</button>
<p>Name is {{ name }}</p>
<p>Age is {{ age }}</p>
<hr />
<div class="row">
<div class="col-xs-12 col-sm-6">
<app-user-detail
:myName="name"
@nameWasReset="name = $event"
:resetFn="resetName"
:userAge="age"
></app-user-detail>
</div>
<button id="buton">Buton</button>
<div class="col-xs-12 col-sm-6">
<app-user-edit :userAge="age" @ageWasEdited="age = $event"></app-user-edit>
</div>
</div>
</div>
</template>
<script>
import UserDetail from "./UserDetail.vue";
import UserEdit from "./UserEdit.vue";
export default {
data: function() {
return {
name: "Max",
age: 27
};
},
methods: {
changeName() {
this.name = "Anna";
},
resetName() {
console.log(this);
this.name = "Max";
}
},
components: {
appUserDetail: UserDetail,
appUserEdit: UserEdit
},
mounted() {
document.getElementById("buton").addEventListener("click", this.resetName);
}
};
</script>
<style scoped>
div {
background-color: lightblue;
}
</style>
// Child component
<template>
<div class="component">
<h3>You may view the User Details here</h3>
<p>Many Details</p>
<p>User Name: {{ switchName() }}</p>
<p>User Age: {{ userAge }}</p>
<button @click="resetName">Reset Name</button>
<button @click="resetFn()">Reset Name</button>
</div>
</template>
<script>
import { eventBus } from "../main";
export default {
props: {
myName: {
type: String
},
resetFn: Function,
userAge: Number
},
methods: {
switchName() {
return this.myName
.split("")
.reverse()
.join("");
},
resetName() {
this.myName = "Max";
this.$emit("nameWasReset", this.myName);
}
},
created() {
eventBus.$on("ageWasEdited", age => {
this.userAge = age;
});
}
};
</script>