【问题标题】:vuejs - .bind(this) not working as expectedvuejs - .bind(this) 没有按预期工作
【发布时间】:2019-07-18 04:08:18
【问题描述】:

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

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

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

代码:

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

<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

<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>

【问题讨论】:

  • testFunction 不是导出对象的属性。 testFunction 是从导出对象中的data 函数返回的对象..
  • @guest271314 for Test2.vue 我也尝试将@click 更改为() =&gt; aFunction.bind(this)()。但它仍然打印出“原始”
  • 没试过vue.js。 data 函数在哪里调用?
  • @guest271314 该数据函数只是设置了组件,以便可以通过this.X访问返回对象中的变量
  • 为什么有两个不同的导出对象具有同名的属性"data"

标签: javascript vue.js vuejs2


【解决方案1】:

Vue 在初始化期间已经binds the component's methods,并且functions cannot be bound more than once(后续绑定无效)。

所以当App被初始化时,Vue将App实例绑定为其dontPassThis方法的上下文。 App 通过一个 prop“传递”dontPassThisTest2Test2 随后尝试绑定,但实际上什么也没做。

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2021-01-27
    • 2021-10-19
    • 2020-03-18
    相关资源
    最近更新 更多