通过道具和“ this”的Vue回调

问题描述 投票:0回答:1

[通常,当您在香草JS中的按钮上注册事件监听器时,如果传递的回调函数使用“ this”关键字而不是箭头函数,则在执行该函数时,“ this”将引用该按钮元素,则必须使用.bind()方法来克服这一点。但是,当您将诸如“ props”之类的回调函数从父组件传递到子组件并在其中使用它时,该函数也使用“ this”关键字,为什么子组件中的“ this”具有对父vue实例而不是子vue实例? vue是否在后台使用了某些绑定?谁能解释?我在本教程中有一个父级和一个子级组件,以及一个prop的用例,它是一个使用“ 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>
javascript vue.js callback this vue-props
1个回答
0
投票

在Vue中对props所做的所有工作都将它们传递下来并将它们附加到Child组件实例。

© www.soinside.com 2019 - 2024. All rights reserved.