vuejs - .bind(this) 没有按预期工作

A. *_*Lau 2 javascript vue.js vuejs2

演示:https : //codesandbox.io/s/23959y5wnp

所以我传递了一个函数并想重新绑定this所以我.bind(this)在函数上使用的,但返回的数据仍然基于原始组件。我错过了什么?

预期: Test2应该Test2在按钮点击时打印出来

代码:

应用程序

<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>
Run Code Online (Sandbox Code Playgroud)

测试1.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>
Run Code Online (Sandbox Code Playgroud)

测试2.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>
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 6

Vue在初始化的时候已经绑定了组件的方法函数不能被多次绑定(后续的绑定没有效果)。

所以在App初始化时,Vue 将App实例绑定为其dontPassThis方法的上下文。App“传递”dontPassThisTest2通过一个道具,该道具Test2随后尝试绑定,实际上什么都不做。