简体   繁体   English

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

[英]vuejs - .bind(this) not working as expected

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

So I'm passing down a function and would like to rebind the this so I used .bind(this) on the function, yet the data returned is still based on the original component. 所以我传递了一个函数,并希望重新绑定this所以我在函数上使用了.bind(this) ,但返回的数据仍然基于原始组件。 What am I missing? 我错过了什么?

Expected: Test2 should print out Test2 on button click 预期: Test2应该在按钮点击时打印出Test2

Code: 码:

App.vue 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 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 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>

Vue already binds the component's methods during initialization, and functions cannot be bound more than once (subsequent binds have no effect). Vue在初始化期间已经绑定了组件的方法 ,并且函数不能被绑定多次 (后续绑定没有效果)。

So when App is initialized, Vue binds the App instance as the context of its dontPassThis method. 因此,当初始化App时,Vue将App实例绑定为其dontPassThis方法的上下文。 App "passes" dontPassThis to Test2 via a prop, which Test2 subsequently tries to bind, which actually does nothing. App通过prop“传递” dontPassThisTest2Test2随后尝试绑定,实际上什么也没做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM