繁体   English   中英

vueJS - 在回调函数中使用“this”

[英]vueJS - Using 'this' in a callback function

编辑---解决了

事实证明,这并不是真正的问题,Vue 会为您自动绑定,因此无需手动绑定。

结束编辑---

我正在尝试将方法传递给子组件的回调(或事件)。
一切都很好,除了function在错误的上下文中执行。

在反应中,我会在constructor functions中绑定functions ,我不确定Vue的解决方案是什么。

例子

<template>
  <div id="app">
    <Header/>
    <Tasks 
    :todos="todos"
    @onMarkAsDone="markAsDone"
    >
    </Tasks>
  </div>
</template>

<script>
import Header from './components/Header.vue';
import Tasks from './components/Tasks.vue';

export default {
  name: 'my-component',
  data() {
    return {
      name: 'Tasks',
      todos: [{
        id:0,
        text:'Complete this by lunch',
        isDone: false
      }]
    }
  },
  methods: {
    markAsDone(id) {
      console.log(this); // refers to the child component
      // can't access this.todos
    }
  },
  components: {
    Tasks,
    Header
  }
}
</script>

这是它的解决方案,事实证明您可以使用“创建”生命周期钩子,这类似于在构造函数中绑定时的反应

<template>
  <div id="app">
    <Header/>
    <Tasks 
    :todos="todos"
    @onMarkAsDone="markAsDone"
    >
    </Tasks>
  </div>
</template>

<script>
import Header from './components/Header.vue';
import Tasks from './components/Tasks.vue';

export default {
  name: 'my-component',
  data() {
    return {
      name: 'Tasks',
      todos: [{
        id:0,
        text:'Complete this by lunch',
        isDone: false
      }]
    }
  },
  methods: {
    markAsDone(id) {
      console.log(this.todos); // can now access the correct 'this'
    }
  },
  created() {
    this.markAsDone = this.markAsDone.bind(this);
  },
  components: {
    Tasks,
    Header
  }
}
</script>

子组件代码

<template>
  <ul>
    <li 
      :class="{isDone:todo.isDone}"
      :key="todo.id" 
      v-for="todo in todos">
      <input type='checkbox' @change="markAsDone(todo.id)"/>
       {{todo.text}}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'Tasks',
  props: ['todos'],
  methods: {
    markAsDone(id) {
      this.$emit('onMarkAsDone', id);
    } 
  }
}
</script>

您可以在markAsDone方法中返回函数,如下所示:

markAsDone() {
  return id => {
    console.log(this.todos);
  }
},

然后在将方法作为道具传递时调用它:

:onMarkAsDone="markAsDone()"

然后你可以在你的子组件中调用 prop 方法。

这应该为您提供所需的功能,而无需在created()挂钩中使用bind

暂无
暂无

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

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